Skip to content

Commit

Permalink
chore: refactorizing
Browse files Browse the repository at this point in the history
  • Loading branch information
SantiiRepair committed Oct 10, 2023
1 parent 06c494d commit cfa3bd5
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 38 deletions.
33 changes: 18 additions & 15 deletions bot/helpers/queues.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import pickle
from bot import r
from typing import Dict, Tuple, Union

Expand All @@ -10,9 +11,9 @@ def add_or_create_queue(
type_of: str,
is_playing=False,
position=0,
) -> Union[Tuple, bool]:
) -> Union[int, bool]:
"""Add or create queue in `group_id` field"""
values = [
kw = [
{
"from_user": from_user,
"is_playing": is_playing,
Expand All @@ -22,23 +23,24 @@ def add_or_create_queue(
"type_of": type_of,
}
]
values: bytes = pickle.dumps(kw)
queue: dict = r.hgetall("queues")
if group_id in queue:
queue[group_id].append(values)
hset = r.hset("queues", group_id, queue[group_id])
if hset == 0:
return True, position
return position
return False
hset = r.hset("queues", group_id, values)
if hset == 1:
return True, position
return position
return False


def next_in_queue(group_id: str) -> Union[Tuple, None]:
"""Get next media in queue"""
queue: dict = r.hgetall("queues")
values: list = queue[group_id]
values: list = pickle.loads(queue[group_id])
if group_id not in queue:
return None
for i in range(len(values)):
Expand All @@ -59,7 +61,7 @@ def next_in_queue(group_id: str) -> Union[Tuple, None]:
def previous_in_queue(group_id: str) -> Union[Tuple, None]:
"""Get previous media in queue"""
queue: dict = r.hgetall("queues")
values: list = queue[group_id]
values: list = pickle.loads(queue[group_id])
if group_id not in queue:
return None
for i in range(len(values)):
Expand All @@ -82,12 +84,17 @@ def remove_queue(group_id: str) -> None:
r.hdel("queues", group_id)


def get_queues() -> Union[Dict, None]:
queues = r.hgetall("queues")
return queues


def get_current_position_in_queue(group_id: str) -> Union[int, None]:
"""Get the current position of the media that is playing"""
queue: dict = r.hgetall("queues")
if group_id not in queue:
return None
values: dict = queue[group_id][-1]
values: dict = pickle.loads(queue[group_id][-1])
for i in range(len(values)):
if values[i].get("is_playing"):
return values[i]["position"]
Expand All @@ -99,28 +106,24 @@ def get_last_position_in_queue(group_id: str) -> Union[int, None]:
queue: dict = r.hgetall("queues")
if group_id not in queue:
return None
value: dict = queue[group_id][-1]
value: dict = pickle.loads(queue[group_id][-1])
return value["position"]


def get_queues() -> Union[Dict, None]:
return r.hgetall("queues")


def update_is_played_in_queue(group_id: str, action: str) -> None:
"""Update `is_playing` status in queue"""
queue: dict = r.hgetall("queues")
values: list = queue[group_id]
values: list = pickle.loads(queue[group_id])
if group_id not in queue:
return None
for i in range(len(values)):
if values[i].get("is_playing"):
if action == "previous":
values[i]["is_playing"] = False
values[i - 1]["is_playing"] = True
return r.hset("queues", group_id, values)
return r.hset("queues", group_id, pickle.dumps(values))
elif action == "next":
values[i]["is_playing"] = False
values[i + 1]["is_playing"] = True
return r.hset("queues", group_id, values)
return r.hset("queues", group_id, pickle.dumps(values))
return None
21 changes: 11 additions & 10 deletions bot/plugins/commands/play_song.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@

@kreacher.on_message(filters.regex(pattern="^[!?/]play_song"))
async def _(client: Client, message: Message):
QUEUES = get_queues()
data = await user_info(message.from_user)
file_name = os.path.join(_cwd, f"../../downloads/songs/{str(uuid.uuid4())}.mp3")
if message.chat.type == ChatType.PRIVATE:
Expand Down Expand Up @@ -82,27 +83,27 @@ async def _(client: Client, message: Message):
_, url = await ytdl(fmt, ref)
if search == 0:
return await msg.edit(
"__Can't find song.\n\nTry searching with more specific title.__",
"**__Can't find song.\n\nTry searching with more specific title.__**",
)
if message.chat.id in get_queues():
if str(message.chat.id) in QUEUES:
position = get_last_position_in_queue(str(message.chat.id)) + 1
add_or_create_queue(
message.chat.id,
str(message.chat.id),
from_user=str(message.from_user.id),
date=str(datetime.now()),
file=url,
type_of="song_yt",
position=position,
)
return await msg.edit(
f"__Added to queue at {position} \n\n Title: [{name}]({url})\nDuration: {duration} Minutes\n Requested by:__ [{data['first_name']}]({data['mention']})",
f"__Added to queue at {position}\n\nTitle: [{name}]({url})\nDuration: {duration} Minutes\n Requested by:__ [{data['first_name']}]({data['mention']})",
reply_markup=InlineKeyboardMarkup(
[[InlineKeyboardButton("cʟᴏꜱᴇ", callback_data="cls")]]
),
)
if message.chat.id not in get_queues():
if str(message.chat.id) not in QUEUES:
add_or_create_queue(
message.chat.id,
str(message.chat.id),
from_user=str(message.from_user.id),
date=str(datetime.now()),
is_playing=True,
Expand Down Expand Up @@ -155,10 +156,10 @@ async def _(client: Client, message: Message):
)
url_mention = f"https://t.me/c/{message.chat.id}/{message.reply_to_message.id}"
msg_mention = url_mention.replace("/c/-100", "/c/")
if message.chat.id in get_queues():
if str(message.chat.id) in QUEUES:
position = get_last_position_in_queue(str(message.chat.id)) + 1
add_or_create_queue(
message.chat.id,
str(message.chat.id),
from_user=str(message.from_user.id),
date=str(datetime.now()),
file=media,
Expand All @@ -171,9 +172,9 @@ async def _(client: Client, message: Message):
[[InlineKeyboardButton("cʟᴏꜱᴇ", callback_data="cls")]]
),
)
if message.chat.id not in get_queues():
if str(message.chat.id) not in QUEUES:
add_or_create_queue(
message.chat.id,
str(message.chat.id),
from_user=str(message.from_user.id),
date=str(datetime.now()),
is_playing=True,
Expand Down
25 changes: 13 additions & 12 deletions bot/plugins/commands/play_video.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@

@kreacher.on_message(filters.regex(pattern="^[!?/]play_video"))
async def _(client: Client, message: Message):
QUEUES = get_queues()
data = await user_info(message.from_user)
try:
msg = await message.reply("\u23F3 **__Processing...__**")
Expand All @@ -46,10 +47,10 @@ async def _(client: Client, message: Message):
if " " in message.text:
query = message.text.split(maxsplit=1)[1]
if "cdn" in query:
if message.chat.id in get_queues():
if str(message.chat.id) in QUEUES:
position = get_last_position_in_queue(str(message.chat.id)) + 1
add_or_create_queue(
message.chat.id,
str(message.chat.id),
from_user=str(message.from_user.id),
date=str(datetime.now()),
file=query,
Expand All @@ -62,9 +63,9 @@ async def _(client: Client, message: Message):
[[InlineKeyboardButton("cʟᴏꜱᴇ", callback_data="cls")]]
),
)
elif message.chat.id not in get_queues():
if str(message.chat.id) not in QUEUES:
add_or_create_queue(
message.chat.id,
str(message.chat.id),
from_user=str(message.from_user.id),
date=str(datetime.now()),
is_playing=True,
Expand Down Expand Up @@ -114,10 +115,10 @@ async def _(client: Client, message: Message):
return await msg.edit(
"**__Can't find YouTube video.\n\nTry searching with more specific title.__**",
)
if message.chat.id in get_queues():
if str(message.chat.id) in QUEUES:
position = get_last_position_in_queue(str(message.chat.id)) + 1
add_or_create_queue(
message.chat.id,
str(message.chat.id),
from_user=str(message.from_user.id),
date=str(datetime.now()),
file=url,
Expand All @@ -130,9 +131,9 @@ async def _(client: Client, message: Message):
[[InlineKeyboardButton("cʟᴏꜱᴇ", callback_data="cls")]]
),
)
if message.chat.id not in get_queues():
if str(message.chat.id) not in QUEUES:
add_or_create_queue(
message.chat.id,
str(message.chat.id),
from_user=str(message.from_user.id),
date=str(datetime.now()),
is_playing=True,
Expand Down Expand Up @@ -177,10 +178,10 @@ async def _(client: Client, message: Message):
progress=progress,
progress_args=(client, message.chat, msg),
)
if message.chat.id in get_queues():
if str(message.chat.id) in QUEUES:
position = get_last_position_in_queue(str(message.chat.id)) + 1
add_or_create_queue(
message.chat.id,
str(message.chat.id),
from_user=str(message.from_user.id),
date=str(datetime.now()),
file=media,
Expand All @@ -193,9 +194,9 @@ async def _(client: Client, message: Message):
[[InlineKeyboardButton("cʟᴏꜱᴇ", callback_data="cls")]]
),
)
if message.chat.id not in get_queues():
if str(message.chat.id) not in QUEUES:
add_or_create_queue(
message.chat.id,
str(message.chat.id),
from_user=str(message.from_user.id),
date=str(datetime.now()),
is_playing=True,
Expand Down
2 changes: 1 addition & 1 deletion bot/plugins/filters/on_joined.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@ async def _(client: Client, message: Message):
"subscription": None,
}
)
"""
"""

0 comments on commit cfa3bd5

Please sign in to comment.