Skip to content

Commit eb2ddcd

Browse files
committed
Refactor user and sudo user handling functions for improved clarity and performance; update user retrieval method in telegram_info.py
1 parent 8253f54 commit eb2ddcd

File tree

3 files changed

+42
-43
lines changed

3 files changed

+42
-43
lines changed

bot_package/downloader.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,6 @@ def download_progress_hook(d):
101101
f"**By:** {user_mention}\n**User ID:** `{user_id}`\n\n"
102102
f"**Progress:** {progress_bar} {percentage_float:.1f}%\n"
103103
f"`{downloaded_mb:.2f} MB / {total_mb:.2f} MB`\n"
104-
f"**Speed:** {speed}\n"
105-
f"**ETA:** {eta}"
106104
)
107105

108106
# Schedule the edit_status_message coroutine on the main event loop

bot_package/handlers.py

Lines changed: 30 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737
find_sudo_user_by_id,
3838
remove_a_sudo_user_from_the_db,
3939
list_all_sudo_users,
40-
list_all_users
40+
list_all_users,
4141
)
4242
from .downloader import get_video_info, download_video_async
4343
from replies import * # Assuming replies.py exists and contains text variables
@@ -49,9 +49,7 @@
4949

5050

5151
# --- MongoDB tools ---
52-
async def mongo_check_user_database(
53-
userid: str, userdict=None, message=None
54-
) -> bool:
52+
async def mongo_check_user_database(userid: str, userdict=None, message=None) -> bool:
5553
if find_user_by_id_in_mongodb(userid) == "False":
5654
# If user not found, create a new document in MongoDB for the user
5755
info: dict = {
@@ -78,7 +76,7 @@ async def mongo_check_user_database(
7876

7977

8078
async def mongo_check_sudo_database(
81-
userid: str, userdict: dict=None, message=None
79+
userid: str, userdict: dict = None, message=None
8280
) -> bool:
8381
if not await find_sudo_user_by_id(userid):
8482
# If user not found, create a new document in MongoDB for the user
@@ -97,8 +95,8 @@ async def mongo_check_sudo_database(
9795
"chat_id": message.chat.id or "None",
9896
"chat_title": message.chat.title or "None",
9997
"chat_type": str(message.chat.type) or "None",
100-
"chat_username": message.chat.username or "None"
101-
}
98+
"chat_username": message.chat.username or "None",
99+
}
102100

103101
await add_a_sudo_user_to_the_db(info)
104102
return "True"
@@ -121,7 +119,6 @@ async def start_command(client: Client, message):
121119
)
122120

123121

124-
125122
@bot.on_message(filters.command("help"))
126123
async def help_command(client: Client, message):
127124

@@ -251,6 +248,7 @@ async def restart_command(client: Client, message):
251248
# --- URL Handler ---
252249
VIDEO_ID = []
253250

251+
254252
@bot.on_message(
255253
filters.regex(
256254
r"(https?://)?(www\.)?(youtube\.com|youtu\.?be)/.+(watch\?v=|embed/|v/|.+\?v=)?([^&\n]{11})",
@@ -286,8 +284,9 @@ async def youtube_url_handler(client: Client, message):
286284
print("Checking thumbnail status...")
287285
args: tuple = (
288286
thumbnail_url,
289-
video_id,
290-
user_id,)
287+
video_id,
288+
user_id,
289+
)
291290
convert_thumbnail_to_jpeg(args) # Convert thumbnail to JPEG
292291
VIDEO_ID.append(video_id) # Store the video ID for later use
293292
print("Thumbnail conversion complete.")
@@ -320,6 +319,7 @@ async def youtube_url_handler(client: Client, message):
320319

321320
##### Add a sudo user ########
322321

322+
323323
@bot.on_message(filters.command("addsudo"))
324324
async def add_sudo_user(client: Client, message):
325325
user_id = str(message.from_user.id)
@@ -372,7 +372,7 @@ async def add_sudo_user(client: Client, message):
372372
and find_sudo_user_by_id(str(message.text.split(" ")[1].strip())) == "False"
373373
):
374374
sudo_user_id: str = str(message_text).split(" ")[1]
375-
user_info = await bot.get_chat(sudo_user_id)
375+
user_info = await bot.get_users(sudo_user_id)
376376
info: dict = {
377377
"_id": sudo_user_id or "None",
378378
"date_time": message.date or "None",
@@ -430,7 +430,7 @@ async def remove_sudo_user(client: Client, message):
430430
and find_sudo_user_by_id(str(message.text.split(" ")[1].strip())) == "True"
431431
):
432432
sudo_user_id: str = str(message_text).split(" ")[1]
433-
user_info = await bot.get_chat(sudo_user_id)
433+
user_info = await bot.get_users(sudo_user_id)
434434
remove_a_sudo_user_from_the_db(sudo_user_id)
435435
await message.reply(f"{user_info.first_name} removed from Sudo users")
436436
return
@@ -442,15 +442,13 @@ async def remove_sudo_user(client: Client, message):
442442

443443
# ---- List sudo users --------#
444444

445+
445446
@bot.on_message(filters.command("sudo"))
446447
async def list_sudo_users(client: Client, message):
447448
sudo_user_names = list_all_sudo_users()
448449
enumerated_sudo_user_names = []
449450
user_id = str(message.from_user.id)
450-
if (
451-
user_id not in AUTH_USERS
452-
and find_sudo_user_by_id(user_id) == "False"
453-
):
451+
if user_id not in AUTH_USERS and find_sudo_user_by_id(user_id) == "False":
454452
not_authorized = await message.reply(
455453
"You are not authorized to use this command"
456454
)
@@ -460,13 +458,15 @@ async def list_sudo_users(client: Client, message):
460458
return
461459
checking = await message.reply("Checking sudo users...")
462460
sudo_users_count = count_sudo_users()
463-
if sudo_users_count != 0:
461+
462+
if sudo_users_count > 0:
464463
# print all the elements in the list with a prefix starting with 1
465464
for i in range(len(sudo_user_names)):
466-
enumerated_sudo_user_names.append(f"{i+1}: {sudo_user_names[i]}\n")
465+
enumerated_sudo_user_names.append(f"{i+1}. {sudo_user_names[i]}\n")
467466
await message.delete()
468467
await checking.edit(
469-
f"**__Total Sudo Users:__** `{sudo_users_count}`\n\n" + "\n".join(sudo_user_names)
468+
f"**__Sudo Users:__** `{sudo_users_count}`\n\n"
469+
+ "".join(enumerated_sudo_user_names)
470470
)
471471
else:
472472
err = await message.reply("Error counting sudo users.")
@@ -482,12 +482,10 @@ async def list_sudo_users(client: Client, message):
482482
@bot.on_message(filters.command("users"))
483483
async def list_users(client: Client, message):
484484
bot_user_names = list_all_users()
485+
bot_user_count = count_bot_users()
485486
enumerated_bot_user_names = []
486487
user_id = str(message.from_user.id)
487-
if (
488-
user_id not in AUTH_USERS
489-
and find_user_by_id_in_mongodb(user_id) == "False"
490-
):
488+
if user_id not in AUTH_USERS and find_user_by_id_in_mongodb(user_id) == "False":
491489
not_authorized = await message.reply(
492490
"You are not authorized to use this command"
493491
)
@@ -496,25 +494,26 @@ async def list_users(client: Client, message):
496494
await not_authorized.delete()
497495
return
498496
checking = await message.reply("Checking database...")
499-
user_count = count_bot_users()
500-
if user_count != 0:
497+
if bot_user_count > 0:
501498
# print all the elements in the list with a prefix starting with 1
502499
for i in range(len(bot_user_names)):
503-
enumerated_bot_user_names.append(f"{i+1}: {bot_user_names[i]}\n")
500+
enumerated_bot_user_names.append(f"{i+1}. {bot_user_names[i]}\n")
504501

505502
await checking.edit(
506-
f"**__Total Users:__** `{user_count}`\n\n" + "".join(enumerated_bot_user_names)
503+
f"**__Total Users:__** `{bot_user_count}`\n\n"
504+
+ "".join(enumerated_bot_user_names)
507505
)
508-
506+
509507
await message.delete()
510-
508+
511509
else:
512510
err = await message.reply("Error counting users.")
513511
await message.delete()
514512
await checking.delete()
515513
await asyncio.sleep(5)
516514
await err.delete()
517515

516+
518517
# --- Command to show information about the lunux system
519518
@bot.on_message(filters.command("server"))
520519
async def server_info(client: Client, message):
@@ -531,8 +530,7 @@ async def server_info(client: Client, message):
531530
f"**Used:** {shutil.disk_usage('/').used / (1024. ** 3):.2f} GB used\n"
532531
f"**Free:** {shutil.disk_usage('/').free / (1024. ** 3):.2f} GB free\n"
533532
)
534-
await message.reply(server_info_text, disable_web_page_preview=True)
535-
533+
await message.reply(server_info_text)
536534

537535

538536
# --- Callback Query Handler ---
@@ -761,7 +759,7 @@ async def upload_progress(current, total):
761759
if LOG_CHANNEL:
762760
try:
763761
log_channel_id = int(LOG_CHANNEL) # Ensure it's an int
764-
await bot.forward_messages(log_channel_id, chat_id, send.id)
762+
await bot.copy_message(log_channel_id, chat_id, send.id)
765763
except (ValueError, PeerIdInvalid) as log_err:
766764
print(
767765
f"Error forwarding to LOG_CHANNEL ({LOG_CHANNEL}): {log_err}. Check ID and bot membership."

bot_package/helpers.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -195,15 +195,17 @@ def remove_a_sudo_user_from_the_db(id: str) -> str:
195195
except Exception as e:
196196
print(f"Error removing document: {e}")
197197
return "False"
198-
198+
199+
199200
# counting all documents in a database
200-
def count_sudo_users() -> str:
201-
count = client.sudo_db.sudo_users.count_documents(filter={})
202-
return str(count)
201+
def count_sudo_users() -> int:
202+
count: int = client.sudo_db.sudo_users.count_documents(filter={})
203+
return count
204+
205+
def count_bot_users() -> int:
206+
count: int = client.bot_db.bot_collection.count_documents(filter={})
207+
return count
203208

204-
def count_bot_users() -> str:
205-
count = client.bot_db.bot_collection.count_documents(filter={})
206-
return str(count)
207209

208210
# list all users in the bot database by their first name
209211
def list_all_users() -> list:
@@ -212,20 +214,21 @@ def list_all_users() -> list:
212214
bot_db = client.bot_db
213215
bot_collection = bot_db.bot_collection
214216
users = bot_collection.find({})
215-
user_list = [f"{user["fist_name"]} `{user["_id"]}`" for user in users]
217+
user_list = [f"{user["first_name"]} `{user["_id"]}`" for user in users]
216218
return user_list
217219
except Exception as e:
218220
print(f"Error listing users: {e}")
219221
return f"Error listing user names: {e}"
220222

223+
221224
# list all sudo users in the bot database by their first name
222225
def list_all_sudo_users() -> list:
223226
"""Lists all sudo users in the bot database."""
224227
try:
225228
sudo_db = client.sudo_db
226229
bot_collection = sudo_db.sudo_users
227230
users = bot_collection.find({})
228-
sudo_list = [f"{user["fist_name"]} `{user["_id"]}`" for user in users]
231+
sudo_list = [f"{user["first_name"]} `{user["_id"]}`" for user in users]
229232
return sudo_list
230233
except Exception as e:
231234
print(f"Error listing sudo users: {e}")

0 commit comments

Comments
 (0)