我是一个使用discord.py和使用aiosqlite作为水准数据库的机器人。有时候,当我启动我的机器人时,我会得到这个错误,我不知道是什么导致了这个错误。不是每次我启动机器人的时候都会发生这种事。我认为当我的机器人在启动过程中有人在服务器上发送消息时会发生这种情况吗?我不确定。
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Users\kouxi\Runa\cogs\leveling.py", line 27, in on_message
async with self.bot.db.cursor() as cursor:
AttributeError: 'Bot' object has no attribute 'db'
这是错误
#add xp on message and checking for leveling up
@commands.Cog.listener()
async def on_message(self, message):
if message.author.bot or message.guild is None:
return
author=message.author
guild=message.guild
async with self.bot.db.cursor() as cursor:
await cursor.execute('SELECT levelsys FROM levelSettings WHERE guild = ?',(guild.id,))
levelsys=await cursor.fetchone()
if levelsys and not levelsys[0]:
return
await cursor.execute('SELECT xp FROM levels WHERE user = ? AND guild = ?',(author.id,guild.id))
xp=await cursor.fetchone()
await cursor.execute('SELECT level FROM levels WHERE user = ? AND guild = ?',(author.id,guild.id))
level=await cursor.fetchone()
if not xp or not level:
await cursor.execute('INSERT INTO levels (level, xp, user, guild) VALUES (?,?,?,?)',(0,0, author.id, guild.id))
try:
xp=xp[0]
level=level[0]
except TypeError:
xp=0
level=0
if level < 5:
xp+=random.randint(1,3)
await cursor.execute('UPDATE levels SET xp = ? WHERE user = ? AND guild = ?',(xp,author.id,guild.id))
else:
rand=random.randint(1,(level//4))
if rand==1:
xp+=random.randint(1,3)
await cursor.execute('UPDATE levels SET xp = ? WHERE user = ? AND guild = ?',(xp,author.id,guild.id))
if xp >= 100:
level +=1
await cursor.execute("UPDATE levels SET level = ? WHERE user = ? AND guild = ?",(level,author.id,guild.id))
await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?",(0,author.id,guild.id))
await message.channel.send(f'{author.name} has leveled up to level {level}!')
await self.bot.db.commit()
这是代码块,在leveling.py下面的齿轮中。我在main.py文件中的on_ready()中包含了on_ready。谢谢!
发布于 2022-10-21 20:38:11
正如注释中所述,如果您想在机器人启动之前设置一些东西,则应该使用setup_hook
。
不过,您需要对机器人进行子类化:
# First you need to subclass your bot
class MyBot(commands.Bot):
# Use the init function to attach a variable to your bot
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.db = None
# And then define your setup_hook function
async def setup_hook(self):
if not self.db:
print("Setting up db..")
self.db = await aiosqlite.connect("level.db")
# And then you can use the class as a replacement for commands.Bot
bot = MyBot(command_prefix=..., intents=...)
https://stackoverflow.com/questions/74143738
复制相似问题