如何在不传递上下文的情况下翻译命令。(不和谐机器人)

2024-03-29 11:37:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我在编一个不和谐机器人。在这里,您可以定义如下命令

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

这将创建一个命令hello,它将发送一条消息。你知道吗

现在我想给它添加翻译。在我的数据库中,我通过公会id存储每个公会的语言。公会id在ctx.guild.id中传递。我想要一个翻译函数来处理这个过程。我不想每次需要翻译的时候都通过公会id。我看到了一些使用ContextVars的方法。但我不知道它到底是怎么工作的。你知道吗

有人对如何处理这件事有什么建议吗? IdleRPG也集成了这一点,但非常复杂:https://github.com/Gelbpunkt/IdleRPG/blob/v4/utils/i18n.py

实际的翻译功能似乎不是问题所在。最后应该是这样的。你知道吗

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?

Tags: theto命令selfsendidhelloasync