forked from anasty17/mirror-leech-telegram-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__main__.py
270 lines (245 loc) · 10.3 KB
/
__main__.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
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
from signal import signal, SIGINT
from aiofiles.os import path as aiopath, remove as aioremove
from aiofiles import open as aiopen
from os import execl as osexecl
from psutil import (
disk_usage,
cpu_percent,
swap_memory,
cpu_count,
virtual_memory,
net_io_counters,
boot_time,
)
from time import time
from sys import executable
from pyrogram.handlers import MessageHandler
from pyrogram.filters import command
from asyncio import create_subprocess_exec, gather
from bot import (
bot,
botStartTime,
LOGGER,
Interval,
DATABASE_URL,
QbInterval,
INCOMPLETE_TASK_NOTIFIER,
scheduler,
)
from .helper.ext_utils.files_utils import clean_all, exit_clean_up
from .helper.ext_utils.bot_utils import cmd_exec, sync_to_async, initiate_help_messages
from .helper.ext_utils.status_utils import get_readable_file_size, get_readable_time
from .helper.ext_utils.db_handler import DbManger
from .helper.telegram_helper.bot_commands import BotCommands
from .helper.telegram_helper.message_utils import sendMessage, editMessage, sendFile
from .helper.telegram_helper.filters import CustomFilters
from .helper.telegram_helper.button_build import ButtonMaker
from bot.helper.listeners.aria2_listener import start_aria2_listener
from .modules import (
authorize,
cancel_task,
clone,
gd_count,
gd_delete,
gd_search,
mirror_leech,
status,
torrent_search,
torrent_select,
ytdlp,
rss,
shell,
eval,
users_settings,
bot_settings,
)
async def stats(_, message):
if await aiopath.exists(".git"):
last_commit = await cmd_exec(
"git log -1 --date=short --pretty=format:'%cd <b>From</b> %cr'", True
)
last_commit = last_commit[0]
else:
last_commit = "No UPSTREAM_REPO"
total, used, free, disk = disk_usage("/")
swap = swap_memory()
memory = virtual_memory()
stats = (
f"<b>Commit Date:</b> {last_commit}\n\n"
f"<b>Bot Uptime:</b> {get_readable_time(time() - botStartTime)}\n"
f"<b>OS Uptime:</b> {get_readable_time(time() - boot_time())}\n\n"
f"<b>Total Disk Space:</b> {get_readable_file_size(total)}\n"
f"<b>Used:</b> {get_readable_file_size(used)} | <b>Free:</b> {get_readable_file_size(free)}\n\n"
f"<b>Upload:</b> {get_readable_file_size(net_io_counters().bytes_sent)}\n"
f"<b>Download:</b> {get_readable_file_size(net_io_counters().bytes_recv)}\n\n"
f"<b>CPU:</b> {cpu_percent(interval=0.5)}%\n"
f"<b>RAM:</b> {memory.percent}%\n"
f"<b>DISK:</b> {disk}%\n\n"
f"<b>Physical Cores:</b> {cpu_count(logical=False)}\n"
f"<b>Total Cores:</b> {cpu_count(logical=True)}\n\n"
f"<b>SWAP:</b> {get_readable_file_size(swap.total)} | <b>Used:</b> {swap.percent}%\n"
f"<b>Memory Total:</b> {get_readable_file_size(memory.total)}\n"
f"<b>Memory Free:</b> {get_readable_file_size(memory.available)}\n"
f"<b>Memory Used:</b> {get_readable_file_size(memory.used)}\n"
)
await sendMessage(message, stats)
async def start(client, message):
buttons = ButtonMaker()
buttons.ubutton("Repo", "https://www.github.com/anasty17/mirror-leech-telegram-bot")
buttons.ubutton("Owner", "https://t.me/anas_tayyar")
reply_markup = buttons.build_menu(2)
if await CustomFilters.authorized(client, message):
start_string = f"""
This bot can mirror all your links|files|torrents to Google Drive or any rclone cloud or to telegram.
Type /{BotCommands.HelpCommand} to get a list of available commands
"""
await sendMessage(message, start_string, reply_markup)
else:
await sendMessage(
message,
"You Are not authorized user! Deploy your own mirror-leech bot",
reply_markup,
)
async def restart(_, message):
restart_message = await sendMessage(message, "Restarting...")
if scheduler.running:
scheduler.shutdown(wait=False)
if QbInterval:
QbInterval[0].cancel()
if Interval:
for intvl in list(Interval.values()):
intvl.cancel()
await clean_all()
proc1 = await create_subprocess_exec(
"pkill", "-9", "-f", "gunicorn|aria2c|qbittorrent-nox|ffmpeg|rclone"
)
proc2 = await create_subprocess_exec("python3", "update.py")
await gather(proc1.wait(), proc2.wait())
async with aiopen(".restartmsg", "w") as f:
await f.write(f"{restart_message.chat.id}\n{restart_message.id}\n")
osexecl(executable, executable, "-m", "bot")
async def ping(_, message):
start_time = int(round(time() * 1000))
reply = await sendMessage(message, "Starting Ping")
end_time = int(round(time() * 1000))
await editMessage(reply, f"{end_time - start_time} ms")
async def log(_, message):
await sendFile(message, "log.txt")
help_string = f"""
NOTE: Try each command without any argument to see more detalis.
/{BotCommands.MirrorCommand[0]} or /{BotCommands.MirrorCommand[1]}: Start mirroring to Google Drive.
/{BotCommands.QbMirrorCommand[0]} or /{BotCommands.QbMirrorCommand[1]}: Start Mirroring to Google Drive using qBittorrent.
/{BotCommands.YtdlCommand[0]} or /{BotCommands.YtdlCommand[1]}: Mirror yt-dlp supported link.
/{BotCommands.LeechCommand[0]} or /{BotCommands.LeechCommand[1]}: Start leeching to Telegram.
/{BotCommands.QbLeechCommand[0]} or /{BotCommands.QbLeechCommand[1]}: Start leeching using qBittorrent.
/{BotCommands.YtdlLeechCommand[0]} or /{BotCommands.YtdlLeechCommand[1]}: Leech yt-dlp supported link.
/{BotCommands.CloneCommand} [drive_url]: Copy file/folder to Google Drive.
/{BotCommands.CountCommand} [drive_url]: Count file/folder of Google Drive.
/{BotCommands.DeleteCommand} [drive_url]: Delete file/folder from Google Drive (Only Owner & Sudo).
/{BotCommands.UserSetCommand} [query]: Users settings.
/{BotCommands.BotSetCommand} [query]: Bot settings.
/{BotCommands.BtSelectCommand}: Select files from torrents by gid or reply.
/{BotCommands.CancelTaskCommand}: Cancel task by gid or reply.
/{BotCommands.CancelAllCommand} [query]: Cancel all [status] tasks.
/{BotCommands.ListCommand} [query]: Search in Google Drive(s).
/{BotCommands.SearchCommand} [query]: Search for torrents with API.
/{BotCommands.StatusCommand}: Shows a status of all the downloads.
/{BotCommands.StatsCommand}: Show stats of the machine where the bot is hosted in.
/{BotCommands.PingCommand}: Check how long it takes to Ping the Bot (Only Owner & Sudo).
/{BotCommands.AuthorizeCommand}: Authorize a chat or a user to use the bot (Only Owner & Sudo).
/{BotCommands.UnAuthorizeCommand}: Unauthorize a chat or a user to use the bot (Only Owner & Sudo).
/{BotCommands.UsersCommand}: show users settings (Only Owner & Sudo).
/{BotCommands.AddSudoCommand}: Add sudo user (Only Owner).
/{BotCommands.RmSudoCommand}: Remove sudo users (Only Owner).
/{BotCommands.RestartCommand}: Restart and update the bot (Only Owner & Sudo).
/{BotCommands.LogCommand}: Get a log file of the bot. Handy for getting crash reports (Only Owner & Sudo).
/{BotCommands.ShellCommand}: Run shell commands (Only Owner).
/{BotCommands.EvalCommand}: Run Python Code Line | Lines (Only Owner).
/{BotCommands.ExecCommand}: Run Commands In Exec (Only Owner).
/{BotCommands.ClearLocalsCommand}: Clear {BotCommands.EvalCommand} or {BotCommands.ExecCommand} locals (Only Owner).
/{BotCommands.RssCommand}: RSS Menu.
"""
async def bot_help(_, message):
await sendMessage(message, help_string)
async def restart_notification():
if await aiopath.isfile(".restartmsg"):
with open(".restartmsg") as f:
chat_id, msg_id = map(int, f)
else:
chat_id, msg_id = 0, 0
async def send_incompelete_task_message(cid, msg):
try:
if msg.startswith("Restarted Successfully!"):
await bot.edit_message_text(
chat_id=chat_id, message_id=msg_id, text=msg
)
await aioremove(".restartmsg")
else:
await bot.send_message(
chat_id=cid,
text=msg,
disable_web_page_preview=True,
disable_notification=True,
)
except Exception as e:
LOGGER.error(e)
if INCOMPLETE_TASK_NOTIFIER and DATABASE_URL:
if notifier_dict := await DbManger().get_incomplete_tasks():
for cid, data in notifier_dict.items():
msg = "Restarted Successfully!" if cid == chat_id else "Bot Restarted!"
for tag, links in data.items():
msg += f"\n\n{tag}: "
for index, link in enumerate(links, start=1):
msg += f" <a href='{link}'>{index}</a> |"
if len(msg.encode()) > 4000:
await send_incompelete_task_message(cid, msg)
msg = ""
if msg:
await send_incompelete_task_message(cid, msg)
if await aiopath.isfile(".restartmsg"):
try:
await bot.edit_message_text(
chat_id=chat_id, message_id=msg_id, text="Restarted Successfully!"
)
except:
pass
await aioremove(".restartmsg")
async def main():
await gather(
clean_all(),
torrent_search.initiate_search_tools(),
restart_notification(),
initiate_help_messages(),
)
await sync_to_async(start_aria2_listener, wait=False)
bot.add_handler(MessageHandler(start, filters=command(BotCommands.StartCommand)))
bot.add_handler(
MessageHandler(
log, filters=command(BotCommands.LogCommand) & CustomFilters.sudo
)
)
bot.add_handler(
MessageHandler(
restart, filters=command(BotCommands.RestartCommand) & CustomFilters.sudo
)
)
bot.add_handler(
MessageHandler(
ping, filters=command(BotCommands.PingCommand) & CustomFilters.authorized
)
)
bot.add_handler(
MessageHandler(
bot_help,
filters=command(BotCommands.HelpCommand) & CustomFilters.authorized,
)
)
bot.add_handler(
MessageHandler(
stats, filters=command(BotCommands.StatsCommand) & CustomFilters.authorized
)
)
LOGGER.info("Bot Started!")
signal(SIGINT, exit_clean_up)
bot.loop.run_until_complete(main())
bot.loop.run_forever()