def __init__(self,bot): self.bot = bot self.file="languages" self.languages = ['fr', 'en'] self.cache = dict() i18n.translations.container.clear() # invalidate old cache i18n.load_path.clear() i18n.set('filename_format', '{locale}.{format}') i18n.set('fallback', 'en') i18n.load_path.append('./lang')
def tl(tl_namespace: str, locale: str): locale = 'en' if not locale else locale i18n.set('locale', locale) i18n.set('fallback', 'en') result = i18n.t(tl_namespace) if locale and locale.lower() not in alpha_2_langs: raise LocaleException("Invalid locale") if result == tl_namespace: raise LocaleException("No translation in any locale") return result
def __init__(self, bot): self.bot = bot self.session = {} conf = Config("config.ini") trans_conf = conf.get("Translation") i18n.set("locale", trans_conf['default_locale']) i18n.set("file_type", "json") i18n.load_path.append(trans_conf['path'])
def get_reading_time(self, content): i18n.load_path.append('./translations') i18n.set('locale', self.meta.lang) i18n.set('fallback', 'en') nb_words = len(content.split()) seconds = math.ceil((nb_words / 200) * 60) estimated_time = time.strftime(f'~ %M {i18n.t("article.read")}', time.gmtime(seconds)) return estimated_time
def add_task(msg): find = db.users.find_one({"id": str(msg.chat.id)}) i18n.set("locale", find["lang"]) markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True) markup.add(i18n.t("msg.cancel")) bot.send_message(msg.chat.id, i18n.t("msg.enter"), reply_markup=markup) bot.register_next_step_handler(msg, add_hand) botan.track(botan_key, msg.chat.id, msg, 'Add task') return
def __init__(self, get_locale: Optional[Callable[[Guild], Awaitable[str]]]): self.get_locale = get_locale root_path = pathlib.Path(__file__).parent.absolute() i18n.load_path.append(root_path) i18n.set("enable_memoization", True) create_owo(root_path) if translate_function: self.translate_function = translate_function else: self.translate_function = i18n.t
def handle(bot: Bot, event: events.TextMessage, _match: typing.Match): if event.uid not in Config.whitelist_admin: return i18n.set("locale", "en") message = i18n.t("available_commands") for _ in bot.commands: if _.USAGE != USAGE: message += "\n - {}".format(_.USAGE) bot.send_message(event.id, message, is_translation=False)
def rate(msg): find = db.users.find_one({"id": str(msg.chat.id)}) i18n.set("locale", find["lang"]) kb = types.InlineKeyboardMarkup() btn = types.InlineKeyboardButton( text=i18n.t("msg.rate"), url="https://t.me/storebot?start=jditbot") kb.add(btn) bot.send_message(msg.chat.id, i18n.t("msg.thanks"), reply_markup=kb) botan.track(botan_key, msg.chat.id, msg, 'Rate') return
def notifyset(msg): find = db.users.find_one({"id": str(msg.chat.id)}) i18n.set("locale", find["lang"]) if find["notify"]: markup = gen_markup(i18n.t("msg.add"), i18n.t("msg.tasks"), i18n.t("msg.help"), i18n.t("msg.rate"), i18n.t("msg.onn"), i18n.t("msg.setl")) db.users.update({"id": str(msg.chat.id)}, {"$set": {"notify": False}}) bot.send_message(msg.chat.id, i18n.t("msg.disabled"), reply_markup=markup) else: markup = gen_markup(i18n.t("msg.add"), i18n.t("msg.tasks"), i18n.t("msg.help"), i18n.t("msg.rate"), i18n.t("msg.offn"), i18n.t("msg.setl")) db.users.update({"id": str(msg.chat.id)}, {"$set": {"notify": True}}) bot.send_message(msg.chat.id, i18n.t("msg.enabled"), reply_markup=markup)
def main(lang, theme, pos, size): """ Main loop Sets i18n, check FFMPEG dependency and init the MainWindow """ i18n.set('locale', lang) i18n.set('fallback', 'en') i18n.load_path.append('./lang/') app = wx.App(False) frame = MainFrame(lang, theme, pos, size) check_ffmpeg() app.MainLoop()
def main(): filename = sys.argv[1] # "data/f-bubk.yml" script_path, _ = os.path.split(os.path.abspath(__file__)) i18n.load_path.append(os.path.join(script_path, "translations")) i18n.set("filename_format", "{locale}.{format}") # remove i18n namespace import locale cur_locale = locale.getlocale()[0][:2] i18n.set("locale", cur_locale) MyApp(filename).run()
def main(request): logging.info('========[START]========') if not request.method == 'POST': return 'Service is Up and Running....' # Request parameters payload = request.get_data() params = json.loads(payload) logging.info(params) # Locale setting # Availability # if 'intent' in params['data'] and params['data']['intent'] == INTENT_MEETING_ARRANGEMENT: # return T_Meetingroom_Arrangement.open(params) if 'intent' in params['data'] and params['data']['intent'] == INTENT_MEETING_ARRANGEMENT_YES: i18n.set('locale', params['data']['lang']) return T_Meetingroom_Arrangement.open(params) elif 'intent' in params['data'] and params['data']['intent'] == INTENT_MEETING_ARRANGEMENT_SLOT: i18n.set('locale', params['data']['lang']) return T_Meeting_Arrangement_Slot.start(params) elif 'type' in params and params['type'] == 'view_submission': i18n.set('locale', params['data']['state']) return T_Meetingroom_Arrangement.start(params) else: i18n.set('locale', params['data']['lang']) logging.info('Nothing to do....') return json.dumps({})
def t(language, translation): """ Translates RST strings to Regional Strings using i18n as a cache as parsing RST delays load by a lot to retrieve simple things that are used many times """ i18n.set('locale', language) if translation == i18n.t(translation): rst = RstFile(download.download_cdragon_rstfile(language)) try: name = rst.__getitem__(translation) except Exception: print("DIDNT FIND: " + translation) name = "" i18n.add_translation(translation, name, locale=language) return name return i18n.t(translation)
def callback_inline(call): find = db.users.find_one({"id": str(call.message.chat.id)}) i18n.set("locale", find["lang"]) db.users.update({"id": str(call.message.chat.id)}, {"$pull": {"tasks": find["tasks"][int(call.data)]}}, upsert=False) bot.answer_callback_query(call.id, text=i18n.t("msg.completed")) find = db.users.find_one({"id": str(call.message.chat.id)}) if len(find["tasks"]) != 0: bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=i18n.t("msg.taskhelp"), reply_markup=tasks_kb(find["tasks"])) botan.track(botan_key, call.message.chat.id, call.message, 'Delete task') return else: bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=i18n.t("msg.notask"))
def init_i18n(): FILE_DIR = path.dirname(path.abspath(__file__)) LOCALE_DIR = path.join(FILE_DIR, 'locales') i18n.load_path.append(LOCALE_DIR) i18n.set('file_format', 'json') lang = getenv('LANG') locale = lang and lang.split('.')[0] locale = locale and locale.split('_')[0] i18n.set('locale', locale) i18n.set('fallback', 'en') i18n.set('skip_locale_root_data', True)
def start(msg): find = db.users.find_one({"id": str(msg.chat.id)}) if find: i18n.set("locale", find["lang"]) if find["notify"]: markup = gen_markup(i18n.t("msg.add"), i18n.t("msg.tasks"), i18n.t("msg.help"), i18n.t("msg.rate"), i18n.t("msg.offn"), i18n.t("msg.setl")) else: markup = gen_markup(i18n.t("msg.add"), i18n.t("msg.tasks"), i18n.t("msg.help"), i18n.t("msg.rate"), i18n.t("msg.onn"), i18n.t("msg.setl")) bot.send_message(msg.chat.id, i18n.t("msg.hi_back"), reply_markup=markup) botan.track(botan_key, msg.chat.id, msg, 'Returned user') return else: markup = gen_markup(i18n.t("msg.add"), i18n.t("msg.tasks"), i18n.t("msg.help"), i18n.t("msg.rate"), i18n.t("msg.offn"), i18n.t("msg.setl")) db.users.save({"id": str(msg.chat.id), "tasks": [], "notify": True, "lang": "en"}) bot.send_message(msg.chat.id, i18n.t("msg.hi"),reply_markup=markup) botan.track(botan_key, msg.chat.id, msg, 'New user') return
def save_task(msg, cid, text): find = db.users.find_one({"id": str(cid)}) i18n.set("locale", find["lang"]) if find["notify"]: markup = gen_markup(i18n.t("msg.add"), i18n.t("msg.tasks"), i18n.t("msg.help"), i18n.t("msg.rate"), i18n.t("msg.offn"), i18n.t("msg.setl")) else: markup = gen_markup(i18n.t("msg.add"), i18n.t("msg.tasks"), i18n.t("msg.help"), i18n.t("msg.rate"), i18n.t("msg.onn"), i18n.t("msg.setl")) if len(text) < 50: if text not in find["tasks"]: db.users.update({"id": str(cid)}, {"$push": {"tasks": text}}, upsert=False) bot.send_message(cid, i18n.t("msg.added"), reply_markup=markup) botan.track(botan_key, cid, msg, 'Add task') return else: bot.send_message(cid, i18n.t("msg.inlist"), reply_markup=markup) else: bot.send_message(cid, i18n.t("msg.long"), reply_markup=markup)
def __init__(self, session: Session, connect: bool = True, is_cycle: bool = False) -> None: self.users: Dict[str, ts3bot.User] = {} self.session = session self.is_cycle = is_cycle if is_cycle: self.client_nick = Config.get("cycle_login", "nickname") self.channel_id = None else: # Register commands self.commands: List[Command] = [] for _ in commands.__commands__: if Config.has_option("commands", _) and not Config.getboolean( "commands", _): LOG.info("Skipping command.%s", _) continue mod = cast(Command, import_module(f"ts3bot.commands.{_}")) mod.REGEX = re.compile(mod.MESSAGE_REGEX) LOG.info("Registered command.%s", _) self.commands.append(mod) # Register translation settings i18n.set("load_path", [str(Path(__file__).parent / "i18n")]) i18n.set("filename_format", "{locale}.json") i18n.set("enable_memoization", True) i18n.set("skip_locale_root_data", True) i18n.set("locale", "de") self.client_nick = Config.get("bot_login", "nickname") self.channel_id = Config.get("teamspeak", "channel_id") self.ts3c: Optional[ts3.query.TS3ServerConnection] = None self.own_id: int = 0 self.own_uid: str = "" if connect: self.connect()
def open(params): logging.info('Open dialog...[START]') logging.info(params) # Locale setting i18n.set('locale', params['data']['lang']) # Extract user profile details to set default contact name and phone try: logging.info('user info fetcch') user_data = slack_client.users_info(user=params['user']) logging.info(user_data) # user_name = user_data['user']['profile']['real_name'] # user_phone = user_data['user']['profile']['phone'] except BaseException: logging.error('Slack user not found...[ERROR]') # Return response return json.dumps({ 'client': 'slack', 'type': 'message', 'data': { 'text': i18n.t('MESSAGE_GUEST_REGISTER_USER_NOT_FOUND') }, 'channel': params['channel'] }) # Set default time to 1 hour from now now = datetime.now(JST) date = now.strftime(DATE_FORMAT) # Dialog Box MODAL = Arrangement_Modal.adjustment_Modal(params, date) # Return response return json.dumps({ 'client': 'slack', 'type': 'modal', 'data': { 'modal': MODAL, 'trigger_id': params['data']['trigger_id'] }, 'channel': params['channel'] })
def setup_translation(): locales_dir = os.path.join(ApplicationUtil.bundle_dir(), 'assets', 'locales') i18n.load_path.append(locales_dir) i18n.set("filename_format", "{locale}.{format}") i18n.set("locale", config.get("APP", "language")) i18n.set("enable_memoization", True)
def main(): i18n.load_path.append(os.path.dirname(__file__)) i18n.set('file_format', 'json') token = None with open(os.path.dirname(__file__) + '/token_file', 'r') as tokenFile: token = tokenFile.readline() app = Flask(__name__) viber = Api( BotConfiguration(name=i18n.t(__get_res('botName')), avatar=i18n.t(__get_res('image-url')), auth_token=token)) messageSwitcher = MessageSwitcher(viber) @app.route('/' + token, methods=['POST']) def incoming(): logger.debug("received request. post data: {0}".format( request.get_data())) viber_request = viber.parse_request(request.get_data().decode('utf-8')) messageSwitcher.disassembleReq(viber_request) # if isinstance(viber_request, ViberMessageRequest): # message = viber_request.message # # lets echo back # userId = viber_request.sender.id # sendMessage(viber, userId) # # viber.send_messages(viber_request.sender.id, [message]) # elif isinstance(viber_request, ViberSubscribedRequest): # viber.send_messages(viber_request.get_user.id, [ # TextMessage(text="thanks for subscribing!") # ]) # elif isinstance(viber_request, ViberFailedRequest): # logger.warn("client failed receiving message. failure: {0}".format(viber_request)) return Response(status=200) app.run()
def dispatchHandler(data): session = data.get("session") language_code = data.get("queryResult").get("languageCode") print(language_code) i18n.set('locale', language_code) action_name = data.get("queryResult").get("intent").get("displayName") if action_name == "Default Welcome Intent": low = 0 high = 5 target = random.randint(low+1, high-1) db.set(session, (low, target, high)) text = i18n.t('guess.welcome', low = str(low), high = str(high)) print("Response:{}".format(text)) reply = { "fulfillmentText": text } return jsonify(reply) elif action_name == "GuessNumber": pair = db.get(session) guessnum = int(data.get("queryResult").get("parameters").get("number")) minnum, target, maxnum = pair if guessnum > maxnum or guessnum < minnum: text = i18n.t('guess.guess_out', low = str(minnum), high = str(maxnum)) else: if guessnum == target: event = "User_number_match" reply = { "followup_event_input" : { "name" : "User_number_match" } } return jsonify(reply) else: if guessnum < target: minnum = guessnum else: maxnum = guessnum text = i18n.t('guess.guess_unmatch', low = str(minnum), high = str(maxnum)) db.set(session, (minnum, target, maxnum)) print("Response:{}".format(text)) reply = { "fulfillmentText": text } return jsonify(reply)
def generate_contact(self): f = self.generate(i18n.t('menu.contact')) i18n.load_path.append('./translations') i18n.set('locale', self.meta.lang) i18n.set('fallback', 'en') doc, tag, text = Doc().tagtext() with tag('div', klass='contact'): with tag('h2', klass='contact__title'): text(i18n.t('menu.contact')) with tag('span', klass='contact__message'): text(i18n.t('contact.intro') + '!') with tag('span', klass='contact__phone'): text( i18n.t('contact.phone', opening_hour=self.meta.author.available_from, closing_hour=self.meta.author.available_until) + ':') with tag('a', href=f'tel:{self.meta.author.phone}', klass='contact__phone__link'): doc.asis('<i class="fas fa-phone"></i>') with tag('span', klass='contact__mail'): text(i18n.t('contact.mail') + ':') with tag( 'a', href=f'mailto:{self.meta.author.mail}?subject=contact', klass='contact__mail__link'): doc.asis('<i class="far fa-paper-plane"></i>') return self.close_html(f + indent(doc.getvalue()))
def __init__(self, localization_dir: Path, language: str) -> None: if not localization_dir.is_dir(): raise ValueError(f'Path [{localization_dir}] does not exist or it is not a dir!') i18n.load_path.append(localization_dir) i18n.set('locale', language) i18n.set('enable_memoization', True) # cache loaded strings in memory i18n.set('filename_format', '{locale}.{format}')
def load_translation(translation_path: Path, language: Text, fallback_language: Text) -> TranslationFunction: """Loads the chosen translation of the app. Args: translation_path: Path to directory containing translation files. language: Language code of chosen language. fallback_language: The default language code to fall back to. Returns: The translation function accepting a textual key and returning the localized string. """ # Default configuration values: # https://github.com/danhper/python-i18n/blob/master/i18n/config.py # Keep localization in memory i18n.set("enable_memoization", True) # Output error for missing translation keys i18n.set("error_on_missing_translation", True) # Set the translation path i18n.load_path.append(translation_path) # Set the selected language i18n.set("locale", language) # Set the fallback language i18n.set("fallback", fallback_language) return i18n.t
def main(): # Get options (combined from defaults, config file, and command line arguments) options = parse_options() # Set up logging level = LogLevel[options.log_level].value logger = logging.getLogger(__package__) handler = logging.StreamHandler() formatter = logging.Formatter( "%(asctime)s (%(levelname)s) [%(name)s] %(message)s", "%m/%d/%Y %H:%M:%S") handler.setFormatter(formatter) handler.setLevel(level) logger.addHandler(handler) logger.setLevel(level) logger.debug(f"Combined options: {vars(options)}") # Set up i18n i18n.set("locale", "en_US") i18n.set("fallback", "en_US") i18n.set("enable_memoization", True) strings_path = pathlib.Path(__file__).parent.absolute().joinpath("strings") i18n.load_path.append(str(strings_path)) # Read environment variables from .env file load_dotenv() # Load the discord authorization token from DISCORD_TOKEN environment variable token = os.getenv("DISCORD_TOKEN") if not token: raise TokenNotFoundError() # Set options and run the bot bot.command_prefix = options.command_prefix bot.run(token)
def user_lang(message): user_lang = message.from_user.language_code.lower() # print(user_lang) i18n.set('locale', user_lang) i18n.set('fallback', 'en-us') set_buttons()
def configure_translation(force_locale=None): i18n.load_path.append(os.path.join(os.path.dirname(__file__), 'messages')) if force_locale is not None: i18n.set('locale', force_locale) i18n.set('fallback', 'en')
def setup_i18n(): i18n.set("locale", config.translation_locale.value) i18n.set("fallback", "en_us")
import altair as alt import pytest import math import os import i18n i18n.set('filename_format', '{locale}.{format}') i18n.set('locale', 'en') i18n.set('fallback', 'en') i18n.load_path.append( os.path.dirname(__file__) + '/../../../src/penn_chime/locales') from penn_chime.view.charts import ( build_admits_chart, build_census_chart, ) DISPOSITION_KEYS = ("hospitalized", "icu", "ventilated") # These are the localized column names for the dataframe sent to the charting library. admits_icu_key = i18n.t("admits_icu") admits_hospitalized_key = i18n.t("admits_hospitalized") admits_ventilated_key = i18n.t("admits_ventilated") census_icu_key = i18n.t("census_icu") census_hospitalized_key = i18n.t("census_hospitalized") census_ventilated_key = i18n.t("census_ventilated") def test_admits_chart(admits_floor_df): chart = build_admits_chart(alt=alt, admits_floor_df=admits_floor_df) assert isinstance(chart, (alt.Chart, alt.LayerChart))
import i18n import logging import logging.handlers import os # import requests import smtplib import sqlite3 # import sys import telebot from telebot import types import urllib.request from validate_email import validate_email i18n.load_path.append('i18n') i18n.set('locale', 'en-us') # Get file from URL def open_file(file_url, chatid): file_name, headers = urllib.request.urlretrieve(file_url, 'send2kindle_' + file_url.split('/')[-1]) return file_name # Send e-mail function def send_mail(chatid, send_from, send_to, subject, text, file_url): if len(send_from) < 5 or len(send_to) < 5: bot.send_message(chatid, i18n.t('bot.error'), parse_mode='HTML') return 0 msg = MIMEMultipart()
import urllib.request from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import formatdate import i18n import sentry_sdk import telebot import weasyprint from telebot import types from validate_email import validate_email i18n.load_path.append("i18n") i18n.set("fallback", "en-us") document_dict = {} class Document: def __init__(self, name): self.name = name[:20] + name[-5:] def epub2mobi(file_name_epub, chatid): logger_info.info( str(datetime.datetime.now()) + " CONVERT: " + str(chatid) + " " + file_name_epub) bot.send_chat_action(chatid, "upload_document") file_name_mobi = file_name_epub.replace(
from threading import Thread #import configparser import os import gspread import yaml import i18n i18n.load_path.append('app/locales/') i18n.set('locale', 'es') i18n.set('fallback', 'en') _ = i18n.t raw_ref = open("app/static/content/descripcion-indicadores.yml").read() ref = yaml.load(raw_ref)['Descripción de los indicadores'] class IrisDimmensionalCalculator(Thread): def __init__(self, url,queue): Thread.__init__(self) self.url = url self.queue = queue def run(self): docid = self.get_docid(self.url) keyset = self.get_keyset() auth = self.authenticate(keyset['email'], keyset['password']) raw_data = self.read_data(auth, docid) data = self.extract_data(raw_data) readiness_scores = self.assess_readiness(data) self.queue.put(readiness_scores)