Skip to main content

Advanced internationalisation (i18n) support for Discord bots, originally developed for ClansBot

Project description

cb-i18n

Advanced internationalisation (i18n) support for Discord bots

This module works with any well-known Discord API library for Python, including:

Installation

Install with pip:

# Linux / MacOS
python3 -m pip install cb-i18n

# Windows
py -3 -m pip install cb-i18n

Install from source:

git clone https://github.com/LTT/cb-i18n
cd cb-i18n
python3 setup.py install

# Windows
git clone https://github.com/LTT/cb-i18n
cd cb-i18n
py -3 setup.py install

Example usage of cb-i18n:

In fact, this library can work with just any application written in python. The first arg in Translator.translate can be anything, you can pass integer, string, custom object or even module, all will work as expected by you. Internally, lib does nothing with that "context", it just passing it to your locale_getter and all.

Directory structure:

src/
  languages/
    en-US.json
    ru-RU.json
  main.py

src/languages/en-US.json:

{
  "Hello {}": "Hello {}", // Positional placeholders
  "You're a Genius!": "You're a Genius!", // No placeholders
  "Locale is now {locale}": "Locale is now {locale}" // Keyword-only placeholders
}

src/languages/ru-RU.json:

{
  "Hello {}": "Привет {}",
  "You're a Genius!": "Да ты гений!",
  "Locale is now {locale}": "Язык теперь {locale}"
}

src/main.py:

import sqlite3
import disnake
from disnake.ext import commands
import cb_i18n as i18n

bot = commands.Bot("!", intents=disnake.Intents.all())

connection = sqlite3.connect('mydatabase.db')
cursor = connection.cursor()

translator = None
_ = None

def get_locale(ctx: commands.Context):
    return cursor.execute("SELECT locale FROM guilds WHERE id = ?;", ctx.guild.id).fetchone()[0]

@bot.event
async def on_ready():
    print("Bot loading")
    
    cursor.execute("CREATE TABLE IF NOT EXISTS guilds (id bigint, locale text);")
    connection.commit()
    
    print("  Loading guilds table...")
    for guild in bot.guilds:
        if not cursor.execute("SELECT * FROM guilds WHERE id = ?", guild.id).fetchone():
            print("    Guild {}: not exist".format(guild.id))
            
            cursor.execute("INSERT INTO guilds VALUES (?, ?);", guild.id, "en-US")
            connection.commit()
        else:
            print("    Guild {}: exists".format(guild.id))
    print("  Loaded guilds table.")
    
    print("  Loading i18n...")
    global translator, _
    
    translator = i18n.make_translator()
    translator.set_locale_dir("./languages/")
    translator.set_locale_getter(get_locale)
    translator.load_translations()
    _ = translator.translate
    print("  Loaded i18n.")
    
    print("Bot ready!\nAccount: {} (ID: {})\nGuild count: {}\nUser count: {}".format(str(bot.user), bot.user.id, len(bot.guilds), len(bot.users)))

@bot.command(description="Set locale for a guild", aliases=["setlocale", "set-locale"])
async def set_locale(ctx: commands.Context, locale: str):
    cursor.execute("UPDATE guilds SET locale = ? WHERE id = ?;", locale, ctx.guild.id)
    connection.commit()
    
    return await ctx.send(_(ctx, "Locale is now {locale}").format(locale=locale))

@bot.command(description="Say hi!")
async def hi(ctx: commands.Context, name: str):
    return await ctx.send(_(ctx, "Hello {}").format(name))

@bot.command(description="You're Genius, right?")
async def genius(ctx: commands.Context):
    return await ctx.send(_(ctx, "You're a Genius!"))

try:
    bot.run(os.environ.get("BOT_TOKEN"))
except Exception as exc:
    print(exc.__class__.__name__ + ": " + exc.__str__() + "".join(tb.format_exception(exc)))
finally:
    cursor.close()
    connection.close()

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cb_i18n-1.0.4.tar.gz (5.2 kB view details)

Uploaded Source

Built Distribution

cb_i18n-1.0.4-py3-none-any.whl (5.5 kB view details)

Uploaded Python 3

File details

Details for the file cb_i18n-1.0.4.tar.gz.

File metadata

  • Download URL: cb_i18n-1.0.4.tar.gz
  • Upload date:
  • Size: 5.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.0 CPython/3.10.2

File hashes

Hashes for cb_i18n-1.0.4.tar.gz
Algorithm Hash digest
SHA256 bce4dc5fb11221b4b61273a460d83d5357339894e041f7fe441568f89555d70d
MD5 7c07a2a28684de762760ab72ff3db9ba
BLAKE2b-256 e03ac8cccc91c58526e4ba4fb6099ae3b2d143e72b5ab02974596ddda8fcc283

See more details on using hashes here.

File details

Details for the file cb_i18n-1.0.4-py3-none-any.whl.

File metadata

  • Download URL: cb_i18n-1.0.4-py3-none-any.whl
  • Upload date:
  • Size: 5.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.0 CPython/3.10.2

File hashes

Hashes for cb_i18n-1.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 6a87211c2a8c51b0cd7ec7ca0d80cffeb3af8383f3c6f5d87cdc4dbc8807a757
MD5 190b47e32f4207479790f155c8ae251c
BLAKE2b-256 6bbb0c3f099532a601be6c280512cb24c5ca9462e0762fec33af18f006fcf531

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page