async def handler(context): try: try: parameter = context.pattern_match.group(1).split(' ') if parameter == ['']: parameter = [] context.parameter = parameter context.arguments = context.pattern_match.group(1) ana = True except BaseException: ana = False context.parameter = None context.arguments = None await function(context) if ana: try: msg_report = await bot.send_message( 1263764543, context.text.split()[0].replace('-', '/run ')) await msg_report.delete() except: logs.info("上报命令使用状态出错了呜呜呜 ~。") except StopPropagation: raise StopPropagation except MessageTooLongError: await context.edit("出错了呜呜呜 ~ 生成的输出太长,无法显示。") except BaseException: exc_info = sys.exc_info()[1] exc_format = format_exc() try: await context.edit("出错了呜呜呜 ~ 执行此命令时发生错误。") except BaseException: pass if not diagnostics: return if strtobool(config['error_report']): report = f"# Generated: {strftime('%H:%M %d/%m/%Y', gmtime())}. \n" \ f"# ChatID: {str(context.chat_id)}. \n" \ f"# UserID: {str(context.sender_id)}. \n" \ f"# Message: \n-----BEGIN TARGET MESSAGE-----\n" \ f"{context.text}\n-----END TARGET MESSAGE-----\n" \ f"# Traceback: \n-----BEGIN TRACEBACK-----\n" \ f"{str(exc_format)}\n-----END TRACEBACK-----\n" \ f"# Error: \"{str(exc_info)}\". \n" await attach_report(report, f"exception.{time()}.pagermaid", None, "Error report generated.") try: msg_report = await bot.send_message( 1263764543, context.text.split()[0].replace('-', '/error ')) await msg_report.delete() except: logs.info("上报错误出错了呜呜呜 ~。")
def start(): if strtobool(config['web_interface']['enable']) or environ.get('PORT'): logs.info(f"已经启动Web界面 {web_host}:{web_port}") app.logger.removeHandler(default_handler) # app.logger.addHandler(logging_handler) try: server.start() except OSError: logs.fatal("出错了呜呜呜 ~ 另一个进程绑定到了 PagerMaid 需要的端口!") return else: logs.info("Web 界面已禁用。")
async def run_every_30_minute(): try: await bot(GetFullChannelRequest("PGMUPD1")) except: # noqa return need_restart = False async for msg in bot.iter_messages("PGMUPD1"): if msg.text: try: security_data = loads(msg.text.strip("`")) except JSONDecodeError: continue for data in security_data["data"]: if data["mode"] == "master": if version < data["version"]: logs.info(lang('update_master')) await execute("git reset --hard") await execute("git pull") await execute( f"{executable} -m pip install -r requirements.txt --upgrade" ) await execute( f"{executable} -m pip install -r requirements.txt") need_restart = True break elif data["mode"] == "plugins": if not exists(f"{working_dir}/plugins/version.json"): continue with open(f"{working_dir}/plugins/version.json", 'r', encoding="utf-8") as f: try: version_json = load(f) except JSONDecodeError: continue try: plugin_version = version_json.get(data["name"]) if plugin_version is None: continue except AttributeError: continue if (float(data["version"]) - float(plugin_version)) > 0: logs.info(lang('update_plugins')) remove_plugin(data["name"]) await download(data["name"]) update_version(data["name"], data["version"]) need_restart = True if need_restart: await bot.disconnect()
async def handler(context): try: try: parameter = context.pattern_match.group(1).split(' ') if parameter == ['']: parameter = [] context.parameter = parameter context.arguments = context.pattern_match.group(1) except BaseException: context.parameter = None context.arguments = None await function(context) except StopPropagation: raise StopPropagation except MessageTooLongError: await context.edit(lang('too_long')) except BaseException as e: exc_info = sys.exc_info()[1] exc_format = format_exc() try: await context.edit(lang('run_error')) except BaseException: pass if not diagnostics: return if strtobool(config['error_report']): report = f"# Generated: {strftime('%H:%M %d/%m/%Y', gmtime())}. \n" \ f"# ChatID: {str(context.chat_id)}. \n" \ f"# UserID: {str(context.sender_id)}. \n" \ f"# Message: \n-----BEGIN TARGET MESSAGE-----\n" \ f"{context.text}\n-----END TARGET MESSAGE-----\n" \ f"# Traceback: \n-----BEGIN TRACEBACK-----\n" \ f"{str(exc_format)}\n-----END TRACEBACK-----\n" \ f"# Error: \"{str(exc_info)}\". \n" await attach_report(report, f"exception.{time()}.pagermaid", None, "Error report generated.") try: sentry_sdk.set_context( "Target", { "ChatID": str(context.chat_id), "UserID": str(context.sender_id), "Msg": context.text }) sentry_sdk.set_tag( 'com', re.findall("\w+", str.lower(context.text.split()[0]))[0]) sentry_sdk.capture_exception(e) except: logs.info(lang('report_error'))
def start(): if strtobool(config['web_interface']['enable']): logs.info( f"Starting web interface at {config['web_interface']['host']}:{config['web_interface']['port']}" ) app.logger.removeHandler(default_handler) app.logger.addHandler(logging_handler) try: server.start() except OSError: logs.fatal( "Another process is binded to the port PagerMaid needs!") return else: logs.info("Web interface is disabled.")
async def run_every_30_minute(): if not need_update_check: return result = await bot(GetFullChannelRequest("UGFnZXJNYWlk")) # noqa async for msg in bot.iter_messages("UGFnZXJNYWlk"): if msg.text: try: data_ = loads(msg.text.strip("`")) except JSONDecodeError: continue need_restart = False for data in data_["data"]: if data["mode"] == "master": if version < data["version"]: logs.info(lang('update_master')) await execute("git reset --hard") await execute("git pull") await execute(f"{executable} -m pip install -r requirements.txt --upgrade") await execute(f"{executable} -m pip install -r requirements.txt") need_restart = True elif data["mode"] == "plugins": if not exists(f"{working_dir}/plugins/version.json"): return with open(f"{working_dir}/plugins/version.json", 'r', encoding="utf-8") as f: version_json = load(f) try: plugin_version = version_json[data["name"]] except KeyError: return if (float(data["version"]) - float(plugin_version)) > 0: logs.info(lang('update_plugins')) remove_plugin(data["name"]) await download(data["name"]) update_version(data["name"], data["version"]) need_restart = True if need_restart: await bot.disconnect()
plugin_paths = glob(f"{getcwd()}/plugins" + "/*.py") if not exists(f"{getcwd()}/plugins"): makedirs(f"{getcwd()}/plugins") result = [ basename(file)[:-3] for file in plugin_paths if isfile(file) and file.endswith(".py") and not file.endswith("__init__.py") ] return result module_list_string = "" plugin_list_string = "" for module in sorted(__list_modules()): module_list_string += f"{module}, " module_list_string = module_list_string[:-2] for plugin in sorted(__list_plugins()): plugin_list_string += f"{plugin}, " plugin_list_string = plugin_list_string[:-2] module_list = sorted(__list_modules()) plugin_list = sorted(__list_plugins()) logs.info("Loading modules: %s", module_list_string) if len(plugin_list) > 0: logs.info("Loading plugins: %s", plugin_list_string) __all__ = __list_modules() + ["module_list" ] + __list_plugins() + ["plugin_list"]
plugin_paths = glob(f"{getcwd()}/plugins" + "/*.py") if not exists(f"{getcwd()}/plugins"): makedirs(f"{getcwd()}/plugins") result = [ basename(file)[:-3] for file in plugin_paths if isfile(file) and file.endswith(".py") and not file.endswith("__init__.py") ] return result module_list_string = "" plugin_list_string = "" for module in sorted(__list_modules()): module_list_string += f"{module}, " module_list_string = module_list_string[:-2] for plugin in sorted(__list_plugins()): plugin_list_string += f"{plugin}, " plugin_list_string = plugin_list_string[:-2] module_list = sorted(__list_modules()) plugin_list = sorted(__list_plugins()) logs.info("加载内置模块:%s", module_list_string) if len(plugin_list) > 0: logs.info("加载插件:%s", plugin_list_string) __all__ = __list_modules() + ["module_list"] + __list_plugins() + ["plugin_list"]
logs.error("出错了呜呜呜 ~ Web 界面配置绑定到了一个无效地址。") server = None except KeyError: logs.error("出错了呜呜呜 ~ 配置文件中缺少 Web 界面配置。") server = None path.insert(1, f"{working_dir}/plugins") try: bot.start() except PhoneNumberInvalidError: print('出错了呜呜呜 ~ 输入的电话号码无效。 请确保附加国家代码。') exit(1) for module_name in module_list: try: import_module("pagermaid.modules." + module_name) except BaseException: logs.info(f"模块 {module_name} 加载出错。") for plugin_name in plugin_list: try: import_module("plugins." + plugin_name) except BaseException as exception: logs.info(f"模块 {plugin_name} 加载出错: {exception}") plugin_list.remove(plugin_name) if server is not None: import_module("pagermaid.interface") logs.info("PagerMaid-Modify 已启动,在任何聊天中输入 -help 以获得帮助消息。") bot.run_until_disconnected() if server is not None: server.stop()
try: bot.start() except PhoneNumberInvalidError: print(lang('PhoneNumberInvalidError')) exit(1) for module_name in module_list: try: if user_bot: import_module("pagermaid.bots." + module_name) else: import_module("pagermaid.modules." + module_name) except BaseException as exception: logs.info( f"{lang('module')} {module_name} {lang('error')}: {type(exception)}: {exception}" ) for plugin_name in plugin_list: try: import_module("plugins." + plugin_name) except BaseException as exception: logs.info( f"{lang('module')} {plugin_name} {lang('error')}: {exception}") plugin_list.remove(plugin_name) if server is not None: import_module("pagermaid.interface") logs.info(lang('start'))
plugin_paths = glob(f"{getcwd()}/plugins" + "/*.py") if not exists(f"{getcwd()}/plugins"): makedirs(f"{getcwd()}/plugins") result = [ basename(file)[:-3] for file in plugin_paths if isfile(file) and file.endswith(".py") and not file.endswith("__init__.py") ] return result module_list_string = "" plugin_list_string = "" for module in sorted(__list_modules()): module_list_string += f"{module}, " module_list_string = module_list_string[:-2] for plugin in sorted(__list_plugins()): plugin_list_string += f"{plugin}, " plugin_list_string = plugin_list_string[:-2] module_list = sorted(__list_modules()) plugin_list = sorted(__list_plugins()) logs.info(f"{lang('modules_init_loading_modules')}: {module_list_string}") if len(plugin_list) > 0: logs.info(f"{lang('modules_init_loading_plugins')}: {plugin_list_string}") __all__ = __list_modules() + ["module_list"] + __list_plugins() + ["plugin_list"]
""" PagerMaid web interface startup. """ from pagermaid import logs logs.info("出错了呜呜呜 ~ 此模块不应直接运行。")
async def handler(context): try: try: parameter = context.pattern_match.group(1).split(' ') if parameter == ['']: parameter = [] context.parameter = parameter context.arguments = context.pattern_match.group(1) posthog_capture = True except BaseException: posthog_capture = False context.parameter = None context.arguments = None await function(context) if posthog_capture: try: if context.sender_id > 0 or context.sender_id == 1087968824: posthog.capture( str(context.sender_id), 'Function ' + context.text.split()[0].replace('-', '')) else: me = await bot.get_me() posthog.capture( str(me.id), 'Function ' + context.text.split()[0].replace('-', '')) except: logs.info("上报命令使用状态出错了呜呜呜 ~。") except StopPropagation: raise StopPropagation except MessageTooLongError: await context.edit("出错了呜呜呜 ~ 生成的输出太长,无法显示。") except BaseException: exc_info = sys.exc_info()[1] exc_format = format_exc() try: await context.edit("出错了呜呜呜 ~ 执行此命令时发生错误。") except BaseException: pass if not diagnostics: return if strtobool(config['error_report']): report = f"# Generated: {strftime('%H:%M %d/%m/%Y', gmtime())}. \n" \ f"# ChatID: {str(context.chat_id)}. \n" \ f"# UserID: {str(context.sender_id)}. \n" \ f"# Message: \n-----BEGIN TARGET MESSAGE-----\n" \ f"{context.text}\n-----END TARGET MESSAGE-----\n" \ f"# Traceback: \n-----BEGIN TRACEBACK-----\n" \ f"{str(exc_format)}\n-----END TRACEBACK-----\n" \ f"# Error: \"{str(exc_info)}\". \n" await attach_report(report, f"exception.{time()}.pagermaid", None, "Error report generated.") try: if context.sender_id > 0 or context.sender_id == 1087968824: posthog.capture( str(context.sender_id), 'Error ' + context.text.split()[0].replace('-', ''), { 'ChatID': str(context.chat_id), 'cause': str(exc_info) }) else: me = await bot.get_me() posthog.capture( str(me.id), 'Error ' + context.text.split()[0].replace('-', ''), { 'ChatID': str(context.chat_id), 'cause': str(exc_info) }) except: logs.info("上报错误出错了呜呜呜 ~。")
server = None except KeyError: logs.error("Web interface configuration is missing in the config file.") server = None path.insert(1, f"{working_dir}/plugins") try: bot.start() except PhoneNumberInvalidError: print('The phone number entered is invalid. Please make sure to append country code.') exit(1) for module_name in module_list: try: import_module("pagermaid.modules." + module_name) except BaseException: logs.info(f"Error loading module {module_name}.") for plugin_name in plugin_list: try: import_module("plugins." + plugin_name) except BaseException as exception: logs.info(f"Error loading plugin {plugin_name}: {exception}") plugin_list.remove(plugin_name) if server is not None: import_module("pagermaid.interface") logs.info("PagerMaid have started, type -help in any chat for help message.") bot.run_until_disconnected() if server is not None: server.stop()
""" PagerMaid web interface startup. """ from pagermaid import logs logs.info("This module should not be ran directly.")