async def do_backup(chat_id, reply=False): await bot.send_message(chat_id, "Dumping the DB, please wait...", reply_to_message_id=reply) date = strftime("%Y-%m-%d_%H:%M:%S", gmtime()) file_name = f"Backups/dump_{date}.7z" if not os.path.exists("Backups/"): os.mkdir("Backups/") await term( f"mongodump --uri \"{get_config_key('mongo_conn')}\" --out=Backups/tempbackup" ) # Let's also save Redis cache with open('Backups/tempbackup/redis_keys.json', 'w+') as f: keys = redis.keys() new = {} for key in keys: key_type = redis.type(key) if key_type == 'string': new[key] = redis.get(key) elif key_type == 'list': new[key] = list(redis.lrange(key, 0, -1)) f.write(ujson.dumps(new, indent=2)) # Copy config file shutil.copyfile('data/bot_conf.yaml', 'Backups/tempbackup/bot_conf.yaml') await bot.send_message(chat_id, "Compressing and uploading to Telegram...", reply_to_message_id=reply) password = get_config_key("backups_password") await term( f"cd Backups/tempbackup/; 7z a -mx9 ../../{file_name} * -p{password} -mhe=on" ) shutil.rmtree('Backups/tempbackup') if not os.path.exists(file_name): await bot.send_message(chat_id, "Error!", reply_to_message_id=reply) return text = "<b>Backup created!</b>" size = convert_size(os.path.getsize(file_name)) text += f"\nBackup name: <code>{file_name}</code>" text += f"\nSize: <code>{size}</code>" await tbot.send_file(chat_id, file_name, reply_to=reply, caption=text, parse_mode="html")
async def import_cas_bans(): if get_config_key('sync_cas_bans') is False: return url = 'https://combot.org/api/cas/export.csv' ffile = requests.get(url, allow_redirects=True) cas_banned = [] num = 0 for user_id in io.StringIO(ffile.text): cas_banned.append(user_id[:-2]) text = f"Start importing <code>{len(cas_banned)}</code> CAS bans" if get_config_key('gbans_channel_enabled') is True: await bot.send_message(get_config_key('gbans_channel'), text) s_num = 0 for user_id in cas_banned: await asyncio.sleep(0.1) num += 1 print(f"{num}/{len(cas_banned)}") gbanned = mongodb.blacklisted_users.find_one({'user': user_id}) if gbanned: print("already gbanned") continue date = strftime("%Y-%m-%d %H:%M:%S", gmtime()) new = { 'user': user_id, 'date': date, 'by': "SophieBot import module", 'reason': "CAS banned" } mongodb.blacklisted_users.insert_one(new) s_num += 1 text = f"Imported {s_num} CAS bans." if get_config_key('gbans_channel_enabled') is True: await bot.send_message(get_config_key('gbans_channel'), text)
async def report_error(query): channel_id = get_config_key("errors_channel") chat_id = query.message.chat.id if await is_user_admin(chat_id, query.from_user.id) is False: await query.answer("Only admins can report errors!") return await bot.forward_message(channel_id, chat_id, query.message.message_id) buttons = InlineKeyboardMarkup(row_width=1).add( InlineKeyboardButton( "Delete message", callback_data='get_delete_msg_{}_admin'.format(chat_id))) text = "<b>Sorry, I encountered a error!</b>\n" text += "Error reported, your report file will be erased in 3 weeks.\n" text += "<a href=\"https://t.me/SophieSupport\">Sophie support chat</a>" await query.message.edit_caption(text, reply_markup=buttons) await query.answer("Error reported! Thank you.")
from sophie_bot.config import get_config_key # Constants FOX_CHATS = [ 483808054, -1001287179850, -1001280218923, -1001155400138, -1001362128194 ] FOX_BETA_CHATS = [-1001280218923, -1001362128194, 483808054] FOX_DEV_CHAT = -1001155400138 FOX_DOMAIN = 'https://files.orangefox.tech/' FOX_STABLE_CHANNEL = -1001196811863 FOX_BETA_CHANNEL = -1001429093106 SF_host = 'web.sourceforge.net' SF_user = '******' SF_pass = get_config_key('fox_sf_pass') # FOX_FILES_LOCAL = '/home/yacha/ofoxtest/' FOX_FILES_LOCAL = '/var/www/fox_files/' # State class ReleaseState(StatesGroup): sel_build_type = State() upload_file = State() write_changelog = State() write_bugs = State() write_build_notes = State() releasing = State()
async def backup(): if get_config_key('auto_backups_enabled') is False: return channel_id = get_config_key('logs_channel_id') await do_backup(channel_id)
import glob import os.path from sophie_bot import logger from sophie_bot.config import get_config_key NO_LOAD_COMPONENTS = get_config_key("not_load_this_components") def list_all_components(): components = [] mod_paths = glob.glob(os.path.dirname(__file__) + "/*.py") all_components = [ os.path.basename(f)[:-3] for f in mod_paths if os.path.isfile(f) and f.endswith(".py") and not f.endswith("__init__.py") ] for component in all_components: if component not in NO_LOAD_COMPONENTS: components.append(component) return components ALL_COMPONENTS = sorted(list(list_all_components())) print(ALL_COMPONENTS) logger.info("Components to load: %s", str(ALL_COMPONENTS)) __all__ = ALL_COMPONENTS + ["ALL_COMPONENTS"]
import re import time from importlib import import_module from aiogram import types from aiogram.dispatcher.handler import SkipHandler from telethon import events from sophie_bot import BOT_USERNAME, DEBUG_MODE, tbot, dp, logger from sophie_bot.config import get_config_key from sophie_bot.modules.helper_func.error import report_error from sophie_bot.modules.helper_func.flood import prevent_flooding import_module("sophie_bot.modules.helper_func.bount_filter") ALLOW_F_COMMANDS = get_config_key("allow_forwards_commands") ALLOW_COMMANDS_FROM_EXC = get_config_key("allow_commands_with_!") BLOCK_GBANNED_USERS = get_config_key("block_gbanned_users") RATE_LIMIT = get_config_key("rate_limit") REGISTRED_COMMANDS = [] def register(cmds=None, f=None, allow_edited=True, allow_kwargs=False, *args, **kwargs): if cmds and type(cmds) == str: cmds = [cmds] register_kwargs = {} if cmds:
import asyncio import os import signal from importlib import import_module import hypercorn from sophie_bot import bot, tbot, redis, logger, dp, quart from sophie_bot.config import get_config_key from sophie_bot.modules import ALL_MODULES # import uvloop LOAD_COMPONENTS = get_config_key("load_components") CATCH_UP = get_config_key("skip_catch_up") LOADED_MODULES = [] # Import modules for module_name in ALL_MODULES: logger.debug("Importing " + module_name) imported_module = import_module("sophie_bot.modules." + module_name) LOADED_MODULES.append(imported_module) logger.info("Modules loaded!") if LOAD_COMPONENTS is True: from sophie_bot.modules.components import ALL_COMPONENTS
async def report_error(event, telethon=False): error = str(sys.exc_info()[1]) class_error = sys.exc_info()[0].__name__ if class_error == 'ChatWriteForbiddenError': # This error mean bot is muted in chat return elif class_error == 'BadRequest' and error == 'Have no rights to send a message': return elif class_error == 'RetryAfter': return if telethon: msg = event chat_id = msg.chat_id lib = 'Telethon' else: lib = 'Aiogram' if 'callback_query' in event: msg = event.callback_query.message else: msg = event.message chat_id = msg.chat.id date = strftime("%Y-%m-%d %H:%M:%S", gmtime()) logger.error("Error: " + date) logger.error("Lib: " + lib) if telethon: logger.error(traceback.format_exc()) if DEBUG_MODE: await msg.reply(error) return new = { 'error_class_name': class_error, 'error': error, 'date': datetime.datetime.now() } mongodb.errors.insert_one(new) # text = "<b>Sorry, I encountered a error!</b>\n" text = random.choice(RANDOM_ERROR_TITLES) text += "\n<a href=\"https://t.me/SophieSupport\">Sophie support chat</a>" ftext = "Sophie error log file." ftext += "\n______________________\n" ftext += "\nIf you wanna you can report it - just press the \"Report error\" button." ftext += "\nTill you press report button your data will be only here." ftext += "\n______________________\n" ftext += "\nDate: " + date ftext += "\nLib: " + lib ftext += "\nGroup ID: " + str(chat_id) ftext += "\nSender ID: " + str(msg.from_user.id if lib == "Aiogram" else msg.from_id) ftext += "\nText: " + str(msg.text or "") ftext += "\n\nRaw update text:\n" ftext += str(event) ftext += "\n\nTraceback info:\n" ftext += str(traceback.format_exc()) ftext += "\n\nFormatted update text:\n" ftext += str(ujson.dumps(msg, indent=2)) command = "git log --pretty=format:\"%an: %s\" -5" ftext += "\n\n\nLast 5 commits:\n" ftext += await term(command) buttons = InlineKeyboardMarkup(row_width=2).add( InlineKeyboardButton("Delete message", callback_data='get_delete_msg_{}_admin'.format(chat_id)) ) if get_config_key("errors_channel_enabled"): buttons.insert(InlineKeyboardButton("Report crash", callback_data='report_error')) await bot.send_document( chat_id, types.InputFile(io.StringIO(ftext), filename="CrashReport.txt"), caption=text, reply_to_message_id=msg.message_id if lib == "Aiogram" else msg.message.id, reply_markup=buttons ) return
import glob import os.path from sophie_bot import logger from sophie_bot.config import get_config_key NO_LOAD_COMPONENTS = get_config_key("disabled_components") def list_all_components(): components = [] mod_paths = glob.glob(os.path.dirname(__file__) + "/*.py") all_components = [ os.path.basename(f)[:-3] for f in mod_paths if os.path.isfile(f) and f.endswith(".py") and not f.endswith("__init__.py") ] for component in all_components: if component not in DISABLED_COMPONENTS: components.append(component) return components ALL_COMPONENTS = sorted(list(list_all_components())) print(ALL_COMPONENTS) logger.info("Components to load: %s", str(ALL_COMPONENTS)) __all__ = ALL_COMPONENTS + ["ALL_COMPONENTS"]