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
from inspect import Parameter
from loguru import logger
from core import command
from loguru import logger
from pyrogram import Client
from pyrogram.errors import FloodWait, RPCError
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'))
@ -15,9 +15,8 @@ async def sb(cli: Client, msg: Message):
"""回复一条消息,将在所有共同且拥有管理踢人权限的群组中踢出目标消息的主人"""
cmd, *_ = Parameter.get(msg)
reply_to_message = msg.reply_to_message
if not reply_to_message or msg.chat.type in ['bot', 'private']:
await msg.edit_text(get_cmd_error(cmd))
return
if not reply_to_message or msg.chat.type in [TG_BOT, TG_PRIVATE]:
return await show_cmd_tip(msg, cmd)
counter, target = 0, reply_to_message.from_user
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.types import Message
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
@ -19,8 +19,7 @@ async def note(_: Client, msg: Message):
"""
cmd, opts = Parameters.get_more(msg)
if not (1 <= len(opts) <= 2):
await msg.edit_text(get_cmd_error(cmd))
return
return await show_cmd_tip(msg, cmd)
replied_msg = msg.reply_to_message
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
text = "😊 Notes saved successfully."
else:
text = get_cmd_error(cmd)
return await show_cmd_tip(msg, cmd)
elif len(opts) == 2 and opts[0] == 'del':
if notes_data.pop(opts[1], None):
text = "😊 Notes deleted successfully."
@ -49,7 +48,7 @@ async def note(_: Client, msg: Message):
res = notes_data.get(option)
text = res if res else f"😱 No saved notes found for {option}"
else:
text = get_cmd_error(cmd)
return await show_cmd_tip(msg, cmd)
try:
await msg.edit_text(text)

View File

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

View File

@ -7,7 +7,7 @@ from pyrogram import Client
from pyrogram.types import Message
from tools.constants import (SYCGRAM, SYCGRAM_ERROR, SYCGRAM_INFO,
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,
reset_cmd_alias, update_cmd_alias,
update_cmd_prefix)
@ -96,7 +96,9 @@ async def alias(_: Client, msg: Message):
elif len(args) == 1 and args[0] == 'list':
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:
text = f"**{SYCGRAM_ERROR}**\n> # `{e}`"
logger.error(e)
@ -105,4 +107,4 @@ async def alias(_: Client, msg: Message):
await msg.edit_text(text, parse_mode='md')
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 tools.constants import INSTALL_SPEEDTEST, SPEEDTEST_PATH_FILE
from tools.constants import INSTALL_SPEEDTEST, SPEEDTEST_PATH_FILE, SYCGRAM_ERROR
from .helpers import basher
@ -31,12 +31,11 @@ class Speedtester:
Args:
cmd (str, optional): speedtest的完整指令需要返回json格式.
Defaults to 'speedtest-cli --share --json'.
Returns:
Tuple[str]: 第一个值是文本/错误第二个是图片link
"""
await self.init_for_speedtest()
await self.install_speedtest_cli()
# 超时报错
res = await basher(cmd, timeout=60)
logger.info(f"Speedtest Execution | {res}")
@ -45,8 +44,9 @@ class Speedtester:
# output result
self.__output: Dict[str, Any] = json.loads(res.get('output'))
self.__server: Dict[str, Any] = self.__output.get('server')
except Exception:
return f"⚠️ Error\n```{res.get('error')}```", ''
except Exception as e:
logger.error(e)
return f"⚠️ Speedtest Error\n```{res.get('error')}```", ''
else:
text = "**Speedtest**\n" \
f"Server: {self.get_server()}\n" \
@ -59,21 +59,21 @@ class Speedtester:
return text, f"{self.__output.get('result').get('url')}.png"
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)
logger.info(f"Speedtest Execution | {res}")
if not res.get('error'):
try:
self.__output: Dict[str, Any] = json.loads(res.get('output'))
except (TypeError, AttributeError, json.decoder.JSONDecodeError):
return "⚠️ Unable to get ids of servers"
except Exception:
return "**{SYCGRAM_ERROR}**\n> # `⚠️ Unable to get ids of servers`"
else:
tmp = '\n'.join(
f"`{k.get('id')}` **|** {k.get('name')} **|** {k.get('location')} {k.get('country')}"
for k in self.__output.get('servers')
)
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:
location = self.__server.get('location')
@ -114,14 +114,14 @@ class Speedtester:
def get_time(self) -> str:
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:
return path.exists(SPEEDTEST_PATH_FILE)
if platform.uname().system != "Linux" or platform.uname().machine not in [
'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)
return text
elif opt == 'install':
@ -134,10 +134,10 @@ class Speedtester:
os.remove(SPEEDTEST_PATH_FILE)
await self.__download_file()
if exists_file():
text = "Update speedtest successfully."
text = "Update speedtest successfully."
logger.success(text)
return text
return "Failed to update speedtest"
return "Failed to update speedtest"
else:
raise ValueError(f'Wrong speedtest option {opt}')