-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathbot.py
More file actions
173 lines (147 loc) · 6.23 KB
/
Copy pathbot.py
File metadata and controls
173 lines (147 loc) · 6.23 KB
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import os, sys, glob, importlib, logging, logging.config, pytz, asyncio
from pathlib import Path
import time as _time
# ── IST Logging Formatter ──────────────────────────────────────────────────
class ISTFormatter(logging.Formatter):
"""Logging formatter that always shows timestamps in IST (Asia/Kolkata)."""
_IST = pytz.timezone("Asia/Kolkata")
def converter(self, timestamp):
import datetime
dt = datetime.datetime.fromtimestamp(timestamp, tz=self._IST)
return dt.timetuple()
def formatTime(self, record, datefmt=None):
import datetime
dt = datetime.datetime.fromtimestamp(record.created, tz=self._IST)
if datefmt:
return dt.strftime(datefmt)
return dt.strftime("%H:%M:%S %p") # 24-hour IST with AM/PM
# ──────────────────────────────────────────────────────────────────────────
# Get logging configurations
logging.config.fileConfig('logging.conf')
logging.getLogger().setLevel(logging.INFO)
logging.getLogger("pyrogram").setLevel(logging.ERROR)
logging.getLogger("imdbpy").setLevel(logging.ERROR)
# Apply IST formatter to every handler so ALL log timestamps are in IST
for _handler in logging.root.handlers:
_fmt = _handler.formatter
_datefmt = _fmt.datefmt if _fmt else "%I:%M:%S %p"
_msgfmt = _fmt._fmt if _fmt else "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
_handler.setFormatter(ISTFormatter(fmt=_msgfmt, datefmt=_datefmt))
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logging.getLogger("aiohttp").setLevel(logging.ERROR)
logging.getLogger("aiohttp.web").setLevel(logging.ERROR)
from requests import get as rget
from os import environ
CONFIG_FILE_URL = environ.get('CONFIG_FILE_URL')
# Dynamically load info.py
spec = importlib.util.spec_from_file_location("info", "info.py")
info = importlib.util.module_from_spec(spec)
spec.loader.exec_module(info)
# Access BOT_TOKEN from info.py
BOT_TOKEN = getattr(info, 'BOT_TOKEN', None)
try:
if not BOT_TOKEN:
if not CONFIG_FILE_URL:
raise ValueError("CONFIG_FILE_URL is missing or empty")
res = rget(CONFIG_FILE_URL)
if res.status_code == 200:
# Write the content to info.py file
with open('info.py', 'wb+') as f:
f.write(res.content)
logging.info("info.py downloaded successfully!")
else:
logging.error(f"Failed to download info.py: {res.status_code}")
# Reload after download
spec.loader.exec_module(info)
BOT_TOKEN = getattr(info, 'BOT_TOKEN', None)
if not BOT_TOKEN:
raise ValueError("BOT_TOKEN not found in info.py!")
except Exception as e:
logging.error(e)
# Import info.py after downloading
from info import *
from pyrogram import Client, idle
from database.ia_filterdb import Media
from database.users_chats_db import db
from utils import temp
from typing import Union, Optional, AsyncGenerator
from script import script
from datetime import date, datetime
from aiohttp import web
from plugins import web_server
from plugins.clone import restart_bots
from stream.bot import KPSBot
from stream.util.keepalive import ping_server
from stream.bot.clients import initialize_clients
from database.filter_keywords_db import load_keywords_to_cache
ppath = "plugins/*.py"
files = glob.glob(ppath)
KPSBot.start()
loop = asyncio.get_event_loop()
async def start():
print('Initalizing Your Bot')
bot_info = await KPSBot.get_me()
await initialize_clients()
for name in files:
with open(name) as a:
patt = Path(a.name)
plugin_name = patt.stem.replace(".py", "")
plugins_dir = Path(f"plugins/{plugin_name}.py")
import_path = "plugins.{}".format(plugin_name)
spec = importlib.util.spec_from_file_location(import_path, plugins_dir)
load = importlib.util.module_from_spec(spec)
spec.loader.exec_module(load)
sys.modules["plugins." + plugin_name] = load
print("Imported => " + plugin_name)
if ON_HEROKU:
asyncio.create_task(ping_server())
b_users, b_chats = await db.get_banned()
temp.BANNED_USERS = b_users
temp.BANNED_CHATS = b_chats
await load_keywords_to_cache() # seed + warm FILTER_KEYWORDS cache from MongoDB
await Media.ensure_indexes()
me = await KPSBot.get_me()
temp.BOT = KPSBot
temp.ME = me.id
temp.U_NAME = me.username
temp.B_NAME = me.first_name
logging.info(LOG_STR)
logging.info(script.LOGO)
tz = pytz.timezone('Asia/Kolkata')
today = date.today()
now = datetime.now(tz)
time = now.strftime("%I:%M:%S %p")
await KPSBot.send_message(chat_id=LOG_CHANNEL, text=script.RESTART_TXT.format(today, time))
if CLONE_MODE == True:
print("Restarting All Clone Bots.......")
await restart_bots()
print("Restarted All Clone Bots.")
app = web.AppRunner(await web_server())
await app.setup()
bind_address = "0.0.0.0"
await web.TCPSite(app, bind_address, PORT).start()
await idle()
async def restart_loop():
try:
if RANDOM_UPDATES == True:
try:
await asyncio.wait_for(start(), timeout= TIMEOUT * 60)
print(f'🔄 Next Restart for in {TIMEOUT} minutes..')
#os.system("python3 get_config.py")
os.execl(sys.executable, sys.executable, *sys.argv)
except KeyboardInterrupt:
logging.info('Service Stopped Bye 👋')
except Exception as e:
logging.error(f"Error occurred: {e}")
else:
await start()
except:
await start()
if __name__ == '__main__':
try:
loop.run_until_complete(restart_loop())
except KeyboardInterrupt:
logging.info('Service Stopped Bye 👋')