def translate(message): if botname_checker(message): inputtext = utils.textparser(message) if inputtext is None: logger.write_log(message, "none") return logger.write_log(message, inputtext) src_lang = None message.text = utils.lang_autocorr(message.text) if utils.extract_arg(message.text, 2) is not None: src_lang = utils.extract_arg(message.text, 1) lang = utils.extract_arg(message.text, 2) elif utils.extract_arg(message.text, 1) is not None: lang = utils.extract_arg(message.text, 1) else: utils.bot.reply_to( message, locales.get_text(message.chat.id, "specifyLang")) return try: utils.bot.reply_to( message, interlayer.get_translate(inputtext, lang, src_lang=src_lang) + add_ad(message.chat.id)) except interlayer.BadTrgLangException: utils.bot.reply_to( message, locales.get_text(message.chat.id, "badTrgLangException")) except interlayer.BadSrcLangException: utils.bot.reply_to( message, locales.get_text(message.chat.id, "badSrcLangException")) except interlayer.TooManyRequestException: utils.bot.reply_to( message, locales.get_text(message.chat.id, "tooManyRequestException")) except interlayer.TooLongMsg: utils.bot.reply_to(message, locales.get_text(message.chat.id, "tooLongMsg")) except interlayer.EqualLangsException: utils.bot.reply_to( message, locales.get_text(message.chat.id, "equalLangsException")) except interlayer.UnkTransException: utils.bot.reply_to( message, locales.get_text(message.chat.id, "unkTransException"))
def translate_query(inline_query): if logger.logger_message is True: logging.info("user " + logger.username_parser(inline_query) + " sent an INLINE: " + inline_query.query) elif logger.logger is True: logging.info("user " + logger.username_parser(inline_query) + " sent an INLINE") if len(inline_query.query) > 250: return locales.get_text_inline(inline_query, "tooLongInline") inline_query.query = utils.lang_autocorr(inline_query.query, True) lang = utils.extract_arg(inline_query.query, 0) try: inputtext = inline_query.query.split(' ', 1)[1].lstrip() except IndexError: return locales.get_text_inline(inline_query, "inlineInstruction") if lang is None: return locales.get_text_inline(inline_query, "inlineInstructionTwo") try: inputtext = interlayer.get_translate(inputtext, lang) return inputtext except interlayer.BadTrgLangException: return locales.get_text_inline(inline_query, "badTrgLangException") except interlayer.TooManyRequestException: return locales.get_text_inline(inline_query, "tooManyRequestException") except interlayer.UnkTransException: return locales.get_text_inline(inline_query, "unkTransException")
def download_clear_log(message, down_clear_check): import utils if utils.extract_arg(message.text, 1) != key and key != "": utils.bot.reply_to(message, "Неверный ключ доступа") return if down_clear_check: try: f = open(current_log, 'r', encoding="utf-8") utils.bot.send_document(message.chat.id, f) f.close() write_log("INFO: log was downloaded successful by " + username_parser(message)) except FileNotFoundError: write_log("INFO: user " + username_parser(message) + " tried to download empty log\n" + traceback.format_exc()) utils.bot.send_message(message.chat.id, "Лог-файл не найден!") except Exception: write_log("ERR: user " + username_parser(message) + " tried to download log, but something went wrong!\n" + traceback.format_exc()) utils.bot.send_message(message.chat.id, "Ошибка выгрузки лога!") else: if clear_log(): write_log("INFO: log was cleared by user " + username_parser(message) + ". Have fun!") utils.bot.send_message(message.chat.id, "Очистка лога успешна") else: write_log("ERR: user " + username_parser(message) + " tried to clear log, but something went wrong\n!") utils.bot.send_message(message.chat.id, "Ошибка очистки лога")
def auto_enable(message): set_lang = utils.lang_autocorr(utils.extract_arg(message.text, 1)) if interlayer.lang_list.get(set_lang) is None and set_lang != "disable": utils.bot.reply_to( message, locales.get_text(message.chat.id, "distortWrongLang")) else: try: sql_worker.write_chat_info(message.chat.id, "target_lang", set_lang) except sql_worker.SQLWriteError: utils.bot.reply_to( message, locales.get_text(message.chat.id, "configFailed")) if set_lang != "disable": lang = interlayer.lang_list.get(set_lang) try: if locales.get_chat_lang(message.chat.id) != "en": translated_lang = lang + " (" \ + interlayer.get_translate(lang, locales.get_chat_lang(message.chat.id)) + ")" else: translated_lang = lang except (interlayer.BadTrgLangException, interlayer.UnkTransException): utils.bot.reply_to( message, locales.get_text(message.chat.id, "langDetectErr")) return utils.bot.reply_to( message, locales.get_text(message.chat.id, "autoTransSuccess") + translated_lang) else: utils.bot.reply_to( message, locales.get_text(message.chat.id, "autoTransDisabled"))
def translate_query(inline_query): lang = utils.extract_arg(inline_query.query, 0) try: inputtext = inline_query.query.split(' ', 1)[1].lstrip() except IndexError: return "Введите код языка и текст" logger.write_log("LOG: user " + logger.username_parser(inline_query) + " sent an INLINE: " + inputtext) if lang is None: return "Укажите код языка/название страны" try: translated = utils.translator.translate(inputtext, lang).text if translated == inputtext: return ( "Исходный и итоговый текст совпадают. Возможно, Google Api отклонил запрос. " "Если вы уверены, что так быть не должно, повторите попытку позже" ) return translated except Exception as e: if str(e) in "invalid destination language": return "Указан неверный код языка/название страны" else: logger.write_log("ERR: " + str(e) + "\n" + traceback.format_exc()) return ("Ошибка перевода. Обратитесь к авторам бота\n" "Информация для отладки сохранена в логах бота.")
def force_premium(message, current_chat, is_user): if utils.user_admin_checker(message) is False: return added_text = locales.get_text(message.chat.id, "premiumChat") if is_user or message.chat.type == "private": added_text = locales.get_text(message.chat.id, "premiumUser") if current_chat[0][3] == "no": timer = "0" if utils.extract_arg(message.text, 2) is not None: try: timer = str( int(time.time()) + int(utils.extract_arg(message.text, 2)) * 86400) except ValueError: utils.bot.reply_to( message, locales.get_text(message.chat.id, "parseTimeError")) return try: sql_worker.write_chat_info(current_chat[0][0], "premium", "yes") sql_worker.write_chat_info(current_chat[0][0], "expire_time", timer) except sql_worker.SQLWriteError: utils.bot.reply_to( message, locales.get_text(message.chat.id, "premiumError")) return utils.bot.reply_to( message, locales.get_text(message.chat.id, "forcePremium").format(added_text)) else: try: sql_worker.write_chat_info(current_chat[0][0], "premium", "no") sql_worker.write_chat_info(current_chat[0][0], "expire_time", "0") except sql_worker.SQLWriteError: utils.bot.reply_to( message, locales.get_text(message.chat.id, "premiumError")) return utils.bot.reply_to( message, locales.get_text(message.chat.id, "forceUnPremium").format(added_text))
def qwerty_main(message): text = utils.textparser(message) if text is None: logger.write_log(message, "none") return logger.write_log(message, text) message.text = utils.lang_autocorr(message.text) arg1, arg2 = utils.extract_arg(message.text, 1), utils.extract_arg(message.text, 2) if arg2 is None: tab1 = utils.layouts.get(interlayer.extract_lang(text)) tab2 = utils.layouts.get(arg1) else: tab1 = utils.layouts.get(arg1) tab2 = utils.layouts.get(arg2) if tab1 is None and arg2 is None: try: recognized_lang = interlayer.get_translate( interlayer.lang_list.get(interlayer.extract_lang(text)), "ru") except (interlayer.BadTrgLangException, interlayer.UnkTransException, interlayer.TooManyRequestException): recognized_lang = "Unknown" utils.bot.reply_to( message, locales.get_text(message.chat.id, "unknownSourceLang").format(recognized_lang)) return if tab1 is None or tab2 is None: utils.bot.reply_to(message, locales.get_text(message.chat.id, "unknownLayout")) return try: translated_text = text.translate(str.maketrans(tab1, tab2)) utils.bot.reply_to(message, translated_text + ad_module.add_ad(message.chat.id)) except Exception as e: logging.error(str(e) + "\n" + traceback.format_exc()) utils.bot.reply_to(message, locales.get_text(message.chat.id, "layoutError"))
def qwerty_main(message): text = utils.textparser(message) if text is None: logger.write_log("none", message) return logger.write_log(text, message) arg1, arg2 = utils.extract_arg(message.text, 1), utils.extract_arg(message.text, 2) if arg2 is None: tab1 = utils.layouts.get(utils.extract_lang(text)) tab2 = utils.layouts.get(arg1) else: tab1 = utils.layouts.get(arg1) tab2 = utils.layouts.get(arg2) if tab1 is None and arg2 is None: utils.bot.reply_to( message, "Исходный язык не распознан. Неправильный аргумент или неверно распознан " "язык? (" + LANGUAGES.get(utils.extract_lang(text)) + ")\n" "Попробуйте указать исходный язык вручную. Возможно, язык отсутствует в " "словаре символов") return if tab1 is None or tab2 is None: utils.bot.reply_to( message, "Неизвестная раскладка. Возможно, язык отсутствует в словаре символов" ) return try: translated_text = text.translate(str.maketrans(tab1, tab2)) utils.bot.reply_to(message, translated_text) except Exception as e: logger.write_log("ERR: " + str(e) + "\n" + traceback.format_exc()) utils.bot.reply_to( message, "Ошибка смены раскладки текста. Обратитесь к авторам бота\n" "Информация для отладки сохранена в логах бота.")
def module_add_task(message): if utils.user_admin_checker(message) is False: return if not enable_ad: utils.bot.reply_to(message, locales.get_text(message.chat.id, "adDisabled")) return text = utils.textparser(message) if text is None: return if utils.extract_arg(message.text, 1) is None or utils.extract_arg( message.text, 2) is None: utils.bot.reply_to( message, locales.get_text(message.chat.id, "taskerArguments")) return try: expire_time = int( time.time()) + int(utils.extract_arg(message.text, 2)) * 86400 except (TypeError, ValueError): utils.bot.reply_to( message, locales.get_text(message.chat.id, "taskerArguments")) return lang_code = utils.extract_arg(message.text, 1) if sql_worker.write_task(message.reply_to_message.id, text, lang_code, expire_time, message.chat.id) is False: utils.bot.reply_to(message, locales.get_text(message.chat.id, "taskerFail")) else: utils.bot.reply_to( message, locales.get_text(message.chat.id, "taskerSuccess").format( lang_code, datetime.datetime.fromtimestamp(expire_time).strftime( "%d.%m.%Y %H:%M:%S")))
def translate_main(message): lang = utils.extract_arg(message.text, 1) if utils.extract_arg(message.text, 2) is not None: lang = lang + " " + utils.extract_arg(message.text, 2) inputtext = utils.textparser(message) if inputtext is None: logger.write_log("none", message) return logger.write_log(inputtext, message) if lang is None: utils.bot.reply_to(message, "Укажите код языка/название страны") return try: translated = utils.translator.translate(inputtext, lang).text if translated == inputtext and translate_verify is True: logger.write_log("ERR: GOOGLE_API_REJECT") utils.bot.reply_to( message, "Исходный и итоговый текст совпадают. Возможно, Google Api отклонил запрос. " "Если вы уверены, что так быть не должно, повторите попытку позже" ) return utils.bot.reply_to(message, translated) except Exception as e: if str(e) in "invalid destination language": utils.bot.reply_to(message, "Указан неверный код языка/название страны") else: logger.write_log("ERR: " + str(e) + "\n" + traceback.format_exc()) utils.bot.reply_to( message, "Ошибка перевода. Обратитесь к авторам бота\n" "Информация для отладки сохранена в логах бота.")
def status_premium(message): if not enable_ad: utils.bot.reply_to(message, locales.get_text(message.chat.id, "adDisabled")) return chat_user_id = message.chat.id is_user = False if message.reply_to_message is not None: chat_user_id = message.reply_to_message.from_user.id is_user = True sql_worker.actualize_chat_premium(chat_user_id) current_chat = sql_worker.get_chat_info(chat_user_id) if not current_chat: try: sql_worker.write_chat_info(chat_user_id, "premium", "no") except sql_worker.SQLWriteError: utils.bot.reply_to(message, locales.get_text(chat_user_id, "premiumError")) return current_chat = sql_worker.get_chat_info(chat_user_id) if utils.extract_arg(message.text, 1) == "force": # Usage: /premium force [time_in_hours (optional argument)] force_premium(message, current_chat, is_user) return added_text = locales.get_text(message.chat.id, "premiumChat") if is_user or message.chat.type == "private": added_text = locales.get_text(message.chat.id, "premiumUser") if current_chat[0][3] == "no": premium_status = locales.get_text(message.chat.id, "premiumStatusDisabled") else: if current_chat[0][4] != 0: premium_status = locales.get_text(message.chat.id, "premiumStatusTime") + " " + \ datetime.datetime.fromtimestamp(current_chat[0][4]).strftime("%d.%m.%Y %H:%M:%S") else: premium_status = locales.get_text(message.chat.id, "premiumStatusInfinity") utils.bot.reply_to( message, locales.get_text(message.chat.id, "premiumStatus").format(added_text) + " <b>" + premium_status + "</b>", parse_mode="html")
def auto_trans_set(message): if not botname_checker(message): return logger.write_log(message, logger.BLOB_TEXT) if not utils.enable_auto: utils.bot.reply_to( message, locales.get_text(message.chat.id, "autoTransDisabledConf")) return if utils.extract_arg(message.text, 1) is None: auto_status(message) return else: if btn_checker(message, message.from_user.id): utils.bot.reply_to(message, locales.get_text(message.chat.id, "adminsOnly")) return auto_enable(message)
def distort_main(message): if max_inits == 0: utils.bot.reply_to( message, "Ошибка, хостер бота принудительно отключил функцию Distort") return inputshiz = utils.textparser(message) if inputshiz is None: logger.write_log("none", message) return logger.write_log(inputshiz, message) try: counter = int(utils.extract_arg(message.text, 1)) except (ValueError, TypeError): utils.bot.reply_to(message, "Ошибка, число не распознано") return if counter > max_inits or counter < 1: utils.bot.reply_to( message, "Ошибка, укажите значение от 1 до " + str(max_inits)) return randlangs = "" if utils.extract_arg(message.text, 2) is not None and utils.extract_arg( message.text, 3) is not None: endlang = utils.extract_arg(message.text, 2) + " " + utils.extract_arg( message.text, 3) elif utils.extract_arg(message.text, 2) is not None: endlang = utils.extract_arg(message.text, 2) else: endlang = utils.extract_lang(inputshiz) tmpmessage = utils.bot.reply_to( message, "Генерация начата, осталось " + str(counter * cooldown) + " секунд") idc = tmpmessage.chat.id idm = tmpmessage.message_id for i in range(counter): randlang = random.choice(list(LANGUAGES)) randlangs += randlang + "; " for iteration in range( attempts ): # three tries as default, if = 0 => without checking inputshizchecker = inputshiz try: inputshiz = utils.translator.translate(inputshiz, randlang).text if inputshizchecker != inputshiz: break except Exception as e: if str(e) in "invalid destination language": pass else: logger.write_log("ERR: " + str(e) + "\n" + traceback.format_exc()) utils.bot.edit_message_text( "Ошибка искажения текста. Обратитесь к авторам бота\n" "Информация для отладки сохранена в логах бота.", idc, idm) return if iteration == attempts - 1: logger.write_log("ERR GOOGLE_API_REJECT") utils.bot.edit_message_text( "Неизвестная ошибка перевода. Повторите попытку позже.\n" "Возможно, запрос был заблокирован Google Api", idc, idm) return time.sleep(cooldown) outstr = "Готова итерация " + str(i + 1) + "/" + str(counter) + "\n" \ "Осталось " + str((counter - i - 1) * cooldown) + " секунд" utils.bot.edit_message_text(outstr, idc, idm) try: inputshiz = utils.translator.translate(inputshiz, endlang).text except Exception as e: if str(e) in "invalid destination language": endlang = utils.extract_lang(utils.textparser(message)) inputshiz = utils.translator.translate(inputshiz, endlang).text utils.bot.edit_message_text( inputshiz + "\n\nИспользовались искажения: " + randlangs, idc, idm)
def start(message): if utils.chat_test(message.chat.id, message.chat.username) != 0: return log(message) if message.chat.username is None: bog.reply_to( message, "Многопользовательские игры не работают с пользователями без ников" ) return arg = utils.extract_arg(message.text) if len(arg) == 0: bog.send_message(message.chat.id, consts.ticrules, parse_mode="markdown") elif len(arg) > 1: bog.reply_to(message, "Это не похоже на имя пользователя") else: if not (tictac.find_one({"_id": message.chat.id}) or tictac.find_one({"_id2": message.chat.id})): enemy = list(arg[0]) if enemy[0] == "@": del enemy[0] enemy = "".join(enemy) find = users.find_one({"n": enemy}) if not find: bog.reply_to( message, "Не найден пользователь в базе." + " Возможно, данные противника в базе устаревшие", ) return enemy_id = find["_id"] if not (tictac.find_one({"_id": enemy_id}) or tictac.find_one({"_id2": enemy_id})): invite(message.chat.id, enemy_id, enemy) else: bog.reply_to( message, "У вашего противника найдена незавершенная игра\n" + "Он должен ее завершить/удалить прежде, чем продолжить", ) elif tictac.find_one({"_id": message.chat.id}): type = tictac.find_one({"_id": message.chat.id})["m"] if int(type) == 2: text = "ваше отправленное приглашение" else: text = "вашу прошлую игру с" enemyid = tictac.find_one({"_id": message.chat.id})["_id2"] enemy = users.find_one({"_id": enemyid})["n"] bog.reply_to(message, f"Найдено {text} @{enemy}", reply_markup=MARKUP.SURRENDER(0)) elif tictac.find_one({"_id2": message.chat.id}): type = tictac.find_one({"_id2": message.chat.id})["m"] if int(type) == 2: text = "ваше отправленное приглашение" else: text = "вашу прошлую игру с" enemyid = tictac.find_one({"_id2": message.chat.id})["_id"] enemy = users.find_one({"_id": enemyid})["n"] bog.reply_to(message, f"Найдено {text} @{enemy}", reply_markup=MARKUP.SURRENDER(1))
def distort_main(message): if max_inits == 0: utils.bot.reply_to( message, locales.get_text(message.chat.id, "distortDisabled")) return inputshiz = utils.textparser(message) if inputshiz is None: logger.write_log(message, "none") return logger.write_log(message, inputshiz) try: counter = int(utils.extract_arg(message.text, 1)) except (ValueError, TypeError): utils.bot.reply_to(message, locales.get_text(message.chat.id, "distortNaN")) return if counter > max_inits or counter < 1: utils.bot.reply_to( message, locales.get_text(message.chat.id, "distortWrongNumber").format(str(max_inits))) return randlangs_list = "" if utils.extract_arg(message.text, 2) is not None: endlang = utils.extract_arg(utils.lang_autocorr(message.text), 2) if interlayer.lang_list.get(endlang) is None: utils.bot.reply_to( message, locales.get_text(message.chat.id, "distortWrongLang")) return else: endlang = interlayer.extract_lang(inputshiz) tmpmessage = utils.bot.reply_to( message, locales.get_text(message.chat.id, "distortStarted")) idc = tmpmessage.chat.id idm = tmpmessage.message_id lastlang = interlayer.extract_lang(inputshiz) randlang = random.choice(list(interlayer.lang_list)) for i in range(counter): while randlang == lastlang: randlang = random.choice(list(interlayer.lang_list)) randlangs_list += randlang + "; " try: inputshiz = interlayer.get_translate(inputshiz, randlang, True) except interlayer.TooManyRequestException: utils.bot.edit_message_text( locales.get_text(message.chat.id, "tooManyRequestException"), idc, idm) return except interlayer.TooLongMsg: utils.bot.edit_message_text( locales.get_text(message.chat.id, "tooLongMsg"), idc, idm) return except interlayer.UnkTransException: utils.bot.edit_message_text( locales.get_text(message.chat.id, "distortUnkTransException"), idc, idm) return lastlang = randlang try: inputshiz = interlayer.get_translate(inputshiz, endlang) except (interlayer.UnkTransException, interlayer.TooLongMsg, interlayer.TooManyRequestException, interlayer.BadTrgLangException): utils.bot.reply_to( message, locales.get_text(message.chat.id, "distortEndingError")) utils.bot.edit_message_text( inputshiz + locales.get_text(message.chat.id, "usedDistortions") + randlangs_list + ad_module.add_ad(idc), idc, idm)