Search code examples
pythondiscord.pybots

Is there a way to update the aliases of a bot discord command?


I have a command that sends text copypasta

example copypasta.json:

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

Code to send the text:

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)

If i send -xxx in Discord, the bots sends the value in json "xxxx xxx..."

So I made a command to add a new element in 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")

But when I send in Discord the key of the new element added, the bot does not find it, I need to restart the bot so that the command's "aliases" variable is updated.

Is it possible to update the command aliases without restarting the bot?


Solution

  • It is possible, simply remove the command, update the aliases and add the command again, a handy function would be:

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

    To use it:

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