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?