Package: discord-ext-i17n
APyCordextension for internationalization[!NOTE]Agentclass has been renamed asAutoI17nAgentbut the old name is still supportedKey FeaturesAutomatic text translations for messages, embedsetc..Zero code change necessaryFully customizableForward CompatibleThe extension is able to automatically translate all
specified objectshereinto any registered language
depending on the preferences of the destination channel or guild.
For instance, if a channel has the preference for Spanish, any messages, embeds etc.. that are being sent to the channel will be automatically translated into Spanish before it is sent.[!TIP]
Translations will carry over markdown!I've set the language to `English` 🏴󠁧󠁢󠁥󠁮󠁧󠁿!
+ He establecido el idioma en `Spanish` 🇪🇸!
+ ငါဘာသာစကားကိုထားတယ် `မြန်မာ (ဗမာ)` 🇲🇲!GoogleTranslated string in different languages with formatting maintainedCheck out theFAQ,Examplesandother feathersfor more information.
This extension is relatively new so please report any bugs atissues!Fields Covered by Automatic TranslationMessagesInteraction MessagesEmbedsButtonsSelectsModals(beta)Webhooks(beta)InstallingThis is an extension forPyCord. It is recommended that there exists an installation ofpy-cord>=2.0.0b5.To install this extension, run the following command:# Linux/macOS
python3 -m pip install -U discord-ext-i17n

# Windows
py -3 -m pip install -U discord-ext-i17nQuick ExampleRequired Steps:Define a language getter function decorated with theDetector.lang_getterdecorator
(this getter is called with an ID ofguilds / channelsto see if it has a
language preference)Instantiate adiscord.ext.i17n.AutoI17nAgentclass to configure and inject codeCreate a command for users to set preferencesfromtypingimportOptionalfromdiscordimportIntents,Bot,ApplicationContextfromdiscord.ext.i17nimportAutoI17nAgent,Language,Detectorintents=Intents.default()# not necessary for the extension, enabled for msg commandsintents.messages=Trueintents.message_content=Truebot=Bot(command_prefix="!",intents=intents,)bot.preferences={}bot.agent=AutoI17nAgent(translate_all=True)# This must be instantiated at least and only once@Detector.lang_getterasyncdefget_lang(id)->Optional[Language]:"""This decorated function will be called internally to get Languagepreferences."""returnbot.preferences.get(id,None)@bot.slash_command(name="lang")asyncdefset_lang(ctx:ApplicationContext,lang_code:str):"""Set the language for the bot in the current channel."""lang=Language.from_code(lang_code)iflangisNone:returnawaitctx.respond("Bad language code!")eliflangisLanguage.English:ifctx.channel.idinbot.preferences:bot.preferences.pop(ctx.channel.id)else:bot.preferences[ctx.channel.id]=langawaitctx.respond(f"I've set the language to `{lang.name.title()}`{lang.emoji}!")@bot.command(name="hi")asyncdefgreet(ctx):# This will be translated before sent if necessaryawaitctx.reply("Hey!!")bot.run("TOKEN")ExamplesGet Started- A minimal example on how to get started with the extension.Cog Example- Get started but inside a cog.Customized- An example on how to customize/make your own translator and override the default one.Settings- An example on how to enable/disable the extension from translating certain fieldsOptimized- An example on how to ignore translation on parts of a string that is prone to changeAll Objects- A summary example of every object that is affected by translation + all features discussed priorFeatures ExtendedTokenizationTokenization breaks down a string in any order or magnitude of markdown decorations to the extent accepted by discord, into separate tokens to ready for batch translation. Once translated, the new phrases are reassembeled into correct positions and thus maintaining decorative characters fairly accurately.ConstantsThis library implements constants for:LanguageNamestoCodetoEmojienumExamples:>>>Language.English.code...en>>>Language.English.emoji...🏴󠁧󠁢󠁥󠁮󠁧󠁿>>>Language.name...englishTo access enum elements for a specific language through it's corresponding code or name:>>>Language.from_code("en")...Language.English>>>Language.from_name("english")...Language.EnglishCodeblock identifiersCODEBLOCK_LANGSis an exhaustive set of string identifiers that are considered valid code block languages in the tokenizer.FAQHow do we tell the extension to translate x?How does the extension work?What does it use to translate the string?When are strings not translated?How do I avoid translation on specific function calls?How do we tell the extension to translate x?By default, the extension will translate all messages and ignore others. If you want
to translate other objects such as buttons, embeds and so on, you will have
to explicitly specify them as a parameter when instantiating theAutoI17nAgentclass or modify thetranslate_xflag from the class. See detailed examplehereApart from that, you can call the usual methods likeMessegable.send,ApplicationContext.respondwith your texts and the translation will be
handled in the backend. Absolutely
no code change is necessary when calling these high-level methods.How does the extension work?When you call high-level methods e.g.Messegable.sendthe extension intercepts the text and the destination it's being sent to. It resolves
whether if this text requires translation by calling the language getter with the
ID of its destination. If it has one, it will append
the language code into an appropriate field and this appendage is later extracted
before text gets sent to the discord API where tokenization, translation, caching
and other book-keeping occurs if necessary.What does it use to translate the string?By default, the extension translates your strings using theGoogle Translatorlibrary. You can override this with your own translator like in the examplehere.When are strings not translated?Strings are not translated in cases where either if the text are already
detected to be in the language
that it should be translated into, or the destination no preference.How do I avoid translation on specific function calls?You can switch the flags to process specific call translations with some
code changes. One example is the commandselectivehere.TODO / KNOWN ISSUES[-] Defer interaction responses only if translation doesn't exist in cache[-] Resolve the issue with not being able to translate in time forModalsand they can't be deferred....[-] Support translation in Webhooks[-] More tests