From 67e003b8815a046cae0ef2301f86dc04620bd52d Mon Sep 17 00:00:00 2001 From: Xtao_dada Date: Sat, 19 Jun 2021 15:25:31 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Fix=20a=20lot=20of=20bugs.=20(#9?= =?UTF-8?q?1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 🐛 修复了许多错误。 --- pagermaid/__init__.py | 46 +++++++++++++++++++++++---- pagermaid/modules/account.py | 32 ++++++++++++------- pagermaid/modules/captions.py | 17 +++++++--- pagermaid/modules/external.py | 24 ++++++++++---- pagermaid/modules/message.py | 60 ++++++++++++++++++++--------------- pagermaid/modules/status.py | 8 +++-- pagermaid/modules/sticker.py | 4 +-- pagermaid/modules/update.py | 9 ++++-- 8 files changed, 139 insertions(+), 61 deletions(-) diff --git a/pagermaid/__init__.py b/pagermaid/__init__.py index 2a334be..9a669c7 100644 --- a/pagermaid/__init__.py +++ b/pagermaid/__init__.py @@ -17,8 +17,14 @@ from logging import getLogger, INFO, DEBUG, ERROR, StreamHandler, basicConfig from distutils2.util import strtobool from coloredlogs import ColoredFormatter from telethon import TelegramClient -from telethon.errors.rpcerrorlist import MessageNotModifiedError, MessageIdInvalidError +from telethon.errors.rpcerrorlist import MessageNotModifiedError, MessageIdInvalidError, ChannelPrivateError, \ + ChatSendMediaForbiddenError, YouBlockedUserError, FloodWaitError, ChatWriteForbiddenError +from telethon.errors.common import AlreadyInConversationError +from requests.exceptions import ChunkedEncodingError from sqlite3 import OperationalError +from http.client import RemoteDisconnected +from urllib.error import URLError +from concurrent.futures._base import TimeoutError persistent_vars = {} module_dir = __path__[0] @@ -164,15 +170,41 @@ with bot: def before_send(event, hint): global report_time exc_info = hint.get("exc_info") - if exc_info and isinstance(exc_info[0], ConnectionError): + if exc_info and isinstance(exc_info[1], ConnectionError): return None - elif exc_info and isinstance(exc_info[0], CancelledError): + elif exc_info and isinstance(exc_info[1], CancelledError): return None - elif exc_info and isinstance(exc_info[0], MessageNotModifiedError): + elif exc_info and isinstance(exc_info[1], MessageNotModifiedError): return None - elif exc_info and isinstance(exc_info[0], MessageIdInvalidError): + elif exc_info and isinstance(exc_info[1], MessageIdInvalidError): return None - elif exc_info and isinstance(exc_info[0], OperationalError): + elif exc_info and isinstance(exc_info[1], OperationalError): + return None + elif exc_info and isinstance(exc_info[1], ChannelPrivateError): + return None + elif exc_info and isinstance(exc_info[1], BufferError): + return None + elif exc_info and isinstance(exc_info[1], RemoteDisconnected): + return None + elif exc_info and isinstance(exc_info[1], ChatSendMediaForbiddenError): + return None + elif exc_info and isinstance(exc_info[1], TypeError): + return None + elif exc_info and isinstance(exc_info[1], URLError): + return None + elif exc_info and isinstance(exc_info[1], YouBlockedUserError): + return None + elif exc_info and isinstance(exc_info[1], FloodWaitError): + return None + elif exc_info and isinstance(exc_info[1], ChunkedEncodingError): + return None + elif exc_info and isinstance(exc_info[1], TimeoutError): + return None + elif exc_info and isinstance(exc_info[1], UnicodeEncodeError): + return None + elif exc_info and isinstance(exc_info[1], ChatWriteForbiddenError): + return None + elif exc_info and isinstance(exc_info[1], AlreadyInConversationError): return None if time() <= report_time + 30: report_time = time() @@ -185,7 +217,7 @@ def before_send(event, hint): report_time = time() git_hash = run("git rev-parse HEAD", stdout=PIPE, shell=True).stdout.decode() sentry_sdk.init( - "https://26b73b1d975042e597bf0c9eab3913e8@o416616.ingest.sentry.io/5312335", + "https://77fbfe3e22a24652894aaec0e6074c7b@o416616.ingest.sentry.io/5312335", traces_sample_rate=1.0, release=git_hash, before_send=before_send, diff --git a/pagermaid/modules/account.py b/pagermaid/modules/account.py index 3609db3..1c12d96 100644 --- a/pagermaid/modules/account.py +++ b/pagermaid/modules/account.py @@ -3,7 +3,7 @@ from os import remove from telethon.errors import ImageProcessFailedError, PhotoCropSizeSmallError from telethon.errors.rpcerrorlist import PhotoExtInvalidError, UsernameOccupiedError, AboutTooLongError, \ - FirstNameInvalidError, UsernameInvalidError + FirstNameInvalidError, UsernameInvalidError, UsernameNotModifiedError from telethon.tl.functions.account import UpdateProfileRequest, UpdateUsernameRequest from telethon.tl.functions.photos import DeletePhotosRequest, GetUserPhotosRequest, UploadProfilePhotoRequest from telethon.tl.functions.users import GetFullUserRequest @@ -29,11 +29,14 @@ async def username(context): try: await bot(UpdateUsernameRequest(result)) except UsernameOccupiedError: - await context.edit(f"{lang('error_prefix')}") + await context.edit(f"{lang('error_prefix')}{lang('username_exist')}") return except UsernameInvalidError: await context.edit(f"{lang('error_prefix')}{lang('username_vaild')}") return + except UsernameNotModifiedError: + await context.edit(f"{lang('error_prefix')}{lang('username_exist')}") + return await context.edit(lang('username_set')) if result == "": await log(lang('username_cancel')) @@ -76,27 +79,34 @@ async def pfp(context): reply = await context.get_reply_message() photo = None await context.edit(lang('pfp_process')) - if reply.media: - if isinstance(reply.media, MessageMediaPhoto): - photo = await bot.download_media(message=reply.photo) - elif "image" in reply.media.document.mime_type.split('/'): - photo = await bot.download_file(reply.media.document) - else: - await context.edit(f"{lang('error_prefix')}{lang('pfp_e_notp')}") + if reply: + if reply.media: + if isinstance(reply.media, MessageMediaPhoto): + photo = await bot.download_media(message=reply.photo) + elif "image" in reply.media.document.mime_type.split('/'): + photo = await bot.download_file(reply.media.document) + else: + await context.edit(f"{lang('error_prefix')}{lang('pfp_e_notp')}") if photo: try: await bot(UploadProfilePhotoRequest( await bot.upload_file(photo) )) - remove(photo) + try: + remove(photo) + except: + pass await context.edit("头像修改成功啦 ~") + return except PhotoCropSizeSmallError: await context.edit(f"{lang('error_prefix')}{lang('pfp_e_size')}") except ImageProcessFailedError: await context.edit(f"{lang('error_prefix')}{lang('pfp_e_img')}") except PhotoExtInvalidError: await context.edit(f"{lang('error_prefix')}{lang('pfp_e_notp')}") + await context.edit(f"{lang('error_prefix')}{lang('pfp_e_notp')}") + return @listener(is_plugin=False, outgoing=True, command=alias_command('bio'), @@ -273,7 +283,7 @@ async def block_user(context): await context.edit(lang('block_process')) if context.reply_to_msg_id: reply_message = await context.get_reply_message() - user = reply_message.from_id.user_id + user = reply_message.sender_id else: if len(context.parameter) == 1: user = context.parameter[0] diff --git a/pagermaid/modules/captions.py b/pagermaid/modules/captions.py index 6b23c03..3c09f7e 100644 --- a/pagermaid/modules/captions.py +++ b/pagermaid/modules/captions.py @@ -24,9 +24,14 @@ async def convert(context): ) if target_file_path is None: await context.edit(lang('convert_no_file')) - result = await execute(f"{module_dir}/assets/caption.sh \"" + target_file_path + - "\" result.png" + " \"" + str("") + - "\" " + "\"" + str("") + "\"") + return + try: + result = await execute(f"{module_dir}/assets/caption.sh \"" + target_file_path + + "\" result.png" + " \"" + str("") + + "\" " + "\"" + str("") + "\"") + except TypeError: + await context.edit(lang('convert_error')) + return if not result: await handle_failure(context, target_file_path) return @@ -158,7 +163,11 @@ async def highlight(context): await context.edit(lang('highlight_no_file')) return lexer = guess_lexer(message) - formatter = img.JpgImageFormatter(style="colorful") + try: + formatter = img.JpgImageFormatter(style="colorful") + except img.FontNotFound: + await context.edit(lang('caption_error')) + return result = syntax_highlight(message, lexer, formatter, outfile=None) await context.edit(lang('highlight_uploading')) await context.client.send_file( diff --git a/pagermaid/modules/external.py b/pagermaid/modules/external.py index d77be2e..8d95887 100644 --- a/pagermaid/modules/external.py +++ b/pagermaid/modules/external.py @@ -37,10 +37,13 @@ async def translate(context): except ValueError: await context.edit(lang('translate_ValueError')) return - - source_lang = result.src - source_text = result.origin - trans_lang = result.dest + try: + source_lang = result.src + source_text = result.origin + trans_lang = result.dest + except AttributeError: + await context.edit(lang('google_connection_error')) + return result = f"**{lang('translate_hits')}**\n{lang('translate_original_lang')}: {source_lang}\n{source_text} -> {result.text}" if len(result) > 4096: @@ -83,7 +86,11 @@ async def tts(context): await context.edit(lang('tts_RuntimeError')) return google_tts = gTTS(message, lang=ap_lang) - google_tts.save("vocals.mp3") + try: + google_tts.save("vocals.mp3") + except AssertionError: + await context.edit(lang('tts_AssertionError')) + return with open("vocals.mp3", "rb") as audio: line_list = list(audio) line_count = len(line_list) @@ -91,8 +98,11 @@ async def tts(context): google_tts = gTTS(message, lang=ap_lang) google_tts.save("vocals.mp3") with open("vocals.mp3", "r"): - await context.client.send_file(context.chat_id, "vocals.mp3", voice_note=True) - remove("vocals.mp3") + try: + await context.client.send_file(context.chat_id, "vocals.mp3", voice_note=True) + remove("vocals.mp3") + except: + pass if len(message) <= 4096: await log(f"{lang('tts_success')}: `{message}`.") else: diff --git a/pagermaid/modules/message.py b/pagermaid/modules/message.py index 3dd15fb..6c61cef 100644 --- a/pagermaid/modules/message.py +++ b/pagermaid/modules/message.py @@ -33,23 +33,30 @@ async def userid(context): text += "lang_code: `" + msg_from.lang_code + "`\n" if context.is_group or context.is_channel: text += "title: `" + msg_from.title + "`\n" - if msg_from.username: - text += "username: @" + msg_from.username + "\n" + try: + if msg_from.username: + text += "username: @" + msg_from.username + "\n" + except AttributeError: + await context.edit(lang('leave_not_group')) + return text += "date: `" + str(msg_from.date) + "`\n" if message: - text += "\n" + lang('id_hint') + "\nMessage ID: `" + str(message.id) + "`\n\n**User**\nid: `" + str(message.sender.id) + "`" - if message.sender.bot: - text += f"\nis_bot: {lang('id_is_bot_yes')}" + text += "\n" + lang('id_hint') + "\nMessage ID: `" + str(message.id) + "`\n\n**User**\nid: `" + str(message.sender_id) + "`" try: - text += "\nfirst_name: `" + message.sender.first_name + "`" - except TypeError: - text += f"\n**{lang('id_da')}**" - if message.sender.last_name: - text += "\nlast_name: `" + message.sender.last_name + "`" - if message.sender.username: - text += "\nusername: @" + message.sender.username - if message.sender.lang_code: - text += "\nlang_code: `" + message.sender.lang_code + "`" + if message.sender.bot: + text += f"\nis_bot: {lang('id_is_bot_yes')}" + try: + text += "\nfirst_name: `" + message.sender.first_name + "`" + except TypeError: + text += f"\n**{lang('id_da')}**" + if message.sender.last_name: + text += "\nlast_name: `" + message.sender.last_name + "`" + if message.sender.username: + text += "\nusername: @" + message.sender.username + if message.sender.lang_code: + text += "\nlang_code: `" + message.sender.lang_code + "`" + except AttributeError: + pass if message.forward: if str(message.forward.chat_id).startswith('-100'): text += "\n\n**Forward From Channel**\nid: `" + str( @@ -64,18 +71,21 @@ async def userid(context): if message.forward.sender: text += "\n\n**Forward From User**\nid: `" + str( message.forward.sender_id) + "`" - if message.forward.sender.bot: - text += f"\nis_bot: {lang('id_is_bot_yes')}" try: - text += "\nfirst_name: `" + message.forward.sender.first_name + "`" - except TypeError: - text += f"\n**{lang('id_da')}**" - if message.forward.sender.last_name: - text += "\nlast_name: `" + message.forward.sender.last_name + "`" - if message.forward.sender.username: - text += "\nusername: @" + message.forward.sender.username - if message.forward.sender.lang_code: - text += "\nlang_code: `" + message.forward.sender.lang_code + "`" + if message.forward.sender.bot: + text += f"\nis_bot: {lang('id_is_bot_yes')}" + try: + text += "\nfirst_name: `" + message.forward.sender.first_name + "`" + except TypeError: + text += f"\n**{lang('id_da')}**" + if message.forward.sender.last_name: + text += "\nlast_name: `" + message.forward.sender.last_name + "`" + if message.forward.sender.username: + text += "\nusername: @" + message.forward.sender.username + if message.forward.sender.lang_code: + text += "\nlang_code: `" + message.forward.sender.lang_code + "`" + except AttributeError: + pass text += "\ndate: `" + str(message.forward.date) + "`" await context.edit(text) diff --git a/pagermaid/modules/status.py b/pagermaid/modules/status.py index 5a49430..f3cc110 100644 --- a/pagermaid/modules/status.py +++ b/pagermaid/modules/status.py @@ -6,7 +6,7 @@ from requests import get from os import remove, popen from datetime import datetime from speedtest import distance, Speedtest, ShareResultsConnectFailure, ShareResultsSubmitFailure, NoMatchedServers, \ - SpeedtestBestServerFailure + SpeedtestBestServerFailure, SpeedtestHTTPError from telethon import functions from platform import python_version, uname from wordcloud import WordCloud @@ -102,7 +102,11 @@ async def status(context): description=lang('speedtest_des')) async def speedtest(context): """ Tests internet speed using speedtest. """ - test = Speedtest() + try: + test = Speedtest() + except SpeedtestHTTPError: + await context.edit(lang('speedtest_ConnectFailure')) + return server, server_json = [], False if len(context.parameter) == 1: try: diff --git a/pagermaid/modules/sticker.py b/pagermaid/modules/sticker.py index 7fcacb7..5cf3a53 100644 --- a/pagermaid/modules/sticker.py +++ b/pagermaid/modules/sticker.py @@ -274,9 +274,9 @@ async def single_sticker(animated, context, custom_emoji, emoji, message, pic_ro request.Request(f'http://t.me/addstickers/{pack_name}'), context=ssl.create_default_context(cafile=certifi.where())) except UnicodeEncodeError: - pack_name = 's' + hex(context.sender.id)[2:] + pack_name = 's' + hex(context.sender_id)[2:] if animated: - pack_name = 's' + hex(context.sender.id)[2:] + '_animated' + pack_name = 's' + hex(context.sender_id)[2:] + '_animated' response = request.urlopen( request.Request(f'http://t.me/addstickers/{pack_name}'), context=ssl.create_default_context(cafile=certifi.where())) diff --git a/pagermaid/modules/update.py b/pagermaid/modules/update.py index 5b665c2..d9165bb 100644 --- a/pagermaid/modules/update.py +++ b/pagermaid/modules/update.py @@ -64,9 +64,12 @@ async def update(context): repo.create_remote('upstream', repo_url) except BaseException: pass - - upstream_remote = repo.remote('upstream') - upstream_remote.fetch(active_branch) + try: + upstream_remote = repo.remote('upstream') + upstream_remote.fetch(active_branch) + except GitCommandError: + await context.edit(lang('update_failed')) + return try: changelog = await changelog_gen(repo, f'HEAD..upstream/{active_branch}') except: