0

I'm coding a Discord bot. There you define your commands like

@commands.command()
async def hello(self, ctx):
    await ctx.send("Hello world!")

This would create a command hello, which would send a message.

Now I want to add translations to it. In my database I store the language per guild via the guild id. The guild ID is passed in ctx.guild.id. I want have a translation function which handles the process. And I don't want to pass the guild id everytime I need to translate. I've seen some ways of doing this with ContextVars. But I don't know how it works exactly.

Does anyone have a suggestion on how to deal with it? IdleRPG has integrated this as well, but very complicated: https://github.com/Gelbpunkt/IdleRPG/blob/v4/utils/i18n.py

The actual translation function seems not to be the problem. In the end it should look something like this.

def _(self, text):
    # Do gettext stuff here (This is the part I know about)
    # Get the context without the need to pass it to the function (But how?)
    return translation

@commands.command()
async def hello(self, ctx):
    await ctx.send(_("Hello world")) # Auto pass ctx to _(), but how?
Spinne
  • 65
  • 1
  • 5
  • Is there a specific reason you do not want to pass `ctx.guild.id`? It would be easy to create a function that does a lookup for translation based on the `id` value passed. – Benjin Sep 05 '19 at 15:31
  • Creating a function which gets the language from the `id` isn't the problem. I don't want to pass it because it would cover over 20% of my code which is a way too much. As I've mentioned before, some devs have already found a solution for this, which I don't know about. – Spinne Sep 06 '19 at 21:29

0 Answers0