2020-02-19 15:31:39 +00:00
|
|
|
""" PagerMaid initialization. """
|
|
|
|
|
2021-04-03 15:24:07 +00:00
|
|
|
import sentry_sdk
|
|
|
|
|
|
|
|
from sentry_sdk.integrations.redis import RedisIntegration
|
2021-04-04 04:31:32 +00:00
|
|
|
from concurrent.futures import CancelledError
|
2021-04-03 15:24:07 +00:00
|
|
|
from subprocess import run, PIPE
|
|
|
|
from time import time
|
2020-02-19 15:31:39 +00:00
|
|
|
from os import getcwd, makedirs
|
|
|
|
from os.path import exists
|
|
|
|
from sys import version_info, platform
|
2021-04-12 16:25:32 +00:00
|
|
|
from yaml import load, FullLoader, safe_load
|
2020-02-19 15:31:39 +00:00
|
|
|
from shutil import copyfile
|
|
|
|
from redis import StrictRedis
|
2021-03-03 17:08:02 +00:00
|
|
|
from logging import getLogger, INFO, DEBUG, ERROR, StreamHandler, basicConfig
|
2020-02-19 15:31:39 +00:00
|
|
|
from distutils2.util import strtobool
|
|
|
|
from coloredlogs import ColoredFormatter
|
2020-08-08 16:31:48 +00:00
|
|
|
from telethon import TelegramClient
|
2020-02-19 15:31:39 +00:00
|
|
|
|
|
|
|
persistent_vars = {}
|
|
|
|
module_dir = __path__[0]
|
|
|
|
working_dir = getcwd()
|
|
|
|
config = None
|
|
|
|
help_messages = {}
|
2021-01-23 12:48:38 +00:00
|
|
|
logs = getLogger(__name__)
|
|
|
|
logging_format = "%(levelname)s [%(asctime)s] [%(name)s] %(message)s"
|
|
|
|
logging_handler = StreamHandler()
|
|
|
|
logging_handler.setFormatter(ColoredFormatter(logging_format))
|
2021-03-03 17:03:48 +00:00
|
|
|
root_logger = getLogger()
|
2021-03-03 17:08:02 +00:00
|
|
|
root_logger.setLevel(ERROR)
|
2021-03-03 17:03:48 +00:00
|
|
|
root_logger.addHandler(logging_handler)
|
2021-01-23 12:48:38 +00:00
|
|
|
basicConfig(level=INFO)
|
|
|
|
logs.setLevel(INFO)
|
2020-02-19 15:31:39 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
config = load(open(r"config.yml"), Loader=FullLoader)
|
|
|
|
except FileNotFoundError:
|
2021-04-12 16:25:32 +00:00
|
|
|
logs.fatal("The configuration file does not exist, and a new configuration file is being generated.")
|
2020-02-19 15:31:39 +00:00
|
|
|
copyfile(f"{module_dir}/assets/config.gen.yml", "config.yml")
|
|
|
|
exit(1)
|
|
|
|
|
2021-04-12 16:25:32 +00:00
|
|
|
# i18n
|
|
|
|
lang_dict: dict = {}
|
|
|
|
|
|
|
|
try:
|
|
|
|
with open(f"languages/built-in/{config['application_language']}.yml", "r", encoding="utf-8") as f:
|
|
|
|
lang_dict = safe_load(f)
|
|
|
|
except Exception as e:
|
|
|
|
print("Reading language YAML file failed")
|
|
|
|
print(e)
|
|
|
|
exit(1)
|
|
|
|
|
|
|
|
def lang(text: str) -> str:
|
|
|
|
""" i18n """
|
|
|
|
result = lang_dict.get(text, text)
|
|
|
|
return result
|
2020-02-19 15:31:39 +00:00
|
|
|
|
2021-01-23 12:48:38 +00:00
|
|
|
if strtobool(config['debug']):
|
|
|
|
logs.setLevel(DEBUG)
|
|
|
|
else:
|
|
|
|
logs.setLevel(INFO)
|
|
|
|
|
|
|
|
|
2020-02-19 15:31:39 +00:00
|
|
|
if platform == "linux" or platform == "linux2" or platform == "darwin" or platform == "freebsd7" \
|
|
|
|
or platform == "freebsd8" or platform == "freebsdN" or platform == "openbsd6":
|
|
|
|
logs.info(
|
2021-04-12 16:25:32 +00:00
|
|
|
lang('platform') + platform + lang('platform_load')
|
2020-02-19 15:31:39 +00:00
|
|
|
)
|
|
|
|
else:
|
|
|
|
logs.error(
|
2021-04-12 16:25:32 +00:00
|
|
|
f"{lang('error_prefix')} {lang('platform')}" + platform + lang('platform_unsupported')
|
2020-02-19 15:31:39 +00:00
|
|
|
)
|
|
|
|
exit(1)
|
|
|
|
|
|
|
|
if version_info[0] < 3 or version_info[1] < 6:
|
|
|
|
logs.error(
|
2021-04-12 16:25:32 +00:00
|
|
|
f"{lang('error_prefix')} {lang('python')}"
|
2020-02-19 15:31:39 +00:00
|
|
|
)
|
|
|
|
exit(1)
|
|
|
|
|
|
|
|
if not exists(f"{getcwd()}/data"):
|
|
|
|
makedirs(f"{getcwd()}/data")
|
|
|
|
|
|
|
|
api_key = config['api_key']
|
|
|
|
api_hash = config['api_hash']
|
2020-08-08 13:28:59 +00:00
|
|
|
try:
|
|
|
|
proxy_addr = config['proxy_addr'].strip()
|
|
|
|
proxy_port = config['proxy_port'].strip()
|
|
|
|
mtp_addr = config['mtp_addr'].strip()
|
|
|
|
mtp_port = config['mtp_port'].strip()
|
|
|
|
mtp_secret = config['mtp_secret'].strip()
|
|
|
|
except:
|
|
|
|
proxy_addr = ''
|
|
|
|
proxy_port = ''
|
|
|
|
mtp_addr = ''
|
|
|
|
mtp_port = ''
|
|
|
|
mtp_secret = ''
|
2020-02-19 15:31:39 +00:00
|
|
|
try:
|
|
|
|
redis_host = config['redis']['host']
|
|
|
|
except KeyError:
|
|
|
|
redis_host = 'localhost'
|
|
|
|
try:
|
|
|
|
redis_port = config['redis']['port']
|
|
|
|
except KeyError:
|
|
|
|
redis_port = 6379
|
|
|
|
try:
|
|
|
|
redis_db = config['redis']['db']
|
|
|
|
except KeyError:
|
|
|
|
redis_db = 14
|
|
|
|
if api_key is None or api_hash is None:
|
|
|
|
logs.info(
|
2021-04-12 16:25:32 +00:00
|
|
|
lang('config_error')
|
2020-02-19 15:31:39 +00:00
|
|
|
)
|
|
|
|
exit(1)
|
|
|
|
|
2020-08-08 13:17:46 +00:00
|
|
|
if not proxy_addr == '' and not proxy_port == '':
|
2020-08-08 16:31:48 +00:00
|
|
|
try:
|
|
|
|
import socks
|
|
|
|
except:
|
|
|
|
pass
|
2020-08-08 13:17:46 +00:00
|
|
|
bot = TelegramClient("pagermaid", api_key, api_hash, auto_reconnect=True, proxy=(socks.SOCKS5, proxy_addr, int(proxy_port)))
|
|
|
|
elif not mtp_addr == '' and not mtp_port == '' and not mtp_secret == '':
|
2020-08-08 16:31:48 +00:00
|
|
|
from telethon import connection
|
2020-08-08 13:17:46 +00:00
|
|
|
bot = TelegramClient("pagermaid", api_key, api_hash, auto_reconnect=True,
|
|
|
|
connection=connection.ConnectionTcpMTProxyRandomizedIntermediate,
|
|
|
|
proxy=(mtp_addr, int(mtp_port), mtp_secret))
|
|
|
|
else:
|
|
|
|
bot = TelegramClient("pagermaid", api_key, api_hash, auto_reconnect=True)
|
2020-02-19 15:31:39 +00:00
|
|
|
redis = StrictRedis(host=redis_host, port=redis_port, db=redis_db)
|
|
|
|
|
2021-04-03 15:24:07 +00:00
|
|
|
|
|
|
|
async def save_id():
|
|
|
|
me = await bot.get_me()
|
2021-04-04 05:03:57 +00:00
|
|
|
if me.username is not None:
|
|
|
|
sentry_sdk.set_user({"id": me.id, "name": me.first_name, "username": me.username, "ip_address": "{{auto}}"})
|
|
|
|
else:
|
|
|
|
sentry_sdk.set_user({"id": me.id, "name": me.first_name, "ip_address": "{{auto}}"})
|
2021-04-12 16:25:32 +00:00
|
|
|
logs.info(lang('save_id'))
|
2021-04-03 15:24:07 +00:00
|
|
|
|
|
|
|
|
|
|
|
with bot:
|
|
|
|
bot.loop.run_until_complete(save_id())
|
|
|
|
|
|
|
|
|
|
|
|
def before_send(event, hint):
|
|
|
|
global report_time
|
2021-04-04 03:04:11 +00:00
|
|
|
exc_info = hint.get("exc_info")
|
2021-04-04 04:31:32 +00:00
|
|
|
if exc_info and isinstance(exc_info[0], ConnectionError):
|
|
|
|
return None
|
|
|
|
elif exc_info and isinstance(exc_info[0], CancelledError):
|
2021-04-04 03:04:11 +00:00
|
|
|
return None
|
2021-04-03 15:24:07 +00:00
|
|
|
if time() <= report_time + 30:
|
|
|
|
report_time = time()
|
|
|
|
return None
|
|
|
|
else:
|
|
|
|
report_time = time()
|
|
|
|
return event
|
|
|
|
|
|
|
|
|
|
|
|
report_time = time()
|
2021-04-04 03:04:11 +00:00
|
|
|
git_hash = run("git rev-parse HEAD", stdout=PIPE, shell=True).stdout.decode()
|
2021-04-03 15:24:07 +00:00
|
|
|
sentry_sdk.init(
|
|
|
|
"https://969892b513374f75916aaac1014aa7c2@o416616.ingest.sentry.io/5312335",
|
|
|
|
traces_sample_rate=1.0,
|
|
|
|
release=git_hash,
|
|
|
|
before_send=before_send,
|
|
|
|
environment="production",
|
|
|
|
integrations=[RedisIntegration()]
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2020-02-19 15:31:39 +00:00
|
|
|
def redis_status():
|
|
|
|
try:
|
|
|
|
redis.ping()
|
|
|
|
return True
|
|
|
|
except BaseException:
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
async def log(message):
|
|
|
|
logs.info(
|
|
|
|
message.replace('`', '\"')
|
|
|
|
)
|
|
|
|
if not strtobool(config['log']):
|
|
|
|
return
|
|
|
|
await bot.send_message(
|
|
|
|
int(config['log_chatid']),
|
|
|
|
message
|
|
|
|
)
|