【问题标题】:Custom prefix discord.py rewrite自定义前缀 discord.py 重写
【发布时间】:2021-04-04 02:26:31
【问题描述】:

好吧,所以我很困惑。当我执行命令“前缀”时,出现此错误 返回前缀[str(message.guild.id)] KeyError:'server.id' 这是我得到的所有代码:

@client.event
async def on_guild_join(guild):
   with open('prefixes.json', 'r') as f:
       prefixes = json.load(f)

   prefixes[str(guild.id)] = ['s!', 'S!']
   with open('prefixes.json','w') as f:
       json.dump(prefixes, f, indent=4)
@client.event
async def on_guild_remove(guild):
   with open('prefixes.json', 'r') as f:
       prefixes = json.load(f)

   prefixes.pop(str(guild.id))

   prefixes[str(guild.id)] = ['s!', 'S!']
   with open('prefixes.json', 'w') as f:
       json.dump(prefixes, f, indent=4)

命令:

@client.command()
async def prefix(ctx, *, prefix):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)

    prefixes[str(ctx.guild.id)] = prefix
    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)
    await ctx.send(f'Prefix set to: **"{prefix}"**')

还有这段代码:

def get_prefix(client, message):
   with open('prefixes.json','r') as f:
       prefixes = json.load(f)

   return prefixes[str(message.guild.id)]

client = commands.Bot(command_prefix=get_prefix)

请帮帮我!

【问题讨论】:

  • 另外,我花了好几个小时才发布这个
  • 哦,是的,我也跟着 Lucas 的教程。

标签: discord.py-rewrite


【解决方案1】:

nvm 得到了答案:

def get_prefix(client, message):
    with open(....) as ...:
        prefixes = json.load(...)

    try: 
        # this will error if the guildid is not in the json
        return prefixes[str(message.guild.id)]
    except:
        # this code will run if the stuff in the if errors
        # here you need to add the guildid with your default prefix to the json
        # the code is pretty similar to what you have in your on_guild_join event, youll just need to change some stuff, like how to get the current guild

        # when you did that then do what you had in the try like this:
        # it shouldnt error now cause the guildid is now in the json 
        return prefixes[str(message.guild.id)]

感谢您的帮助 :D (lol)

【讨论】:

    猜你喜欢
    • 2021-03-31
    • 2021-11-01
    • 2021-04-04
    • 2020-12-31
    • 2021-03-30
    • 1970-01-01
    • 2019-04-12
    • 2021-07-19
    • 2020-12-18
    相关资源
    最近更新 更多