有没有办法更新bot discord命令的别名?

2024-10-01 00:35:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个发送文本的命令

示例copypata.json:

{
    "xxx" : "xxxxxx xxxx xxxxx xxxxx...",
    "yyy" : "yyyyyy yyyy yyyyy yyyyy...",
    "zzz" : "zzzzzz zzzz zzzzz zzzzz..."
}

发送文本的代码:

json_file = 'copypasta.json'
with open(json_file) as json_data:
    jsonLoad = json.load(json_data)

aliases = list(jsonLoad.keys())

@client.command(aliases=aliases) #problem is here
async def _copypasta(ctx):

    keyCopypasta = ctx.invoked_with
    valueCopypasta = jsonLoad[keyCopypasta]

    await ctx.send(valueCopypasta)

如果我在Discord中发送-xxx,则bot会发送json“xxxx xxx…”中的值

因此,我发出了一个命令,在json中添加一个新元素:

async def addCopypasta(ctx, key, *, value):
    
    a_dictionary = {key: value}

    with open("copypasta.json", "r+") as file:
        data = json.load(file)
        data.update(a_dictionary)
        file.seek(0)
        json.dump(data, file)
    
    await ctx.send("successfully added")

但是当我在Discord中发送添加的新元素的键时,bot没有找到它,我需要重新启动bot,以便更新命令的“alias”变量

是否可以在不重新启动bot的情况下更新命令别名


Tags: 文本命令jsondatabotwithfilexxx
1条回答
网友
1楼 · 发布于 2024-10-01 00:35:18

可以只需删除命令、更新别名并再次添加命令,一个方便的功能是:

def update_aliases(command, *aliases):
    client.remove_command(command.name)
    command.aliases.extend(aliases)
    client.add_command(command)

要使用它:

@client.command()
async def foo(ctx):
    await ctx.send(foo.aliases)

@client.command()
async def update(ctx, alias: str):
    update_aliases(foo, alias) # I'm passing the function itself, not the name of the function
    await ctx.send("Done")

相关问题 更多 >