Skip to content

Commit

Permalink
Added server-specific translations
Browse files Browse the repository at this point in the history
  • Loading branch information
MaxiHuHe04 committed May 12, 2018
1 parent 6a174dd commit 9fb63ca
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 31 deletions.
71 changes: 46 additions & 25 deletions betheprofessional.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import os
import re
import string
import sys
Expand All @@ -11,18 +12,20 @@
from discord.ext import commands
from pytz import timezone

MSG_LANG = "de"
DEFAULT_MSG_LANG = "de"
PREFIX = "."

bot = commands.Bot(PREFIX, pm_help=True)
bot.remove_command("help")

with open("languages", mode="r", encoding="utf-8") as languages_file:
default_languages = [line.strip() for line in languages_file.readlines()]
sql = SQLHelper("servers.db", default_languages)
sql = SQLHelper("servers.db", default_languages, DEFAULT_MSG_LANG)

with open(f"lang/{MSG_LANG}.json", mode="r", encoding="utf-8") as translation_file:
translations: dict = json.load(translation_file)
translations = dict()
for lang_file in os.listdir("lang"):
with open(f"lang/{lang_file}", mode="r", encoding="utf-8") as translation_file:
translations[os.path.splitext(os.path.basename(lang_file))[0]] = json.load(translation_file)


@bot.event
Expand Down Expand Up @@ -50,8 +53,11 @@ def split_languages(args):
return [arg.strip() for arg in args.strip(';').split(";")]


def get_translation(*keys: str, default=None) -> Union[dict, str, float, bool]:
current = None
def get_translation(*keys: str, default=None, language=DEFAULT_MSG_LANG) -> Union[dict, str, float, bool]:
if language.lower() not in translations:
return default

current = translations.get(language.lower())
for key in keys:
if type(current) is dict:
current = current.get(key, None)
Expand All @@ -61,9 +67,7 @@ def get_translation(*keys: str, default=None) -> Union[dict, str, float, bool]:
return copy.deepcopy(current) or default


@bot.command(name="+",
description=get_translation("commands", "description", "+"),
help=get_translation("commands", "syntax", "+"))
@bot.command(name="+")
@commands.guild_only()
@commands.bot_has_permissions(manage_roles=True)
async def cmd_add_language(ctx: commands.Context, lang, *langs):
Expand All @@ -78,9 +82,7 @@ async def cmd_add_language(ctx: commands.Context, lang, *langs):
await send_translated(ctx.channel, result, lang=", ".join(affected), mention=ctx.author.mention)


@bot.command(name="-",
description=get_translation("commands", "description", "-"),
help=get_translation("commands", "syntax", "-"))
@bot.command(name="-")
@commands.guild_only()
@commands.bot_has_permissions(manage_roles=True)
async def cmd_remove_language(ctx: commands.Context, lang, *langs):
Expand All @@ -95,9 +97,7 @@ async def cmd_remove_language(ctx: commands.Context, lang, *langs):
await send_translated(ctx.channel, result, lang=", ".join(affected), mention=ctx.author.mention)


@bot.command(name="*",
description=get_translation("commands", "description", "*"),
help=get_translation("commands", "syntax", "*"))
@bot.command(name="*")
@commands.guild_only()
@commands.bot_has_permissions(manage_roles=True)
@commands.has_permissions(manage_roles=True)
Expand All @@ -123,9 +123,7 @@ async def cmd_register_language(ctx: commands.Context, lang, *langs):
mention=ctx.author.mention, lang=args)


@bot.command(name="/",
description=get_translation("commands", "description", "/"),
help=get_translation("commands", "syntax", "/"))
@bot.command(name="/")
@commands.guild_only()
@commands.bot_has_permissions(manage_roles=True)
@commands.has_permissions(manage_roles=True)
Expand All @@ -145,14 +143,26 @@ async def cmd_unregister_language(ctx: commands.Context, lang, *langs):
await send_translated(ctx.channel, "language_unregistered", mention=ctx.author.mention, lang=args)


@bot.command(name="?",
description=get_translation("commands", "description", "?"))
@bot.command(name="?")
async def cmd_help(ctx: commands.Context):
await send_help(ctx.author)

await ctx.message.add_reaction("✅")


@bot.command(name="°")
@commands.guild_only()
async def cmd_set_translation(ctx: commands.Context, language):
language = language.lower()
if language not in translations:
await ctx.message.add_reaction("❌")
return

sql.set_message_language(ctx.guild.id, language)
sql.commit()
await ctx.message.add_reaction("✅")


class Professional:
def __init__(self, user: discord.Member):
self.user = user
Expand Down Expand Up @@ -255,27 +265,38 @@ async def on_command_error(ctx: commands.Context, error: commands.CommandError):

async def send_translated(channel: discord.abc.Messageable, key, **args):
try:
await channel.send(plural_formatter.format(get_translation(key, default=""), **args))
guild_origin = channel.guild if isinstance(channel, discord.TextChannel) else None
language = sql.get_msg_language(guild_origin.id) if guild_origin else DEFAULT_MSG_LANG

await channel.send(plural_formatter.format(get_translation(key, default="", language=language), **args))
except discord.Forbidden:
pass


async def send_help(user: discord.User):
cmd_descriptions: Dict[str, Tuple[str, str]] = {cmd.name: (cmd.help, cmd.description) for cmd in bot.commands}
translation_lang = sql.get_msg_language(user.guild.id) if isinstance(user, discord.Member) else DEFAULT_MSG_LANG

cmd__help = ["``{}{}``".format(cmd, (" " + syntax) if syntax else "") + (" {}".format(desc) if desc else "")
cmd_descriptions: Dict[str, Tuple[str, str]] = {cmd.name: (get_translation("commands", "syntax", cmd.name,
language=translation_lang),
get_translation("commands", "description", cmd.name,
language=translation_lang))
for cmd in bot.commands}

cmd__help = [f"``{cmd}{(' ' + syntax) if syntax else ''}``"
f" {desc.format(translations=', '.join(translations.keys())) if desc else ''}"
for cmd, (syntax, desc) in cmd_descriptions.items()]

cmd__help = "\n".join(cmd__help)

embed_data: dict = get_translation("help_embed")
embed_data: dict = get_translation("help_embed", language=translation_lang)

if embed_data and isinstance(embed_data, dict):
if "fields" in embed_data and isinstance(embed_data["fields"], list):
languages = sql.get_topics(user.guild.id) if isinstance(user, discord.Member) else default_languages

field_formatting = dict(mention=user.mention, prefix=PREFIX, language_amount=len(languages),
commands=cmd__help, languages=", ".join(languages),
guild_count=sql.get_guild_count())
guild_count=sql.get_guild_count(), translations=", ".join(translations.keys()))

for f in embed_data["fields"]:
if "name" in f and "value" in f:
Expand Down
6 changes: 4 additions & 2 deletions lang/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,16 @@
"+": "[Sprache]",
"-": "[Sprache]",
"*": "[Sprache]",
"/": "[Sprache]"
"/": "[Sprache]",
"°": "[Sprachkürzel]"
},
"description": {
"+": "Gibt dir eine Sprache (mehrere gleichzeitig mit ``;``)",
"-": "Entfernt dir eine Sprache (alle mit ``- *``)",
"*": "Fügt eine Sprache zum Bot hinzu (nur für Admins)",
"/": "Löscht eine Sprache vom Bot (nur für Admins)",
"?": "Zeigt diese Hilfe an"
"?": "Zeigt diese Hilfe an",
"°": "Legt die Sprache eines Servers fest (Übersetzungen: {translations})"
}
},
"help_embed": {
Expand Down
8 changes: 5 additions & 3 deletions lang/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,20 @@
"+": "<language>",
"-": "<language>",
"*": "<language>",
"/": "<language>"
"/": "<language>",
"°": "<language-code>"
},
"description": {
"+": "Adds a language (multiple languages at once: ``;``)",
"-": "Removes a language (all languages with ``- *``)",
"*": "Adds a language to the bot (only for admins)",
"/": "Removes a language from the bot (only for admins)",
"?": "Displays this help"
"?": "Displays this help",
"°": "Sets the language of a server (Available: {translations})"
}
},
"help_embed": {
"title": "BeTheProfessional help",
"title": "BeTheProfessional Help",
"description": "Help for BeTheProfessional\n[GitHub Link](https://github.com/MaxiHuHe04/BeTheProfessional)",
"fields": [
{
Expand Down
15 changes: 14 additions & 1 deletion sqlhelper.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@

class SQLHelper:

def __init__(self, filename: str, default_languages: List[str]):
def __init__(self, filename: str, default_languages: List[str], default_message_language):
self.conn = sqlite3.connect(filename)
self.default_languages = default_languages
self.default_msg_language = default_message_language

def setup(self):
self.conn.execute("CREATE TABLE IF NOT EXISTS languages (guild_id int PRIMARY KEY, topics text)")
self.conn.execute("CREATE TABLE IF NOT EXISTS msg_language (guild_id int PRIMARY KEY, language text)")

def __enter__(self):
return self
Expand All @@ -22,6 +24,7 @@ def is_guild(self, guild_id: int) -> bool:

def add_guild(self, guild_id: int):
self.conn.execute("INSERT INTO languages VALUES (?, ?)", (guild_id, "\n".join(self.default_languages)))
self.conn.execute("INSERT INTO msg_language VALUES (?, ?)", (guild_id, self.default_msg_language))

def get_guild_count(self):
return self.conn.execute("SELECT COUNT(*) FROM languages").fetchone()[0]
Expand Down Expand Up @@ -51,6 +54,16 @@ def remove_topic(self, guild_id: int, topic: str):
self.conn.execute("UPDATE languages SET topics=? WHERE guild_id=?", ("\n".join(before.values()), guild_id))
return True

def get_msg_language(self, guild_id: int):
if not self.is_guild(guild_id):
self.add_guild(guild_id)
return self.conn.execute("SELECT language FROM msg_language WHERE guild_id=?", (guild_id,)).fetchone()[0]

def set_message_language(self, guild_id: int, language: str):
if not self.is_guild(guild_id):
self.add_guild(guild_id)
self.conn.execute("UPDATE msg_language SET language=? WHERE guild_id=?", (language, guild_id))

def commit(self):
self.conn.commit()

Expand Down

0 comments on commit 9fb63ca

Please sign in to comment.