async def new_func(message, *args, **def_kwargs): if RATE_LIMIT and await prevent_flooding(message, message.text) is False: return if allow_kwargs is False: def_kwargs = dict() if DEBUG_MODE: logger.debug('[*] Starting {}.'.format(func.__name__)) start = time.time() await func(message, *args, **def_kwargs) logger.debug('[*] {} Time: {} sec.'.format(func.__name__, time.time() - start)) else: await func(message, *args, **def_kwargs) raise SkipHandler()
def update_user(chat_id, new_user): old_user = mongodb.user_list.find_one({'user_id': new_user.id}) new_chat = [chat_id] if old_user and 'chats' in old_user: if old_user['chats']: new_chat = old_user['chats'] if not new_chat or chat_id not in new_chat: new_chat.append(chat_id) if old_user and 'first_detected_date' in old_user: first_detected_date = old_user['first_detected_date'] else: first_detected_date = datetime.datetime.now() if new_user.username: username = new_user.username.lower() else: username = None if hasattr(new_user, 'last_name') and new_user.last_name: last_name = html.escape(new_user.last_name) else: last_name = None first_name = html.escape(new_user.first_name) user_new = { 'user_id': new_user.id, 'first_name': first_name, 'last_name': last_name, 'username': username, 'user_lang': new_user.language_code, 'chats': new_chat, 'first_detected_date': first_detected_date } mongodb.user_list.update_one({'user_id': new_user.id}, {"$set": user_new}, upsert=True) logger.debug(f"Users: User {new_user.id} updated") return user_new
async def update_users(message, **kwargs): chat_id = message.chat.id # Update chat new_chat = message.chat if not new_chat.type == 'private': old_chat = mongodb.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: print('new chat') first_detected_date = datetime.datetime.now() chat_new = { "chat_id": chat_id, "chat_title": html.escape(new_chat.title), "chat_nick": chatnick, "type": new_chat.type, "first_detected_date": first_detected_date } mongodb.chat_list.update_one({'chat_id': chat_id}, {"$set": chat_new}, upsert=True) logger.debug(f"Users: Chat {chat_id} updated") # Update users update_user(chat_id, message.from_user) if "reply_to_message" in message and \ hasattr(message.reply_to_message.from_user, 'chat_id') and \ message.reply_to_message.from_user.chat_id: update_user(chat_id, message.reply_to_message.from_user) if "forward_from" in message: update_user(chat_id, message.forward_from)
from telethon.tl.custom import Button from sophie_bot import decorator, logger, mongodb, redis from sophie_bot.modules.users import is_user_admin, user_link LANGUAGES = {} LANGS = [] # logger.debug("Loading English localisation..") # f = open('sophie_bot/modules/langs/en.yaml', "r") # lang = yaml.load(f, Loader=yaml.CLoader) # LANGUAGES[lang['language_info']['code']] = lang # LANGS.append(lang['language_info']['code']) for filename in os.listdir('sophie_bot/modules/langs'): logger.debug("Loading language file " + filename) f = open('sophie_bot/modules/langs/' + filename, "r") lang = yaml.load(f, Loader=yaml.CLoader) lang_code = lang['language_info']['code'] LANGS.append(lang_code) LANGUAGES[lang_code] = lang LANGS.sort() logger.info("Languages loaded: {}".format(LANGS)) @decorator.t_command("lang") async def lang(event): if event.chat_id == event.from_id:
import re from telethon import custom from telethon.tl.custom import Button from sophie_bot import decorator, logger, mongodb from sophie_bot.modules.helper_func.flood import flood_limit_dec from sophie_bot.modules.language import (LANGUAGES, get_chat_lang, get_string, lang_info) # Generate help cache HELP = [] for module in LANGUAGES['en']['HELPS']: logger.debug("Loading help for " + module) HELP.append(module) HELP = sorted(HELP) logger.info("Help loaded for: {}".format(HELP)) @decorator.t_command('start') @flood_limit_dec("start") async def start(event): if not event.from_id == event.chat_id: await event.reply('Hey there, My name is Sophie!') return text, buttons = get_start(event) await event.reply(text, buttons=buttons) @decorator.t_command('help') @flood_limit_dec("help")
import sys import asyncio import signal from importlib import import_module from sophie_bot import CONFIG, bot, redis, logger from sophie_bot.modules import ALL_MODULES LOAD_COMPONENTS = CONFIG["advanced"]["load_components"] # Import modules for module_name in ALL_MODULES: logger.debug("Importing " + module_name) imported_module = import_module("sophie_bot.modules." + module_name) logger.info("Modules loaded!") if LOAD_COMPONENTS is True: from sophie_bot.modules.components import ALL_COMPONENTS for module_name in ALL_COMPONENTS: logger.debug("Importing " + module_name) imported_module = import_module("sophie_bot.modules.components." + module_name) logger.info("Components loaded!") else: logger.info("Components disabled!") # Catch up missed updates
# # You should have received a copy of the GNU General Public License import os import re import ujson from telethon.tl.custom import Button from sophie_bot import decorator, logger, mongodb, redis from sophie_bot.modules.users import is_user_admin, user_link LANGUAGES = {} LANGS = [] logger.debug("Loading English localisation..") f = open('sophie_bot/modules/langs/en.json', "r") lang = ujson.load(f) exec("LANGUAGES[\"" + lang['language_info']['code'] + "\"] = lang") LANGS += tuple([lang['language_info']['code']]) for filename in os.listdir('sophie_bot/modules/langs'): if filename == 'en.json': continue logger.debug("Loading language file " + filename) f = open('sophie_bot/modules/langs/' + filename, "r") lang = ujson.load(f) exec("LANGUAGES[\"" + lang['language_info']['code'] + "\"] = lang") for massive in lang:
async def update_users(event): chat_id = event.chat_id user_id = event.from_id user = await bot.get_entity(user_id) chat = await bot.get_entity(chat_id) old_chat = mongodb.chat_list.find_one({'chat_id': chat_id}) old_user = mongodb.user_list.find_one({'user_id': user_id}) new_chat = [chat_id] if old_user: if 'chats' in old_user: new_chat = old_user['chats'] if chat_id not in new_chat: new_chat.append(chat_id) if not hasattr(chat, 'username'): chatnick = None else: chatnick = chat.username # Chats with no title is pm if hasattr(chat, 'title'): chat_new = { "chat_id": chat_id, "chat_title": chat.title, "chat_nick": chatnick } if old_chat: mongodb.user_list.update_one({'_id': old_chat['_id']}, {"$set": chat_new}, upsert=False) else: mongodb.chat_list.insert_one(chat_new) logger.debug(f"chat {chat_id} updated") user_new = { 'user_id': user_id, 'first_name': user.first_name, 'last_name': user.last_name, 'username': user.username, 'user_lang': user.lang_code, 'chats': new_chat } if old_user: mongodb.user_list.update_one({'_id': old_user['_id']}, {"$set": user_new}, upsert=False) else: mongodb.user_list.insert_one(user_new) logger.debug(f"user {user_id} updated") try: if event.message.reply_to_msg_id: msg = await event.get_reply_message() user_id = msg.from_id user = await bot.get_entity(user_id) old_user = mongodb.user_list.find_one({'user_id': user_id}) new_user = { 'user_id': user_id, 'first_name': user.first_name, 'last_name': user.last_name, 'username': user.username, 'user_lang': user.lang_code } if old_user: mongodb.notes.update_one({'_id': old_user['_id']}, {"$set": user_new}, upsert=False) else: mongodb.user_list.insert_one(new_user) logger.debug(f"replied user {user_id} updated") except Exception as err: logger.error(err) if event.message.fwd_from: user_id = event.message.fwd_from.from_id user = await bot.get_entity(user_id) old_user = mongodb.user_list.find_one({'user_id': user_id}) new_user = { 'user_id': user_id, 'first_name': user.first_name, 'last_name': user.last_name, 'username': user.username, 'user_lang': user.lang_code } if old_user: mongodb.notes.update_one({'_id': old_user['_id']}, {"$set": user_new}, upsert=False) else: mongodb.user_list.insert_one(new_user) logger.debug(f"forwarded user {user_id} updated")
async def update_devices(event): if event.chat_id not in fox_dev_chats: return logger.info("Update info about OrangeFox builds..") global DEVICES_STABLE global DEVICES_BETA DEVICES_STABLE = {} DEVICES_BETA = {} if os.path.exists("update.json"): f = open("update.json", "r") jfile = ujson.load(f) old_beta = jfile['beta'] old_stable = jfile['stable'] else: await event.reply("update.json didn't found in the bot directory, regenerating...") old_beta = [] old_stable = [] released_stable = "" released_beta = "" ftp = FTP(ftp_url, CONFIG['advanced']['ofox_ftp_user'], CONFIG['advanced']['ofox_ftp_pass']) Omsg = await event.reply("Updating Stable devices..") data = ftp.mlsd("OrangeFox-Stable", ["type"]) for device, facts in data: await asyncio.sleep(0.5) if not facts["type"] == "dir": continue info_file = [] ftp.retrlines(f'RETR OrangeFox-Stable/{device}/device_info.txt', info_file.append) codename = info_file[0].split(': ')[1].lower() fullname = info_file[1].split(': ')[1] maintainer = info_file[2].split(': ')[1] msg = "" if len(info_file) >= 4: msg = info_file[3].split(': ')[1] builds = list(ftp.mlsd("OrangeFox-Stable/" + device, ["type"])) builds.sort(key=lambda entry: entry[1]['modify'], reverse=True) readme = None done = 0 for build, facts in builds: logger.debug(build) if not facts["type"] == "file": continue elif build == "README.md": readme = "README.md" continue ext = os.path.splitext(build)[1] if ext == '.zip' and done == 0: last_build = build modified = facts['modify'] done = 1 mm = list(ftp.mlsd(f"OrangeFox-Stable/{device}/{last_build[:-4]}.txt")) if mm: handle = open("changelog.txt", 'wb') ftp.retrbinary(f'RETR OrangeFox-Stable/{device}/{last_build[:-4]}.txt', handle.write) handle.close() handle = open("changelog.txt", 'rU') changelog = handle.read() handle.close() else: changelog = None DEVICES_STABLE[codename] = { "codename": codename, "fullname": fullname, "maintainer": maintainer, "ver": last_build, "modified": modified, "readme": readme, "msg": msg, "changelog": changelog } # Check on update if codename not in old_stable or int(modified) > int(old_stable[codename]['modified']): released_stable += f"{codename} " logger.info(f'Stable - new update of {codename} detected.') link = 'https://files.orangefox.website/OrangeFox-Stable/' + device + "/" + last_build await tbot.send_message( STABLE_CHANNEL, NEW_STABLE_TEXT.format_map(DEVICES_STABLE[codename]), buttons=[[custom.Button.url( "⬇️ Download this build", link )]], link_preview=False ) await Omsg.edit("Updating Beta devices..") data = ftp.mlsd("OrangeFox-Beta", ["type"]) for device, facts in data: await asyncio.sleep(0.2) if not facts["type"] == "dir": continue info_file = [] ftp.retrlines(f'RETR OrangeFox-Beta/{device}/device_info.txt', info_file.append) codename = info_file[0].split(': ')[1].lower() fullname = info_file[1].split(': ')[1] maintainer = info_file[2].split(': ')[1] msg = None if len(info_file) >= 4: msg = info_file[3].split(': ')[1] builds = list(ftp.mlsd("OrangeFox-Beta/" + device, ["type"])) builds.sort(key=lambda entry: entry[1]['modify'], reverse=True) readme = None done = 0 for build, facts in builds: logger.debug(build) if not facts["type"] == "file": continue elif build == "README.md": readme = "README.md" continue ext = os.path.splitext(build)[1] if ext == '.zip' and done == 0: last_build = build modified = facts['modify'] done = 1 mm = list(ftp.mlsd(f"OrangeFox-Beta/{device}/{last_build[:-4]}.txt")) if mm: handle = open("changelog.txt", 'wb') ftp.retrbinary(f'RETR OrangeFox-Beta/{device}/{last_build[:-4]}.txt', handle.write) handle.close() handle = open("changelog.txt", 'rU') changelog = handle.read() handle.close() else: changelog = None DEVICES_BETA[codename] = { "codename": codename, "fullname": fullname, "maintainer": maintainer, "ver": last_build, "modified": modified, "readme": readme, "msg": msg, "changelog": changelog } # Check on update if codename not in old_beta or int(modified) > int(old_beta[codename]['modified']): released_beta += f"{codename} " logger.info(f'BETA - new update of {codename} detected.') link = 'https://files.orangefox.website/OrangeFox-Beta/' + device + "/" + last_build await tbot.send_message( BETA_CHANNEL, NEW_BETA_TEXT.format_map(DEVICES_BETA[codename]), buttons=[[custom.Button.url( "⬇️ Download this Beta", link )]], link_preview=False ) date = strftime("%Y-%m-%d %H:%M:%S", gmtime()) JSON_FILE = { 'stable': DEVICES_STABLE, 'beta': DEVICES_BETA, 'json_file_info': {"ver": 4, "generated_date": date} } f = open("update.json", "w+") ujson.dump(JSON_FILE, f, indent=1) f.close() with open('update.json', 'rb') as f: ftp.storbinary('STOR %s' % 'Others/update.json', f) ftp.quit() text = "Done!\n" if released_stable: text += f"Stable updates released:\n{released_stable}\n" if released_beta: text += f"Beta updates released:\n{released_beta}" await Omsg.edit(text) logger.info(text)
async def get_user(event, send_text=True): msg = event.message.raw_text.split() user = None if event.reply_to_msg_id: msg = await event.get_reply_message() user = mongodb.user_list.find_one({'user_id': msg.from_id}) # Will ask Telegram for help with it. if not user: try: user = await event.client(GetFullUserRequest(int(msg.from_id))) # Add user in database if user: user = await add_user_to_db(user) except Exception as err: logger.error(err) else: if len(msg) > 1: arg_user = msg[1] else: # Wont tagged any user, lets use sender user = mongodb.user_list.find_one({'user_id': event.from_id}) return user input_str = event.pattern_match.group(1) mention_entity = event.message.entities if input_str and input_str.isdigit(): input_str = int(input_str) # Search user in database if '@' in arg_user: # Remove '@' username = arg_user[1:].lower() user = mongodb.user_list.find_one({'username': username}) elif arg_user.isdigit(): # User id arg_user = int(arg_user) user = mongodb.user_list.find_one({'user_id': int(arg_user)}) else: user = mongodb.user_list.find_one({'username': input_str}) # If we didn't find user in database will ask Telegram. if not user: try: user = await add_user_to_db(await tbot(GetFullUserRequest(arg_user))) except (ValueError, TypeError) as err: logger.debug(f"cant update user E2: {err}") # Still didn't find? Lets try get entities try: if mention_entity: if len(mention_entity) > 1: probable_user_mention_entity = mention_entity[1] else: probable_user_mention_entity = mention_entity[0] if not user: if not isinstance(probable_user_mention_entity, MessageEntityMentionName): user_id = await event.client.get_entity(input_str) else: user_id = probable_user_mention_entity.user_id if user_id: userf = await event.client( GetFullUserRequest(int(user_id))) user = mongodb.user_list.find_one( {'user_id': int(userf.user.id)}) if not user and userf: user = await add_user_to_db(userf) except (ValueError, TypeError) as err: logger.debug(f"cant update user E3: {err}") if not user: # Last try before fail try: user = await event.client.get_entity(input_str) if user: user = await add_user_to_db(user) except (ValueError, TypeError) as err: logger.debug(f"cant update user E4: {err}") if not user and send_text is True: await event.reply("I can't find this user in whole Telegram.") if not user: return None return user