Modify the error reporting method

This commit is contained in:
iwumingz 2022-04-09 13:47:04 +08:00
parent 34d5d5f70b
commit a975053a85
5 changed files with 29 additions and 29 deletions

View File

@ -1,13 +1,13 @@
import asyncio import asyncio
from inspect import Parameter from inspect import Parameter
from loguru import logger
from core import command from core import command
from loguru import logger
from pyrogram import Client from pyrogram import Client
from pyrogram.errors import FloodWait, RPCError from pyrogram.errors import FloodWait, RPCError
from pyrogram.types import Message from pyrogram.types import Message
from tools.helpers import delete_this, get_cmd_error, kick_one from tools.constants import TG_BOT, TG_PRIVATE
from tools.helpers import delete_this, kick_one, show_cmd_tip
@Client.on_message(command('sb')) @Client.on_message(command('sb'))
@ -15,9 +15,8 @@ async def sb(cli: Client, msg: Message):
"""回复一条消息,将在所有共同且拥有管理踢人权限的群组中踢出目标消息的主人""" """回复一条消息,将在所有共同且拥有管理踢人权限的群组中踢出目标消息的主人"""
cmd, *_ = Parameter.get(msg) cmd, *_ = Parameter.get(msg)
reply_to_message = msg.reply_to_message reply_to_message = msg.reply_to_message
if not reply_to_message or msg.chat.type in ['bot', 'private']: if not reply_to_message or msg.chat.type in [TG_BOT, TG_PRIVATE]:
await msg.edit_text(get_cmd_error(cmd)) return await show_cmd_tip(msg, cmd)
return
counter, target = 0, reply_to_message.from_user counter, target = 0, reply_to_message.from_user
common_groups = await target.get_common_chats() common_groups = await target.get_common_chats()

View File

@ -6,7 +6,7 @@ from pyrogram import Client
from pyrogram.errors import BadRequest, FloodWait from pyrogram.errors import BadRequest, FloodWait
from pyrogram.types import Message from pyrogram.types import Message
from tools.constants import STORE_NOTES_DATA from tools.constants import STORE_NOTES_DATA
from tools.helpers import Parameters, get_cmd_error from tools.helpers import Parameters, show_cmd_tip
from tools.storage import SimpleStore from tools.storage import SimpleStore
@ -19,8 +19,7 @@ async def note(_: Client, msg: Message):
""" """
cmd, opts = Parameters.get_more(msg) cmd, opts = Parameters.get_more(msg)
if not (1 <= len(opts) <= 2): if not (1 <= len(opts) <= 2):
await msg.edit_text(get_cmd_error(cmd)) return await show_cmd_tip(msg, cmd)
return
replied_msg = msg.reply_to_message replied_msg = msg.reply_to_message
async with SimpleStore() as store: async with SimpleStore() as store:
@ -30,7 +29,7 @@ async def note(_: Client, msg: Message):
notes_data[opts[1]] = replied_msg.text or replied_msg.caption notes_data[opts[1]] = replied_msg.text or replied_msg.caption
text = "😊 Notes saved successfully." text = "😊 Notes saved successfully."
else: else:
text = get_cmd_error(cmd) return await show_cmd_tip(msg, cmd)
elif len(opts) == 2 and opts[0] == 'del': elif len(opts) == 2 and opts[0] == 'del':
if notes_data.pop(opts[1], None): if notes_data.pop(opts[1], None):
text = "😊 Notes deleted successfully." text = "😊 Notes deleted successfully."
@ -49,7 +48,7 @@ async def note(_: Client, msg: Message):
res = notes_data.get(option) res = notes_data.get(option)
text = res if res else f"😱 No saved notes found for {option}" text = res if res else f"😱 No saved notes found for {option}"
else: else:
text = get_cmd_error(cmd) return await show_cmd_tip(msg, cmd)
try: try:
await msg.edit_text(text) await msg.edit_text(text)

View File

@ -19,7 +19,7 @@ async def speedtest(_: Client, msg: Message):
async with Speedtester() as tester: async with Speedtester() as tester:
if opt == 'update': if opt == 'update':
try: try:
update_res = await tester.init_for_speedtest('update') update_res = await tester.install_speedtest_cli('update')
except asyncio.exceptions.TimeoutError: except asyncio.exceptions.TimeoutError:
await show_exception(msg, "Update Timeout") await show_exception(msg, "Update Timeout")
except Exception as e: except Exception as e:
@ -50,7 +50,7 @@ async def speedtest(_: Client, msg: Message):
return await show_cmd_tip(msg, cmd) return await show_cmd_tip(msg, cmd)
if not link: if not link:
return await show_exception(msg, "Speedtest Connection Error") return await msg.edit_text(text)
# send speed report # send speed report
try: try:

View File

@ -7,7 +7,7 @@ from pyrogram import Client
from pyrogram.types import Message from pyrogram.types import Message
from tools.constants import (SYCGRAM, SYCGRAM_ERROR, SYCGRAM_INFO, from tools.constants import (SYCGRAM, SYCGRAM_ERROR, SYCGRAM_INFO,
SYCGRAM_WARNING, UPDATE_CMD) SYCGRAM_WARNING, UPDATE_CMD)
from tools.helpers import Parameters, basher, get_cmd_error from tools.helpers import Parameters, basher, show_cmd_tip
from tools.updates import (get_alias_of_cmds, pull_and_update_command_yml, from tools.updates import (get_alias_of_cmds, pull_and_update_command_yml,
reset_cmd_alias, update_cmd_alias, reset_cmd_alias, update_cmd_alias,
update_cmd_prefix) update_cmd_prefix)
@ -96,7 +96,9 @@ async def alias(_: Client, msg: Message):
elif len(args) == 1 and args[0] == 'list': elif len(args) == 1 and args[0] == 'list':
try: try:
text = get_alias_of_cmds() data = get_alias_of_cmds()
tmp = ''.join(f"`{k}` | `{v}`\n" for k, v in data.items())
text = f"**⭐️ 指令别名:**\n**源名** | **别名**\n{tmp}"
except Exception as e: except Exception as e:
text = f"**{SYCGRAM_ERROR}**\n> # `{e}`" text = f"**{SYCGRAM_ERROR}**\n> # `{e}`"
logger.error(e) logger.error(e)
@ -105,4 +107,4 @@ async def alias(_: Client, msg: Message):
await msg.edit_text(text, parse_mode='md') await msg.edit_text(text, parse_mode='md')
else: else:
await msg.edit_text(get_cmd_error(cmd)) await show_cmd_tip(msg, cmd)

View File

@ -8,7 +8,7 @@ from typing import Any, Dict, Optional, Tuple
from loguru import logger from loguru import logger
from tools.constants import INSTALL_SPEEDTEST, SPEEDTEST_PATH_FILE from tools.constants import INSTALL_SPEEDTEST, SPEEDTEST_PATH_FILE, SYCGRAM_ERROR
from .helpers import basher from .helpers import basher
@ -31,12 +31,11 @@ class Speedtester:
Args: Args:
cmd (str, optional): speedtest的完整指令需要返回json格式. cmd (str, optional): speedtest的完整指令需要返回json格式.
Defaults to 'speedtest-cli --share --json'.
Returns: Returns:
Tuple[str]: 第一个值是文本/错误第二个是图片link Tuple[str]: 第一个值是文本/错误第二个是图片link
""" """
await self.init_for_speedtest() await self.install_speedtest_cli()
# 超时报错 # 超时报错
res = await basher(cmd, timeout=60) res = await basher(cmd, timeout=60)
logger.info(f"Speedtest Execution | {res}") logger.info(f"Speedtest Execution | {res}")
@ -45,8 +44,9 @@ class Speedtester:
# output result # output result
self.__output: Dict[str, Any] = json.loads(res.get('output')) self.__output: Dict[str, Any] = json.loads(res.get('output'))
self.__server: Dict[str, Any] = self.__output.get('server') self.__server: Dict[str, Any] = self.__output.get('server')
except Exception: except Exception as e:
return f"⚠️ Error\n```{res.get('error')}```", '' logger.error(e)
return f"⚠️ Speedtest Error\n```{res.get('error')}```", ''
else: else:
text = "**Speedtest**\n" \ text = "**Speedtest**\n" \
f"Server: {self.get_server()}\n" \ f"Server: {self.get_server()}\n" \
@ -59,21 +59,21 @@ class Speedtester:
return text, f"{self.__output.get('result').get('url')}.png" return text, f"{self.__output.get('result').get('url')}.png"
async def list_servers_ids(self, cmd: str) -> str: async def list_servers_ids(self, cmd: str) -> str:
await self.init_for_speedtest() await self.install_speedtest_cli()
res = await basher(cmd, timeout=10) res = await basher(cmd, timeout=10)
logger.info(f"Speedtest Execution | {res}") logger.info(f"Speedtest Execution | {res}")
if not res.get('error'): if not res.get('error'):
try: try:
self.__output: Dict[str, Any] = json.loads(res.get('output')) self.__output: Dict[str, Any] = json.loads(res.get('output'))
except (TypeError, AttributeError, json.decoder.JSONDecodeError): except Exception:
return "⚠️ Unable to get ids of servers" return "**{SYCGRAM_ERROR}**\n> # `⚠️ Unable to get ids of servers`"
else: else:
tmp = '\n'.join( tmp = '\n'.join(
f"`{k.get('id')}` **|** {k.get('name')} **|** {k.get('location')} {k.get('country')}" f"`{k.get('id')}` **|** {k.get('name')} **|** {k.get('location')} {k.get('country')}"
for k in self.__output.get('servers') for k in self.__output.get('servers')
) )
return f"**Speedtest节点列表**\n{tmp}" return f"**Speedtest节点列表**\n{tmp}"
return f"⚠️ Error\n```{res.get('error')}```" return f"**{SYCGRAM_ERROR}**\n```{res.get('error')}```"
def get_server(self) -> str: def get_server(self) -> str:
location = self.__server.get('location') location = self.__server.get('location')
@ -114,14 +114,14 @@ class Speedtester:
def get_time(self) -> str: def get_time(self) -> str:
return f"`{datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')}`" return f"`{datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')}`"
async def init_for_speedtest(self, opt: str = 'install') -> Optional[str]: async def install_speedtest_cli(self, opt: str = 'install') -> Optional[str]:
def exists_file() -> bool: def exists_file() -> bool:
return path.exists(SPEEDTEST_PATH_FILE) return path.exists(SPEEDTEST_PATH_FILE)
if platform.uname().system != "Linux" or platform.uname().machine not in [ if platform.uname().system != "Linux" or platform.uname().machine not in [
'i386', 'x86_64', 'armel', 'armhf', 'aarch64', 'i386', 'x86_64', 'armel', 'armhf', 'aarch64',
]: ]:
text = f"Unsupported System >>> {platform.uname().system} - {platform.uname().machine}" text = f"Unsupported System >>> {platform.uname().system} {platform.uname().machine}"
logger.warning(text) logger.warning(text)
return text return text
elif opt == 'install': elif opt == 'install':
@ -134,10 +134,10 @@ class Speedtester:
os.remove(SPEEDTEST_PATH_FILE) os.remove(SPEEDTEST_PATH_FILE)
await self.__download_file() await self.__download_file()
if exists_file(): if exists_file():
text = "Update speedtest successfully." text = "Update speedtest successfully."
logger.success(text) logger.success(text)
return text return text
return "Failed to update speedtest" return "Failed to update speedtest"
else: else:
raise ValueError(f'Wrong speedtest option {opt}') raise ValueError(f'Wrong speedtest option {opt}')