【问题标题】:Is there a way to update the aliases of a bot discord command?有没有办法更新 bot discord 命令的别名?
【发布时间】:2021-04-13 04:27:35
【问题描述】:

我有一个发送文本 copypasta 的命令

示例copypasta.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,机器人会发送 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 时,机器人找不到它,我需要重新启动机器人以便更新命令的“别名”变量。

是否可以在不重新启动机器人的情况下更新命令别名?

【问题讨论】:

    标签: python discord.py bots


    【解决方案1】:

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

    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")
    

    【讨论】:

    • 很好的解决方案,它奏效了。非常感谢兄弟。
    猜你喜欢
    • 2021-11-10
    • 2022-01-04
    • 2018-08-15
    • 2022-07-12
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 2023-01-22
    相关资源
    最近更新 更多