简体   繁体   中英

Discord bot - how to update a JSON file live without restarting program?

I have made a discord bot that acts as a translator ie the user can type '!translate word', and the bot will respond with a translation of that word, based on the values in a JSON file. This works fine.

However, I have some issues with another command which lets the user add new words to the JSON file. When the user does '!add word translation', it adds it to the JSON file fine and I can see it clearly in the file in my IDE, but then when I use the !translate command on the word I just added, the bot does not recognise it. It will recognise it when I terminate the program and run it again though. How do I get my bot to recognise the newly added words straight away? Since I want it to just run 24/7 on Heroku or something, and not have to constantly stop and start the program.

This is the code for the add command:

@client.command()
async def add(ctx, *message):
    """ User can add an emoji and its english translation to the dictionary.
        At the moment the program needs to be terminated and then restarted for the bot to translate the added words"""

    if len(message) != 2:
        await ctx.send("Incorrect format. Please try again in the format: !add {name} {emoji} \ne.g. '!add fire 🔥'")

    else:
        name = message[0]
        emoji = message[1]

        if not does_translation_exist(name):
            add_emoji(name, emoji)

            await ctx.send(name + " AKA " + emoji + " has been added to the dictionary!")
        else:
            stored_emoji = does_translation_exist(name)
            await ctx.send(name + " already exists in the dictionary as " + stored_emoji +
                           "\nIf you would like to update the translation, try the !update command (e.g. '!update fire 🔥')")

And then this is the code for the translate command:

@client.command()
async def translate(ctx, *message):
    """ user types '!translate' followed by a message, bot then replies with that message translated to emojis
        message argument a tuple e.g. if they message "hello there", message = ("hello", "there")
    """

    output = emojify(message)[0]
    unknown = emojify(message)[1]

    await ctx.send(output)

    if len(unknown):    # list isn't empty, there were unknown words
        await ctx.send("The following words do not currently have a translation: ")
        await ctx.send(unknown)
        await ctx.send("Consider adding them to the dictionary with the !add command, in the format {name} {emoji}" +
                       "\ne.g. '!add fire 🔥'")

I assume I have to have some code that does an update of what's in the JSON file before I run the translate command but I'm not sure how to do that and haven't found anything useful online in my search. Any help would be appreciated :)

If you'd also provide the contents of your "emojify" and "add_emoji" functions, it might be easier to answer, but my guess is: When starting the bot, you store the contents of your JSON file in some container, like a dictionary. Your "emojify" function looks at that container to translate input. When adding a new word, you only change the JSON but not the container where its content are stored. That means there are two options:

  1. Add a translation to the container as well, not only to the JSON file.
  2. Reload the data from the JSON file after adding something to it, just like your program does when starting.

You should probably reread the file every time a new change has been made.

I don't use discord.py specifically, so please spare me if I miss some rule with async python programming.

import json
def reloadJSON():
    with open("your_data.json", "r") as f: # Replace your_data with the file
        return json.loads(f.read())

# Now when you need to reload the file, just call this command like this:
# data = reloadJSON()
# And now, you have your json parsed and stored.

Note: This code is untested, as I cannot do so at this time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM