【发布时间】:2023-04-06 05:10:01
【问题描述】:
我目前正在使用 discord.py 开发一个机器人,在这种情况下使用 JSON 文件来存储它所在的每个服务器的机器人前缀。 (+ 是机器人的默认前缀) 使用前缀,我正在做 4 件事: 在公会加入时:向 JSON 文档添加前缀 On guild remove:从 JSON 文档中删除此公会的前缀 +更改前缀 当提到机器人时,它会输出一条消息,说明: '你好,这个服务器的前缀是+'
前 3 部分工作正常。但是,当提到该机器人时,它会输出错误:
await message.channel.send(f'Hi my prefix for this server is **{prefix}**)
NameError: name 'prefix' is not defined
我已经做了一些研究,并就这个问题询问了多个帮助服务器,但是我发现 python 没有在这种情况下有用的常量,帮助服务器上的人不确定这个问题的答案。
前缀设置的所有部分的代码是这样的:
@bot.event
async def on_guild_join(guild):
with open('prefix.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(guild.id)] = '+'
prefixes = prefix
with open('prefix.json', 'w') as f:
json.dump(prefixes, f, indent=4)
# REMOVES PREFIX FROM JSON FILE
@bot.event
async def on_guild_remove(guild):
with open('prefix.json', 'r') as f:
prefixes = json.load(f)
prefixes.pop(str(guild.id))
with open('prefix.json', 'w') as f:
json.dump(prefixes, f, indent=4)
# COMMAND TO CHANGE THE PREFIX
@bot.command()
@commands.has_permissions(manage_messages=True)
async def changeprefix(ctx, prefix):
with open('prefix.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = prefix
prefix = prefix
with open('prefix.json', 'w') as f:
json.dump(prefixes, f, indent=4)
await ctx.send(f'Prefix changed to **{prefix}**')
错误来自的on_message是这样的:
@bot.event
async def on_message(message):
if message.content.startswith("<@bot ID>"):
await message.channel.send(f'Hi my prefix for this server is **{prefix}**')
await bot.process_commands(message)
这在代码中比其他部分更靠后
任何帮助将不胜感激。 预期的输出是,当它标记的机器人时,它会发送一条消息,说明服务器的当前前缀。
更新
正如下面的评论中提到的,我已经更新了我的代码,以便它读取 JSON 文件并检索前缀。这是on_messageevent 中的更新代码
if message.content.startswith("<bot ID>"):
with open('prefix.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = prefix
await message.channel.send(f'Hi my prefix for this server is **{prefix}**')
但是,这仍然显示
NameError: name 'prefix' is not defined
我尝试过的其他方法
我还尝试像这样定义prefix:
if message.content.startswith("<@850794452364951554>"):
with open('prefix.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = prefix
prefix = prefix
await message.channel.send(f'Hi my prefix for this server is **{prefix}**')
我在prefixes[str(ctx.guild.id)] = prefix 行之前和之后都尝试了prefix = prefix 行
在这两种情况下,它都会输出以下错误:
UnboundLocalError: local variable 'prefix' referenced before assignment
【问题讨论】:
-
prefix必须被定义,错误说明了什么......仅仅因为你在另一个command中使用了它,你就不能在on_message事件中再次使用它。打开 JSON 文件,加载prefixes并显示它。 -
@Dominik 我刚刚尝试过这样做并用我尝试过的内容更新了问题,但是,我仍然遇到错误。
-
什么是
prefixes = prefix?给我一个错误 (prefix)。另外:如果机器人加入公会,为什么要添加前缀?我看不出有什么好处。 -
@Dominik
prefixes = prefix在出现错误时尝试定义前缀。我在公会加入时添加了前缀,以便机器人具有默认前缀,然后可以使用命令进行更改。这里没有设置默认前缀:bot = commands.Bot(command_prefix=get_prefix, intents=intents),它从 JSON 文件中检索前缀,所以我认为它需要在公会加入时添加前缀才能起作用。 -
我将编辑我的答案并添加另一种方法。
标签: python json variables discord.py bots