-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
__init__.py
136 lines (110 loc) · 4.43 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import sys, os, logging, socket, pdb, json, pickle, dotenv, datetime, re
import base64, re, httpx
from datetime import timedelta
from telegram import Bot, Chat, Message, User
from telegram.ext import JobQueue
from handlers import *
import translations as translations
from typing import List
from cryptography.fernet import Fernet
from util.util_stripe import *
import util.util_paypal_receive as paypal
import datetime
import translations.translations as translations
import plugin_system.main as plugin_system_main
from plugin_system.plugin_manager import PluginManager
import requests, inspect
import os, platform, time, asyncio
from telegram import Update
from telegram.ext import CommandHandler, CallbackContext
# ------------------------------------------
# Construct the URL for the sendMessage endpoint
dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
dotenv.load_dotenv(dotenv_path)
bot_token = os.getenv('DEFAULT_BOT_TOKEN', None)
telegram_api_base_url = f'https://api.telegram.org/bot{bot_token}/sendMessage' if bot_token else None
def telegram_object_to_dict(obj):
if isinstance(obj, User):
return {
"id": obj.id,
"is_bot": obj.is_bot,
"first_name": obj.first_name,
"last_name": obj.last_name,
"username": obj.username,
"language_code": obj.language_code,
"can_join_groups": obj.can_join_groups,
"can_read_all_group_messages": obj.can_read_all_group_messages,
"supports_inline_queries": obj.supports_inline_queries
}
elif isinstance(obj, Message):
return {
"message_id": obj.message_id,
"date": obj.date.isoformat() if obj.date else None,
"chat": telegram_object_to_dict(obj.chat),
"from_user": telegram_object_to_dict(obj.from_user) if obj.from_user else None,
"text": obj.text
}
elif isinstance(obj, Chat):
return {
"id": obj.id,
"type": obj.type,
"title": obj.title,
"username": obj.username,
"first_name": obj.first_name,
"last_name": obj.last_name
}
# Add more elif blocks for other telegram object types as needed
else:
raise TypeError(f"Object of type {obj.__class__.__name__} is not JSON serializable")
def handle_exception(exc_type, exc_value, exc_traceback):
"""Handle global unhandled exceptions and start the debugger.
Args:
exc_type (_type_): _description_
exc_value (_type_): _description_
exc_traceback (_type_): _description_
"""
if issubclass(exc_type, KeyboardInterrupt):
# Call the default excepthook for KeyboardInterrupt
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
print(f"An unhandled exception occurred: {exc_value}")
debug_mode = input_with_timeout("Press enter to continue or 'D' + enter to launch debugger ...")
if debug_mode.lower() == 'd':
pdb.post_mortem(exc_traceback)
# Set the custom exception handler
sys.excepthook = handle_exception
class TelegramObjectEncoder(json.JSONEncoder):
def default(self, obj):
try:
return telegram_object_to_dict(obj)
except TypeError:
return super().default(obj)
# ---- Add parent folder to import path ----
script_path = os.path.dirname(os.path.realpath(__file__))
parent_folder = os.path.dirname(script_path)
common_module_path = rf"{parent_folder}{os.sep}"
sys.path.append(common_module_path)
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(parent_folder)
script_name = os.path.basename(sys.argv[0]).replace('.py', '')
# ---- Logging ----------------------------
log_folder = f'{script_path}{os.sep}log'
if not os.path.exists(log_folder):
os.makedirs(log_folder)
logging.basicConfig(
format="%(asctime)s:%(levelname)s:%(message)s",
level=logging.DEBUG,
handlers=[
logging.FileHandler(f'{log_folder}{os.sep}{script_name}.log'),
logging.StreamHandler(sys.stdout)
]
)
# set up logging error messages to red color
logging.addLevelName(logging.ERROR, "\033[1;31m%s\033[1;0m" % logging.getLevelName(logging.ERROR))
logger = logging.getLogger(__name__)
logger.debug(f"Log folder: {log_folder}")
# ------------------------------------------
from util.util_decorators import *
from util.util_telegram import *
from util.util_console import *
from handlers import *