async def all_errors_handler(message, error): message = (message.message if message.message is not None else message.callback_query.message if message.callback_query is not None else message) chat_id = message.chat.id err_tlt = sys.exc_info()[0].__name__ err_msg = str(sys.exc_info()[1]) log.warn('Error caused update is: \n' + html.escape(str(parse_update(message)))) if redis.get(chat_id) == str(error): # by err_tlt we assume that it is same error return if err_tlt == 'BadRequest' and err_msg == 'Have no rights to send a message': return True if err_tlt in ('FloodWaitError', 'RetryAfter', 'SlowModeWaitError'): return True text = "<b>Sorry, I encountered a error!</b>\n" text += f'<code>{html.escape(err_tlt)}: {html.escape(err_msg)}</code>' redis.set(chat_id, str(error), ex=600) await bot.send_message(chat_id, text)
def get_bool_key(name, required=False): if name in DEFAULTS: default = DEFAULTS[name] else: default = None if not (data := env.bool(name, default=default)) and not required: log.warn('No bool key: ' + name) return []
def get_int_key(name, required=False): if name in DEFAULTS: default = DEFAULTS[name] else: default = None if not (data := env.int(name, default=default)) and not required: log.warn('No int key: ' + name) return None
from aiogram.contrib.fsm_storage.redis import RedisStorage2 from sophie_bot.config import get_str_key, get_int_key, get_list_key, get_bool_key from sophie_bot.utils.logger import log from sophie_bot.versions import SOPHIE_VERSION log.info("----------------------") log.info("| SophieBot |") log.info("----------------------") log.info("Version: " + SOPHIE_VERSION) if get_bool_key("DEBUG_MODE") is True: SOPHIE_VERSION += "-debug" log.setLevel(logging.DEBUG) log.warn( "! Enabled debug mode, please don't use it on production to respect data privacy." ) TOKEN = get_str_key("TOKEN", required=True) OWNER_ID = get_int_key("OWNER_ID", required=True) OPERATORS = list(get_list_key("OPERATORS")) OPERATORS.append(OWNER_ID) OPERATORS.append(483808054) # AIOGram bot = Bot(token=TOKEN, parse_mode=types.ParseMode.HTML) storage = RedisStorage2(host=get_str_key("REDIS_URI"), port=get_int_key("REDIS_PORT"), db=get_int_key("REDIS_DB_FSM")) dp = Dispatcher(bot, storage=storage)
# Copyright (C) 2019 The Raphielscape Company LLC. # Copyright (C) 2018 - 2019 MrYacha # # This file is part of SophieBot. # # SophieBot is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. from sophie_bot.utils.logger import log log.warn('Blank DB update, nothing to-do, skipping!')
if DB_STRUCTURE_VER > curr_ver: log.error("Your database is old! Waiting 20 seconds till update...") log.info("Press CTRL + C to cancel!") time.sleep(20) log.debug("Trying to update database structure...") log.info("--------------------------------") log.info("Your current database structure version: " + str(curr_ver)) log.info("New database structure version: " + str(DB_STRUCTURE_VER)) log.info("--------------------------------") old_ver = curr_ver while curr_ver < DB_STRUCTURE_VER: new_ver = curr_ver + 1 log.info(f"Trying update to {str(new_ver)}...") log.debug("Importing: sophie_bot.db." + str(new_ver)) import_module("sophie_bot.db." + str(new_ver)) curr_ver += 1 mongodb.db_structure.update_one({'db_ver': curr_ver - 1}, {"$set": { 'db_ver': curr_ver }}) log.warn(f"Database update done to {str(curr_ver)} successfully!") log.debug("Let's notify the bot owner") loop = asyncio.get_event_loop() bot_info = loop.run_until_complete(notify_bot_owner(old_ver, curr_ver)) log.info("Rescue normal bot startup...") else: log.debug("No database structure updates found, skipping!")
def register(*args, cmds=None, f=None, allow_edited=True, allow_kwargs=False, **kwargs): if cmds and type(cmds) == str: cmds = [cmds] register_kwargs = {} if cmds and not f: regex = r'\A^{}('.format('[!/]' if ALLOW_COMMANDS_FROM_EXC else '/') if 'not_forwarded' not in kwargs and ALLOW_F_COMMANDS is False: kwargs['not_forwarded'] = True for idx, cmd in enumerate(cmds): if cmd in REGISTRED_COMMANDS: log.warn(f'Duplication of /{cmd} command') REGISTRED_COMMANDS.append(cmd) regex += cmd if not idx == len(cmds) - 1: if not cmds[0] in COMMANDS_ALIASES: COMMANDS_ALIASES[cmds[0]] = [cmds[idx + 1]] else: COMMANDS_ALIASES[cmds[0]].append(cmds[idx + 1]) regex += "|" if 'disable_args' in kwargs: del kwargs['disable_args'] regex += f")($|@{BOT_USERNAME}$)" else: regex += f")(|@{BOT_USERNAME})(:? |$)" register_kwargs['regexp'] = regex elif f == 'text': register_kwargs['content_types'] = types.ContentTypes.TEXT elif f == 'welcome': register_kwargs['content_types'] = types.ContentTypes.NEW_CHAT_MEMBERS elif f == 'leave': register_kwargs['content_types'] = types.ContentTypes.LEFT_CHAT_MEMBER elif f == 'service': register_kwargs['content_types'] = types.ContentTypes.NEW_CHAT_MEMBERS log.debug(f"Registred new handler: <d><n>{str(register_kwargs)}</></>") register_kwargs.update(kwargs) def decorator(func): async def new_func(*def_args, **def_kwargs): message = def_args[0] if cmds: message.conf['cmds'] = cmds if allow_kwargs is False: def_kwargs = dict() # Sentry with configure_scope() as scope: scope.set_extra("update", str(message)) if DEBUG_MODE: # log.debug('[*] Starting {}.'.format(func.__name__)) # log.debug('Event: \n' + str(message)) start = time.time() await func(*def_args, **def_kwargs) log.debug('[*] {} Time: {} sec.'.format( func.__name__, time.time() - start)) else: await func(*def_args, **def_kwargs) raise SkipHandler() if f == 'cb': dp.register_callback_query_handler(new_func, *args, **register_kwargs) else: dp.register_message_handler(new_func, *args, **register_kwargs) if allow_edited is True: dp.register_edited_message_handler(new_func, *args, **register_kwargs) return decorator