🐛🚀 fix some bugs and support for deploy to railway (#128)

🐛 批量修复错误
🚀 支持云部署到 railway
This commit is contained in:
Xtao_dada 2021-09-03 19:03:34 +08:00 committed by GitHub
parent 0cc4a78388
commit 34c567c1f2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 157 additions and 41 deletions

View File

@ -8,7 +8,9 @@
<img alt="star" src="https://img.shields.io/github/stars/xtaodada/PagerMaid-Modify.svg"/>
<img alt="fork" src="https://img.shields.io/github/forks/xtaodada/PagerMaid-Modify.svg"/>
<img alt="GitHub last commit" src="https://img.shields.io/github/last-commit/xtaodada/PagerMaid-Modify.svg?label=commits">
<img alt="size" src="https://img.shields.io/github/repo-size/Xtao-Labs/PagerMaid-Modify?color=pink"/>
<img alt="issues" src="https://img.shields.io/github/issues/xtaodada/PagerMaid-Modify.svg"/>
<img alt="docker" src="https://img.shields.io/docker/pulls/mrwangzhe/pagermaid_modify"/>
<a href="https://github.com/xtaodada/PagerMaid-Modify/blob/master/LICENSE"><img alt="license" src="https://img.shields.io/github/license/xtaodada/PagerMaid-Modify.svg"/></a>
<img alt="telethon" src="https://img.shields.io/badge/telethon-blue.svg"/>
</p>
@ -29,6 +31,25 @@ Pagermaid 是一个用在 Telegram 的实用工具。
[Docker安装](utils/docker.md)
## 云部署
### 必须变量
- `API_ID` - 到 [my.telegram.org](https://my.telegram.org/) 申请获得的值
- `API_HASH` - 到 [my.telegram.org](https://my.telegram.org/) 申请获得的值
- `SESSION` - 账户授权字符,您需要[到这里](#Session)获取
[![Deploy on Railway](https://railway.app/button.svg)](https://railway.app/new/template?template=https%3A%2F%2Fgithub.com%2FXtao-Labs%2FPagerMaid-Modify%2Ftree%2Fmaster&envs=session%2Capi_key%2Capi_hash&sessionDesc=Your+telethon+session+string.&api_keyDesc=api_id%2C+from+my.telegram.org&api_hashDesc=api_hash%2C+from+my.telegram.org&referralCode=xtaolabs)
# Session
> 这是您账户的授权文件,请妥善保管
获得 `API_ID``API_HASH` 后,你可以通过下面两种方式获取 `SESSION`
* 在线获取:[![Repl.it](https://replit.com/badge/github/Xtao-Labs/PagerMaid-Modify)](https://replit.com/@mrwangzhe/gensession)
* 本地获取:`cd utils && python3 -m pip install telethon && python3 gensession.py`
# 对存在使用本项目用户群组的提醒
由于本项目需要响应账号通过其他客户端发出的命令,所以在本项目正常运行时,可能使用下列信息:

View File

@ -15,7 +15,7 @@ except:
pass
from subprocess import run, PIPE
from time import time
from os import getcwd, makedirs
from os import getcwd, makedirs, environ
from os.path import exists
from sys import version_info, platform
from yaml import load, FullLoader, safe_load
@ -26,11 +26,13 @@ from logging import getLogger, INFO, DEBUG, ERROR, StreamHandler, basicConfig
from distutils.util import strtobool
from coloredlogs import ColoredFormatter
from telethon import TelegramClient
from telethon.sessions import StringSession
# Errors
from telethon.errors.rpcerrorlist import MessageNotModifiedError, MessageIdInvalidError, ChannelPrivateError, \
ChatSendMediaForbiddenError, YouBlockedUserError, FloodWaitError, ChatWriteForbiddenError, \
AuthKeyDuplicatedError, ChatSendStickersForbiddenError
AuthKeyDuplicatedError, ChatSendStickersForbiddenError, SlowModeWaitError, MessageEditTimeExpiredError, \
PeerIdInvalidError
from telethon.errors.common import AlreadyInConversationError
from requests.exceptions import ChunkedEncodingError
from requests.exceptions import ConnectionError as ConnectedError
@ -141,6 +143,25 @@ if not exists(f"{getcwd()}/data"):
api_key = config['api_key']
api_hash = config['api_hash']
session_string = "pagermaid"
# environ
if environ.get('api_key'):
api_key = environ.get('api_key')
if environ.get('api_hash'):
api_hash = environ.get('api_hash')
if environ.get('session'):
string_session = environ.get('session')
session_string = StringSession(string_session)
# api type
try:
api_key = int(api_key)
except ValueError:
logs.info(
lang('config_error')
)
exit(1)
except:
pass
try:
proxy_addr = config['proxy_addr'].strip()
proxy_port = config['proxy_port'].strip()
@ -192,13 +213,13 @@ if not proxy_addr == '' and not proxy_port == '':
"http": f"socks5://{proxy_addr}:{proxy_port}",
"https": f"socks5://{proxy_addr}:{proxy_port}"
}
bot = TelegramClient("pagermaid", api_key, api_hash,
bot = TelegramClient(session_string, api_key, api_hash,
auto_reconnect=True,
proxy=(python_socks.ProxyType.SOCKS5, proxy_addr, int(proxy_port)),
use_ipv6=use_ipv6)
except:
proxies = {}
bot = TelegramClient("pagermaid", api_key, api_hash,
bot = TelegramClient(session_string, api_key, api_hash,
auto_reconnect=True,
use_ipv6=use_ipv6)
elif not http_addr == '' and not http_port == '':
@ -209,24 +230,24 @@ elif not http_addr == '' and not http_port == '':
"http": f"http://{http_addr}:{http_port}",
"https": f"http://{http_addr}:{http_port}"
}
bot = TelegramClient("pagermaid", api_key, api_hash,
bot = TelegramClient(session_string, api_key, api_hash,
auto_reconnect=True,
proxy=(python_socks.ProxyType.HTTP, http_addr, int(http_port)),
use_ipv6=use_ipv6)
except:
bot = TelegramClient("pagermaid", api_key, api_hash,
bot = TelegramClient(session_string, api_key, api_hash,
auto_reconnect=True,
use_ipv6=use_ipv6)
elif not mtp_addr == '' and not mtp_port == '' and not mtp_secret == '':
from telethon import connection
bot = TelegramClient("pagermaid", api_key, api_hash,
bot = TelegramClient(session_string, api_key, api_hash,
auto_reconnect=True,
connection=connection.ConnectionTcpMTProxyRandomizedIntermediate,
proxy=(mtp_addr, int(mtp_port), mtp_secret),
use_ipv6=use_ipv6)
else:
bot = TelegramClient("pagermaid", api_key, api_hash, auto_reconnect=True, use_ipv6=use_ipv6)
bot = TelegramClient(session_string, api_key, api_hash, auto_reconnect=True, use_ipv6=use_ipv6)
user_id = 0
redis = StrictRedis(host=redis_host, port=redis_port, db=redis_db)
@ -259,59 +280,65 @@ def before_send(event, hint):
global report_time
exc_info = hint.get("exc_info")
if exc_info and isinstance(exc_info[1], ConnectionError):
return None
return
elif exc_info and isinstance(exc_info[1], CancelledError):
return None
return
elif exc_info and isinstance(exc_info[1], MessageNotModifiedError):
return None
return
elif exc_info and isinstance(exc_info[1], MessageIdInvalidError):
return None
return
elif exc_info and isinstance(exc_info[1], OperationalError):
return None
return
elif exc_info and isinstance(exc_info[1], ChannelPrivateError):
return None
return
elif exc_info and isinstance(exc_info[1], BufferError):
return None
return
elif exc_info and isinstance(exc_info[1], RemoteDisconnected):
return None
return
elif exc_info and isinstance(exc_info[1], ChatSendMediaForbiddenError):
return None
return
elif exc_info and isinstance(exc_info[1], TypeError):
return None
return
elif exc_info and isinstance(exc_info[1], URLError):
return None
return
elif exc_info and isinstance(exc_info[1], YouBlockedUserError):
return None
return
elif exc_info and isinstance(exc_info[1], FloodWaitError):
return None
return
elif exc_info and isinstance(exc_info[1], ChunkedEncodingError):
return None
return
elif exc_info and isinstance(exc_info[1], TimeoutError):
return None
return
elif exc_info and isinstance(exc_info[1], UnicodeEncodeError):
return None
return
elif exc_info and isinstance(exc_info[1], ChatWriteForbiddenError):
return None
return
elif exc_info and isinstance(exc_info[1], ChatSendStickersForbiddenError):
return None
return
elif exc_info and isinstance(exc_info[1], AlreadyInConversationError):
return None
return
elif exc_info and isinstance(exc_info[1], ConnectedError):
return None
return
elif exc_info and isinstance(exc_info[1], KeyboardInterrupt):
return None
return
elif exc_info and isinstance(exc_info[1], OSError):
return None
return
elif exc_info and isinstance(exc_info[1], AuthKeyDuplicatedError):
return None
return
elif exc_info and isinstance(exc_info[1], ResponseError):
return None
return
elif exc_info and isinstance(exc_info[1], SlowModeWaitError):
return
elif exc_info and isinstance(exc_info[1], MessageEditTimeExpiredError):
return
elif exc_info and isinstance(exc_info[1], PeerIdInvalidError):
return
if not python36:
if exc_info and isinstance(exc_info[1], CancelError):
return None
return
if time() <= report_time + 30:
report_time = time()
return None
return
else:
report_time = time()
return event
@ -320,7 +347,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://a0e1ef3c67ca48f4b1ecfc5538528ef3@o416616.ingest.sentry.io/5312335",
"https://935d04099b7d4bd889e7ffac488579fc@o416616.ingest.sentry.io/5312335",
traces_sample_rate=1.0,
release=git_hash,
before_send=before_send,

View File

@ -1,5 +1,6 @@
""" PagerMaid web interface utility. """
from os import environ
from threading import Thread
from distutils.util import strtobool
from importlib import import_module
@ -36,12 +37,23 @@ import_module('pagermaid.interface.views')
import_module('pagermaid.interface.modals')
dispatcher = PathInfoDispatcher({'/': app})
server = WSGIServer((config['web_interface']['host'], int(config['web_interface']['port'])), dispatcher)
web_host = config['web_interface']['host']
try:
web_port = int(config['web_interface']['port'])
except ValueError:
web_port = 3333
if environ.get('PORT'):
web_host = '0.0.0.0'
try:
web_port = int(environ.get('PORT'))
except ValueError:
web_port = 3333
server = WSGIServer((web_host, web_port), dispatcher)
def start():
if strtobool(config['web_interface']['enable']):
logs.info(f"已经启动Web界面 {config['web_interface']['host']}:{config['web_interface']['port']}")
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:

View File

@ -4,6 +4,7 @@ from pygoogletranslation import Translator
from os import remove
from magic_google import MagicGoogle
from gtts import gTTS
from gtts.tts import gTTSError
from re import compile as regex_compile
from pagermaid import log
from pagermaid.listener import listener, config
@ -94,6 +95,9 @@ async def tts(context):
except ConnectionError:
await context.edit(lang('tts_RuntimeError'))
return
except gTTSError:
await context.edit(lang('tts_RuntimeError'))
return
with open("vocals.mp3", "rb") as audio:
line_list = list(audio)
line_count = len(line_list)

View File

@ -104,6 +104,8 @@ async def span_ban(context):
pass
except ChatAdminRequiredError:
pass
except ValueError:
pass
if redis_status():
sb_groups = redis.get('sb_groups')
if sb_groups:

View File

@ -5,7 +5,7 @@ from bs4 import BeautifulSoup
from asyncio import sleep
from os import remove
from io import BytesIO
from telethon.tl.types import DocumentAttributeFilename, MessageMediaPhoto, MessageMediaWebPage
from telethon.tl.types import DocumentAttributeFilename, MessageMediaPhoto, MessageMediaWebPage, MessageMediaDice
from telethon.tl.functions.contacts import UnblockRequest
from telethon.errors.common import AlreadyInConversationError
from PIL import Image, ImageOps
@ -203,6 +203,12 @@ async def single_sticker(animated, context, custom_emoji, emoji, message, pic_ro
except:
pass
return
elif isinstance(message.media, MessageMediaDice):
try:
await context.edit(lang('sticker_type_not_support'))
except:
pass
return
elif "image" in message.media.document.mime_type.split('/'):
photo = BytesIO()
try:

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

View File

@ -1,6 +1,6 @@
<div class="demo-drawer mdl-layout__drawer mdl-color--blue-grey-900 mdl-color-text--blue-grey-50">
<header class="demo-drawer-header">
<img src="static/images/icon.png" class="demo-avatar" alt="icon">
<img src="static/images/icon.jpg" class="demo-avatar" alt="icon">
<div class="demo-avatar-dropdown">
<span>PagerMaid</span>
<div class="mdl-layout-spacer"></div>
@ -28,7 +28,7 @@
</a>
<div class="mdl-layout-spacer"></div>
<a class="mdl-navigation__link" href="https://katonkeyboard.moe/pagermaid.html" target="_blank">
<a class="mdl-navigation__link" href="https://xtaolabs.com/" target="_blank">
<i class="mdl-color-text--blue-grey-400 material-icons" role="presentation">help_outline</i>
<span class="visuallyhidden">Help</span>
</a>

44
utils/gensession.py Normal file
View File

@ -0,0 +1,44 @@
import os
from sys import executable
try:
from telethon.errors.rpcerrorlist import ApiIdInvalidError, PhoneNumberInvalidError
from telethon.sessions import StringSession
from telethon.sync import TelegramClient
print("Found an existing installation of Telethon...\nSuccessfully Imported.")
except ImportError:
print("Installing Telethon...")
os.system(f"{executable} -m pip install telethon")
print("Done. Installed and imported Telethon.")
from telethon.errors.rpcerrorlist import ApiIdInvalidError, PhoneNumberInvalidError
from telethon.sessions import StringSession
from telethon.sync import TelegramClient
API_ID = 0
try:
API_ID = int(input("Please enter your API ID: "))
except ValueError:
print("APP ID must be an integer.\nQuitting...")
exit(0)
except Exception as e:
raise e
API_HASH = input("Please enter your API HASH: ")
try:
with TelegramClient(StringSession(), API_ID, API_HASH) as bot:
print("Generating a user session...")
bot.send_message(
"me",
f"**PagerMaid** `String SESSION`:\n\n`{bot.session.save()}`",
)
print("Your SESSION has been generated. Check your telegram saved messages!")
exit(0)
except ApiIdInvalidError:
print("Your API ID/API HASH combination is invalid. Kindly recheck.\nQuitting...")
exit(0)
except ValueError:
print("API HASH must not be empty!\nQuitting...")
exit(0)
except PhoneNumberInvalidError:
print("The phone number is invalid!\nQuitting...")
exit(0)