Skip to content
This repository was archived by the owner on Jul 24, 2024. It is now read-only.

Commit a11aa60

Browse files
committed
Maintenance update
1 parent 0a989a8 commit a11aa60

File tree

19 files changed

+229
-77
lines changed

19 files changed

+229
-77
lines changed

WebStreamer/__main__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@
1919

2020

2121
async def start_services():
22+
"""
23+
Start the bot and the web server
24+
"""
2225
LOGGER.info("------------------- Initializing Telegram Bot -------------------")
2326
await StreamBot.start()
2427
LOGGER.info("----------------------------- DONE -----------------------------")

WebStreamer/bot/plugins/admin.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@
2121
filters.command("status") & filters.private & filters.user(Vars.OWNER_ID),
2222
)
2323
async def status(_, m: Message):
24+
"""
25+
Get status of the bot, number of users, number of files, etc.
26+
"""
2427
dl = Downloads()
2528
filename = "downloadList.txt"
2629
total_users = await Users().total_users_count()
@@ -59,6 +62,9 @@ async def status(_, m: Message):
5962
& filters.reply,
6063
)
6164
async def broadcast_(_, m: Message):
65+
"""
66+
Broadcast a message to all users
67+
"""
6268
all_users = await Users().get_all_users()
6369
broadcast_msg = m.reply_to_message
6470
while 1:
@@ -79,7 +85,7 @@ async def broadcast_(_, m: Message):
7985
)
8086
async with open_aiofiles("broadcast.txt", "w") as broadcast_log_file:
8187
for user in all_users:
82-
sts, msg = await send_msg(user_id=int(user), message=broadcast_msg)
88+
sts, msg = await send_msg(user_id=int(user), m=broadcast_msg)
8389
if msg is not None:
8490
await broadcast_log_file.write(msg)
8591
if sts == 200:

WebStreamer/bot/plugins/ban.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77

88
@StreamBot.on_callback_query(filters.regex("^ban_"))
99
async def ban_user(c: StreamBot, q: CallbackQuery):
10+
"""
11+
Ban a user from using the bot
12+
"""
1013
user_id = int(q.data.split("_", 1)[1])
1114
await c.ban_chat_member(Vars.AUTH_CHANNEL, user_id)
1215
await q.answer("User Banned from Updates Channel!", show_alert=True)

WebStreamer/bot/plugins/start.py

Lines changed: 36 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646

4747
class Btns:
4848
channel_and_group = [
49-
("Support Group", "https://t.me/DivideProjectsDiscussion", "url"),
49+
("Support Group", "https://t.me/DivideSupport", "url"),
5050
("Channel", "https://t.me/DivideProjects", "url"),
5151
]
5252
about_me = ("About Me", "aboutbot")
@@ -57,6 +57,9 @@ class Btns:
5757
@StreamBot.on_message(filters.command("start") & filters.private)
5858
@joinCheck()
5959
async def start(_, m: Message):
60+
"""
61+
Start the bot
62+
"""
6063
return await m.reply_text(
6164
text=PMTEXT.format(m.from_user.mention),
6265
parse_mode=ParseMode.HTML,
@@ -68,6 +71,9 @@ async def start(_, m: Message):
6871
@StreamBot.on_message(filters.command("help") & filters.private)
6972
@joinCheck()
7073
async def help_handler(_, m: Message):
74+
"""
75+
Help message handler
76+
"""
7177
return await m.reply_text(
7278
HELPTEXT,
7379
parse_mode=ParseMode.HTML,
@@ -77,28 +83,36 @@ async def help_handler(_, m: Message):
7783

7884
@StreamBot.on_callback_query()
7985
async def button(_, m: CallbackQuery):
86+
"""
87+
handle button presses
88+
"""
8089
cb_data = m.data
8190
msg = m.message
8291

83-
if cb_data == "aboutbot":
84-
await msg.edit(
85-
text=ABOUT,
86-
parse_mode=ParseMode.HTML,
87-
disable_web_page_preview=True,
88-
reply_markup=ikb([[Btns.back]]),
89-
)
90-
elif cb_data == "helptext":
91-
await msg.edit(
92-
text=HELPTEXT,
93-
parse_mode=ParseMode.HTML,
94-
disable_web_page_preview=True,
95-
reply_markup=ikb([[Btns.back]]),
96-
)
97-
elif cb_data == "gotohome":
98-
await msg.edit(
99-
text=PMTEXT.format(msg.from_user.mention),
100-
parse_mode=ParseMode.HTML,
101-
disable_web_page_preview=True,
102-
reply_markup=ikb([Btns.channel_and_group, [Btns.about_me, Btns.help_me]]),
103-
)
92+
match cb_data:
93+
case "aboutbot":
94+
await msg.edit(
95+
text=ABOUT,
96+
parse_mode=ParseMode.HTML,
97+
disable_web_page_preview=True,
98+
reply_markup=ikb([[Btns.back]]),
99+
)
100+
case "helptext":
101+
await msg.edit(
102+
text=HELPTEXT,
103+
parse_mode=ParseMode.HTML,
104+
disable_web_page_preview=True,
105+
reply_markup=ikb([[Btns.back]]),
106+
)
107+
case "gotohome":
108+
await msg.edit(
109+
text=PMTEXT.format(msg.from_user.mention),
110+
parse_mode=ParseMode.HTML,
111+
disable_web_page_preview=True,
112+
reply_markup=ikb(
113+
[Btns.channel_and_group, [Btns.about_me, Btns.help_me]],
114+
),
115+
)
116+
case _:
117+
await msg.edit("Invalid Button Pressed!")
104118
await m.answer()

WebStreamer/bot/plugins/stream.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
<i>@DivideProjects </i>
2828
"""
2929

30+
# Cache for storing how many times a user has used the bot, takes number of mimuted from Vars
3031
ttl_dict = TTLCache(maxsize=512, ttl=(Vars.FLOODCONTROL_TIME_MINUTES * 60))
3132

3233

@@ -35,7 +36,7 @@
3536
& (filters.document | filters.video | filters.audio | filters.photo),
3637
group=4,
3738
)
38-
@joinCheck()
39+
@joinCheck() # Check if user has joined the channel
3940
async def private_receive_handler(c: Client, m: Message):
4041
user = m.from_user
4142
user_id = user.id
@@ -122,6 +123,9 @@ async def private_receive_handler(c: Client, m: Message):
122123

123124
@StreamBot.on_callback_query(filters.regex("^delete_url."))
124125
async def delete_download(_, q: CallbackQuery):
126+
"""
127+
Delete the download link from the database using a callback query
128+
"""
125129
user_id = q.from_user.id
126130
msg = q.message
127131
url = str(q.data.split(".")[-1])

WebStreamer/db/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55

66

77
def __connect_first():
8+
"""
9+
Connect to the database before importing the models
10+
"""
811
_ = MongoDB("test")
912
LOGGER.info("Initialized Database!")
1013

WebStreamer/db/downloads.py

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,28 @@
11
from datetime import datetime, timedelta
22
from secrets import token_urlsafe
3+
from typing import Tuple, Union
34

45
from WebStreamer.db.mongo import MongoDB
56
from WebStreamer.logger import LOGGER
67

78

89
class Downloads(MongoDB):
10+
"""
11+
Define downloads collection here
12+
"""
13+
914
db_name = "filestreamerbot_downloads"
1015

1116
def __init__(self):
17+
"""
18+
Initialize the collection
19+
"""
1220
super().__init__(self.db_name)
1321

1422
async def add_download(self, message_id: int, random_url: str, user_id: int) -> str:
23+
"""
24+
Add a download to the database
25+
"""
1526
LOGGER.info(f"Added {random_url}: {message_id}")
1627
real_link = token_urlsafe(16)
1728
await self.insert_one(
@@ -25,21 +36,30 @@ async def add_download(self, message_id: int, random_url: str, user_id: int) ->
2536
)
2637
return real_link
2738

28-
async def get_actual_link(self, link: str):
39+
async def get_actual_link(self, link: str) -> Union[str, None]:
40+
"""
41+
Get the actual link from the database
42+
"""
2943
document = await self.find_one({"random_link": link})
3044
if not document:
3145
return None
3246
return document["link"]
3347

34-
async def get_msg_id(self, link: str):
48+
async def get_msg_id(self, link: str) -> Tuple[int, bool, datetime]:
49+
"""
50+
Get the message id from the database
51+
"""
3552
document = await self.find_one({"link": link})
3653
if not document:
3754
return 0, False, datetime.now()
3855
valid_upto = document["valid_upto"]
3956
valid = valid_upto > datetime.now()
4057
return document["message_id"], valid, valid_upto
4158

42-
async def total_downloads(self):
59+
async def total_downloads(self) -> int:
60+
"""
61+
Get the total number of downloads
62+
"""
4363
return await self.count()
4464

4565
async def valid_downloads_list(self):

WebStreamer/db/mongo.py

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from typing import Any, Tuple, Union
2+
13
from motor.motor_asyncio import AsyncIOMotorClient
24

35
from WebStreamer.vars import Vars
@@ -7,55 +9,57 @@
79

810

911
class MongoDB:
10-
"""Class for interacting with Bot database."""
12+
"""
13+
Class for interacting with Bot database.
14+
"""
1115

1216
def __init__(self, collection) -> None:
1317
self.collection = main_db[collection]
1418

1519
# Insert one entry into collection
16-
async def insert_one(self, document):
20+
async def insert_one(self, document) -> str:
1721
result = await self.collection.insert_one(document)
1822
return repr(result.inserted_id)
1923

2024
# Find one entry from collection
21-
async def find_one(self, query):
25+
async def find_one(self, query) -> Union[bool, None, Any]:
2226
result = await self.collection.find_one(query)
2327
if result:
2428
return result
2529
return False
2630

2731
# Find entries from collection
28-
async def find_all(self, query=None):
32+
async def find_all(self, query=None) -> Union[bool, None, Any]:
2933
if query is None:
3034
query = {}
3135
return [document async for document in self.collection.find(query)]
3236

3337
# Count entries from collection
34-
async def count(self, query=None):
38+
async def count(self, query=None) -> int:
3539
if query is None:
3640
query = {}
3741
return await self.collection.count_documents(query)
3842

3943
# Delete entry/entries from collection
40-
async def delete_one(self, query):
44+
async def delete_one(self, query) -> int:
4145
await self.collection.delete_many(query)
4246
after_delete = await self.collection.count_documents({})
4347
return after_delete
4448

4549
# Replace one entry in collection
46-
async def replace(self, query, new_data):
50+
async def replace(self, query, new_data) -> Tuple[int, int]:
4751
old = await self.collection.find_one(query)
4852
_id = old["_id"]
4953
await self.collection.replace_one({"_id": _id}, new_data)
5054
new = await self.collection.find_one({"_id": _id})
5155
return old, new
5256

5357
# Update one entry from collection
54-
async def update(self, query, update):
58+
async def update(self, query, update) -> Tuple[int, int]:
5559
result = await self.collection.update_one(query, {"$set": update})
5660
new_document = await self.collection.find_one(query)
5761
return result.modified_count, new_document
5862

5963
@staticmethod
60-
async def db_command(command: str):
64+
async def db_command(command: str) -> Any:
6165
return await main_db.command(command)

WebStreamer/db/users.py

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,48 @@
11
from datetime import date
2+
from typing import List, Union
23

34
from WebStreamer.db.mongo import MongoDB
45
from WebStreamer.logger import LOGGER
56

67

7-
def new_user(uid):
8-
return {"id": uid, "join_date": date.today().isoformat(), "downloads": []}
8+
def new_user(uid: int):
9+
"""
10+
Creates a new user in the database
11+
"""
12+
return {
13+
"id": uid,
14+
"join_date": date.today().isoformat(),
15+
"downloads": [],
16+
}
917

1018

1119
class Users(MongoDB):
20+
"""
21+
Users collections to be made in the database
22+
"""
23+
1224
db_name = "filestreamerbot_users"
1325

1426
def __init__(self):
1527
super().__init__(self.db_name)
1628

17-
async def total_users_count(self):
29+
async def total_users_count(self) -> int:
30+
"""
31+
Returns the total number of users in the database
32+
"""
1833
return await self.count({})
1934

20-
async def get_all_users(self):
35+
async def get_all_users(self) -> List[int]:
36+
"""
37+
Returns a list of all users in the database
38+
"""
2139
users = await self.find_all({})
2240
return [user["id"] for user in users]
2341

24-
async def user_exists(self, user_id: int):
42+
async def user_exists(self, user_id: int) -> bool:
43+
"""
44+
Checks if a user exists in the database
45+
"""
2546
user = await self.find_one({"id": user_id})
2647
if not user:
2748
user_data = {
@@ -33,5 +54,8 @@ async def user_exists(self, user_id: int):
3354
return False
3455
return True
3556

36-
async def delete_user(self, user_id: int):
57+
async def delete_user(self, user_id: int) -> Union[bool, int]:
58+
"""
59+
Deletes a user from the database
60+
"""
3761
return await self.delete_one({"id": user_id})

WebStreamer/server/__init__.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,16 @@
66

77

88
async def web_server():
9+
"""
10+
Create the web server and return it
11+
"""
912
web_app = web.Application(client_max_size=30000000)
13+
# setup jinja2 with the web templates from templates folder
1014
setup_jinja2(
1115
web_app,
1216
enable_async=True,
1317
loader=FileSystemLoader("/app/WebStreamer/html/templates"),
1418
)
19+
# add the routes to the web app
1520
web_app.add_routes(routes)
1621
return web_app

0 commit comments

Comments
 (0)