首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >自定义前缀discord.py重写

自定义前缀discord.py重写
EN

Stack Overflow用户
提问于 2020-12-27 00:48:47
回答 1查看 78关注 0票数 0

好吧,所以我太困惑了。当我执行我的命令"prefix“时,我得到了这个错误return prefixesstr(message.guild.id) KeyError:'server.id‘这是我得到的所有代码:

代码语言:javascript
复制
@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)

命令:

代码语言:javascript
复制
@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}"**')

还有这段代码:

代码语言:javascript
复制
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)

请帮帮我!

EN

回答 1

Stack Overflow用户

发布于 2021-03-09 23:49:45

nvm得到了答案:

代码语言:javascript
复制
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)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65458585

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档