【问题标题】:Discord.py variables not constant throughout the codeDiscord.py 变量在整个代码中不是恒定的
【发布时间】: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


【解决方案1】:

您的代码在很多地方对我来说毫无意义,因为您在 message 事件中使用了 ctx,这起初是不可能的。另外,在复制代码时,prefixes = prefix 出现错误,因此值得怀疑的是为什么这对您有效。

您的on_guild_join 对我来说也毫无意义,因为每个人都有默认前缀。该事件可能与您的changeprefix 命令相关,但可以做得更好。

我稍微重写了您的changeprefix 命令并调整了您的on_message 事件。

看看下面的代码:

@bot.event
async def on_message(message):
    if message.content.startswith("What is the prefix for this guild?"):
        with open('prefix.json', 'r', encoding='utf-8') as fp:
            custom_prefixes = json.load(fp)
        try:
            prefix = custom_prefixes[f"{message.guild.id}"] 
            await message.channel.send(f'Hi my prefix for this server is **{prefix}**')
        except KeyError:
            return await message.channel.send("You have not set a new prefix.") # No JSON entry

    await bot.process_commands(message)


@bot.command()
async def setprefix(ctx, prefixes: str):
    with open('prefix.json', 'r', encoding='utf-8') as fp:
        custom_prefixes = json.load(fp)

    try:
        custom_prefixes[f"{ctx.guild.id}"] = prefixes # If the guild.id already exists
    except KeyError: # If there is no JSON entry
        new = {ctx.guild.id: prefixes} # New prefix with command input
        custom_prefixes.update(new) # Add guild.id and prefix

    await ctx.send(f"Prefix set to: `{prefixes}`")

    with open('prefix.json', 'w', encoding='utf-8') as fpp:
        json.dump(custom_prefixes, fpp, indent=2)

由于您的on_guild_join 事件也包含错误,我们必须以不同的方式确定前缀。如果我们将集合 prefix 附加到默认集合,我们可以实现这一点。

看看下面的代码:

def determine_prefix(bot, msg):
    guild = msg.guild
    base = [DEFAULT_PREFIX]

    with open('prefix.json', 'r', encoding='utf-8') as fp: # Open the JSON
        custom_prefixes = json.load(fp) # Load the custom prefixes

    if guild: # If the guild exists
        try:
            prefix = custom_prefixes[f"{guild.id}"] # Get the prefix
            base.append(prefix) # Append the new prefix
        except KeyError:
            pass

    return base

[...](command.prefix = determine_prefix) # Where you defined your bot

【讨论】:

  • 那么 DEFAULT_PREFIX 是在哪里定义的?
猜你喜欢
  • 2022-01-26
  • 2016-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-03
  • 1970-01-01
  • 2016-05-08
相关资源
最近更新 更多