我正在开发一个 discord.py 机器人,但我遇到了一个我似乎无法解决的重大问题。我有两个具有几乎完全相同代码的命令,但一个不起作用。以下代码有效:
@bot.command(name = 'rees', aliases=['setup'])
async def rees(ctx, guild = None, updateddict = None):
#delete message
await ctx.message.delete()
guild = ctx.message.guild.id
if guild in data:
await ctx.send('this guild is already set up!')
elif guild not in data:
data[guild] = {'pogchampers' : 'false'}
print(data)
await ctx.send('guild is set up!')
with open('data.txt', 'w') as outfile:
json.dump(data, outfile)
await ctx.send('hello! my name is ehe! use ehehelppls to get a list of my commands!')
但是下面的代码给了我一个错误信息
@bot.event
async def on_guild_join(ctx, guild = None, updateddict = None):
print('guild joined')
guild = ctx.message.guild.id
if guild in data:
await print('recently joined guild is already set up!')
elif guild not in data:
data[guild] = {'pogchampers' : 'false'}
print(data)
await ctx.send('it is done master...')
with open('data.txt', 'w') as outfile:
json.dump(data, outfile)
await ctx.send('hello! my name is ehe! use ehehelppls to get a list of my commands!')
运行此代码时,会显示以下错误消息:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Reesj\OneDrive\Documents\GitHub\python_bot\bot_here\botcode.py", line 312, in on_guild_join
guild = ctx.message.guild.id
AttributeError: 'Guild' object has no attribute 'message'
知道为什么我只会在第二个代码块而不是第一个代码块中收到 guild = ctx.message.guild.id 的错误消息吗?
答案 0 :(得分:0)
您弄乱了 on_guild_join
event 的参数。 ctx
在您的情况下是一个 guild
对象,它当然没有属性 message
。您需要重写事件处理程序的代码以适应
@bot.event
async def on_guild_join(guild):
# do function
事件不是命令!他们已经设置了您可以使用的参数!也许看看event-reference