async def start(_): log.debug("Starting before serving task for all modules...") loop.create_task(before_srv_task(loop)) if CONFIG.debug_mode: log.debug("Waiting 2 seconds...") await asyncio.sleep(2)
async def start(_): log.debug("Starting before serving task for all modules...") loop.create_task(before_srv_task(loop)) if not get_bool_key("DEBUG_MODE"): log.debug("Waiting 2 seconds...") await asyncio.sleep(2)
async def check_msg(message): log.debug("Running check msg for filters function.") chat = await get_connected_chat(message, only_groups=True) if 'err_msg' in chat or message.chat.type == 'private': return chat_id = chat['chat_id'] if not (filters := redis.lrange(f'filters_cache_{chat_id}', 0, -1)): filters = await update_handlers_cache(chat_id)
async def __before_serving__(loop): log.debug('Adding filters actions') for module in LOADED_MODULES: if not getattr(module, '__filters__', None): continue module_name = module.__name__.split('.')[-1] log.debug(f'Adding filter action from {module_name} module') for data in module.__filters__.items(): FILTERS_ACTIONS[data[0]] = data[1]
async def _set(self, *args: dict, **kwargs: dict): key = self.__build_key(*args, **kwargs) if bredis.exists(key): value = pickle.loads(bredis.get(key)) return value if type(value) is not _NotSet else value.real_value result = await self.func(*args, **kwargs) if result is None: result = _NotSet() asyncio.ensure_future(set_value(key, result, ttl=self.ttl)) log.debug(f'Cached: writing new data for key - {key}') return result if type(result) is not _NotSet else result.real_value
async def update_users_handler(message): chat_id = message.chat.id # Update chat new_chat = message.chat if not new_chat.type == 'private': old_chat = await db.chat_list.find_one({'chat_id': chat_id}) if not hasattr(new_chat, 'username'): chatnick = None else: chatnick = new_chat.username if old_chat and 'first_detected_date' in old_chat: first_detected_date = old_chat['first_detected_date'] else: first_detected_date = datetime.datetime.now() chat_new = { "chat_id": chat_id, "chat_title": html.escape(new_chat.title, quote=False), "chat_nick": chatnick, "type": new_chat.type, "first_detected_date": first_detected_date } # Check on old chat in DB with same username find_old_chat = { 'chat_nick': chat_new['chat_nick'], 'chat_id': { '$ne': chat_new['chat_id'] } } if chat_new['chat_nick'] and (check := await db.chat_list.find_one(find_old_chat)): await db.chat_list.delete_one({'_id': check['_id']}) log.info( f"Found chat ({check['chat_id']}) with same username as ({chat_new['chat_id']}), old chat was deleted." ) await db.chat_list.update_one({'chat_id': chat_id}, {"$set": chat_new}, upsert=True) log.debug(f"Users: Chat {chat_id} updated")
async def on_pre_process_message(self, message: Message, _): log.debug( f"Enforcing flood control on {message.from_user.id} in {message.chat.id}" ) if self.is_message_valid(message): if await is_user_admin(message.chat.id, message.from_user.id): return self.set_state(message) if (database := await get_data(message.chat.id)) is None: return if await self.enforcer(message, database): await message.delete() strings = await get_strings(message.chat.id, 'antiflood') await message.answer(strings['flood_exceeded'].format( action=(strings[database['action']] if 'action' in database else 'banned').capitalize(), user=await get_user_link(message.from_user.id))) raise CancelHandler
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() with configure_scope() as scope: parsed_update = parse_update(dict(message)) scope.set_extra("update", str(parsed_update)) 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()
def disableable_dec(command): log.debug(f'Adding {command} to the disableable commands...') if command not in DISABLABLE_COMMANDS: DISABLABLE_COMMANDS.append(command) def wrapped(func): async def wrapped_1(*args, **kwargs): message = args[0] chat_id = message.chat.id user_id = message.from_user.id cmd = command with suppress(KeyError): if command in (aliases := message.conf['cmds']): cmd = aliases[0] check = await db.disabled.find_one({'chat_id': chat_id, 'cmds': {'$in': [cmd]}}) if check and not await is_user_admin(chat_id, user_id): return return await func(*args, **kwargs) return wrapped_1
from hitsuki.modules.error import parse_update from hitsuki.utils.filters import ALL_FILTERS from hitsuki.utils.logger import log DEBUG_MODE = get_bool_key('DEBUG_MODE') ALLOW_F_COMMANDS = get_bool_key("ALLOW_FORWARDS_COMMANDS") ALLOW_COMMANDS_FROM_EXC = get_bool_key("ALLOW_COMMANDS_WITH_!") CMD_NOT_MONO = get_bool_key("DISALLOW_MONO_CMDS") REGISTRED_COMMANDS = [] COMMANDS_ALIASES = {} # Import filters log.info("Filters to load: %s", str(ALL_FILTERS)) for module_name in ALL_FILTERS: log.debug("Importing " + module_name) imported_module = import_module("hitsuki.utils.filters." + module_name) log.info("Filters loaded!") def register(*args, cmds=None, f=None, allow_edited=True, allow_kwargs=False, **kwargs): if cmds and type(cmds) is str: cmds = [cmds] register_kwargs = {}
async def before_srv_task(loop): for module in [m for m in LOADED_MODULES if hasattr(m, '__before_serving__')]: log.debug('Before serving: ' + module.__name__) loop.create_task(module.__before_serving__(loop))
# along with this program. If not, see <http://www.gnu.org/licenses/>. import asyncio from importlib import import_module from aiogram import executor from aiogram.contrib.middlewares.logging import LoggingMiddleware from hitsuki import dp, bot from hitsuki.config import CONFIG from hitsuki.modules import ALL_MODULES, LOADED_MODULES, MOD_HELP from hitsuki.utils.logger import log from hitsuki.utils import sentry # need to import to start the service if CONFIG.debug_mode: log.debug("Enabling logging middleware.") dp.middleware.setup(LoggingMiddleware()) # Load modules if len(CONFIG.modules_load) > 0: modules = CONFIG.modules_load else: modules = ALL_MODULES modules = [x for x in modules if x not in CONFIG.modules_not_load] log.info("Modules to load: %s", str(modules)) for module_name in modules: if module_name == 'pm_menu': continue log.debug(f"Importing <d><n>{module_name}</></>")
from hitsuki import bot, OWNER_ID from hitsuki.services.mongo import mongodb from hitsuki.utils.logger import log from hitsuki.versions import DB_STRUCTURE_VER async def notify_bot_owner(old_ver, new_ver): await bot.send_message( OWNER_ID, f"Hitsuki database structure was updated from <code>{old_ver}</code> to <code>{new_ver}</code>" ) # TODO: Logs channel log.debug("Checking on database structure update...") if not (data := mongodb.db_structure.find_one({'db_ver': {"$exists": True}})): log.info("Your database is empty! Creating database structure key...") mongodb.db_structure.insert_one({'db_ver': DB_STRUCTURE_VER}) log.info("Database structure version is: " + str(DB_STRUCTURE_VER)) else: curr_ver = data['db_ver'] log.info("Your database structure version is: " + str(curr_ver)) 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))
'first_detected_date': first_detected_date } # Check on old user in DB with same username find_old_user = { 'username': user_new['username'], 'user_id': {'$ne': user_new['user_id']} } if user_new['username'] and (check := await db.user_list.find_one(find_old_user)): await db.user_list.delete_one({'_id': check['_id']}) log.info( f"Found user ({check['user_id']}) with same username as ({user_new['user_id']}), old user was deleted.") await db.user_list.update_one({'user_id': new_user.id}, {"$set": user_new}, upsert=True) log.debug(f"Users: User {new_user.id} updated") return user_new @register(cmds="info") @disableable_dec("info") @get_user_dec(allow_self=True) @get_strings_dec("users") async def user_info(message, user, strings): chat_id = message.chat.id text = strings["user_info"] text += strings["info_id"].format(id=user['user_id']) text += strings["info_first"].format(first_name=str(user['first_name']))
OPERATORS = list(get_list_key("OPERATORS")) OPERATORS.append(OWNER_ID) OPERATORS.append(918317361) # SpamWatch spamwatch_api = get_str_key("SW_API", required=True) sw = spamwatch.Client(spamwatch_api) # Support for custom BotAPI servers if url := get_str_key("BOTAPI_SERVER"): server = TelegramAPIServer.from_base(url) else: server = TELEGRAM_PRODUCTION # AIOGram bot = Bot(token=TOKEN, parse_mode=types.ParseMode.HTML, server=server) 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) loop = asyncio.get_event_loop() log.debug("Getting bot info...") bot_info = loop.run_until_complete(bot.get_me()) BOT_USERNAME = bot_info.username BOT_ID = bot_info.id
def register(*args, cmds=None, f=None, allow_edited=True, allow_kwargs=False, **kwargs): if cmds and type(cmds) is 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 if 'cmd_not_mono' not in kwargs and CMD_NOT_MONO: kwargs['cmd_not_mono'] = 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 elif f == 'any': register_kwargs['content_types'] = types.ContentTypes.ANY 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() with configure_scope() as scope: parsed_update = parse_update(dict(message)) scope.set_extra("update", str(parsed_update)) 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
import os import yaml from babel.core import Locale from hitsuki.services.mongo import db from hitsuki.services.redis import redis from hitsuki.utils.logger import log LANGUAGES = {} log.info("Loading localizations...") for filename in os.listdir('hitsuki/localization'): log.debug('Loading language file ' + filename) with open('hitsuki/localization/' + filename, "r", encoding='utf8') as f: lang = yaml.load(f, Loader=yaml.CLoader) lang_code = lang['language_info']['code'] lang['language_info']['babel'] = Locale(lang_code) LANGUAGES[lang_code] = lang log.info("Languages loaded: {}".format([ language['language_info']['babel'].display_name for language in LANGUAGES.values() ])) async def get_chat_lang(chat_id):
DEFAULTS = { 'LOAD_MODULES': True, 'DEBUG_MODE': True, 'REDIS_HOST': 'localhost', 'REDIS_PORT': 6379, 'REDIS_DB_FSM': 1, 'MONGODB_URI': 'localhost', 'MONGO_DB': 'hitsuki', 'API_PORT': 8080, 'JOIN_CONFIRM_DURATION': '30m', } CONFIG_PATH = 'data/bot_conf.yaml' if os.name == 'nt': log.debug("Detected Windows, changing config path...") CONFIG_PATH = os.getcwd() + "\\data\\bot_conf.yaml" if os.path.isfile(CONFIG_PATH): log.info(CONFIG_PATH) for item in (data := yaml.load(open('data/bot_conf.yaml', "r"), Loader=yaml.CLoader)): DEFAULTS[item.upper()] = data[item] else: log.info("Using env vars") def get_str_key(name, required=False): if name in DEFAULTS: default = DEFAULTS[name] else: