🐛 Fix a lot of bugs. (#91)

* 🐛 修复了许多错误。
This commit is contained in:
Xtao_dada 2021-06-19 15:25:31 +08:00 committed by GitHub
parent 7fad1aae10
commit 67e003b881
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 139 additions and 61 deletions

View File

@ -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,

View File

@ -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]

View File

@ -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(

View File

@ -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:

View File

@ -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)

View File

@ -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:

View File

@ -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()))

View File

@ -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: