Skip to content

Commit

Permalink
Fixing redis queues error
Browse files Browse the repository at this point in the history
  • Loading branch information
SantiiRepair committed Oct 11, 2023
1 parent bc30e1c commit 6d41274
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 34 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ downloads

*.env
*.log
*.rdb
*.lock
*.pyc
*.session
Expand Down
9 changes: 4 additions & 5 deletions bot/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,8 @@


async def start_bot():
print(f'{colored("[INFO]", "blue")}: LOADING BOT DETAILS')
bot_me = await kreacher.get_me()
print(f'{colored("[INFO]", "blue")}: BOT ID {bot_me.id}')
print(f'{colored("[INFO]:", "blue")} BOT ID {bot_me.id}')
await kreacher.set_bot_commands(
commands=[
BotCommand("config", "Set bot configuration"),
Expand All @@ -26,15 +25,15 @@ async def start_bot():
BotCommand("streaming", "Any movie or series"),
]
)
print(f'{colored("[INFO]", "blue")}: SETED BOT COMMANDS')
print(f'{colored("[INFO]:", "blue")} SETED BOT COMMANDS')


try:
setup_plugins()
ay.run_until_complete(start_bot())
print(f'{colored("[INFO]", "blue")}: SUCCESSFULLY STARTED BOT!')
print(f'{colored("[INFO]:", "blue")} SUCCESSFULLY STARTED BOT!')
idle()
except KeyboardInterrupt:
kreacher.disconnect()
assistant.disconnect()
print(f'{colored("[INFO]", "blue")}: CLIENTS DISCONNECTED')
print(f'{colored("[INFO]:", "blue")} CLIENTS DISCONNECTED')
5 changes: 3 additions & 2 deletions bot/commands/play_song.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
@kreacher.on_message(filters.regex(pattern="^[!?/]play_song"))
async def _(client: Client, message: Message):
QUEUES = get_queues()
print(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 @@ -85,7 +86,7 @@ async def _(client: Client, message: Message):
return await msg.edit(
"**__Can't find song.\n\nTry searching with more specific title.__**",
)
if str(message.chat.id) in str(QUEUES):
if str(message.chat.id) in QUEUES:
position = get_last_position_in_queue(str(message.chat.id)) + 1
add_or_create_queue(
str(message.chat.id),
Expand All @@ -101,7 +102,7 @@ async def _(client: Client, message: Message):
[[InlineKeyboardButton("cʟᴏꜱᴇ", callback_data="close")]]
),
)
if str(message.chat.id) not in str(QUEUES):
if str(message.chat.id) not in QUEUES:
add_or_create_queue(
str(message.chat.id),
from_user=str(message.from_user.id),
Expand Down
52 changes: 26 additions & 26 deletions bot/helpers/queues.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import pickle
import json
from bot import r
from typing import Dict, Tuple, Union

Expand All @@ -23,17 +23,16 @@ def add_or_create_queue(
"type_of": type_of,
}
]
values: bytes = pickle.dumps(kw)
queue: dict = r.hgetall("queues")
if group_id in str(queue):
giq: list = pickle.loads(queue[group_id])
print(giq)
values: bytes = json.dumps(kw).encode("utf-8")
queue: dict = get_queues()
if group_id in queue:
giq: list = queue[group_id]
giq.append(values)
hset = r.hset("queues", group_id, pickle.dumps(giq))
values: bytes = json.dumps(giq).encode("utf-8")
hset = r.hset("queues", group_id, values)
if hset == 0:
return position
return False
print(kw)
hset = r.hset("queues", group_id, values)
if hset == 1:
return position
Expand All @@ -42,9 +41,9 @@ def add_or_create_queue(

def next_in_queue(group_id: str) -> Union[Tuple, None]:
"""Get next media in queue"""
queue: dict = r.hgetall("queues")
values: list = pickle.loads(queue[group_id])
if group_id not in str(queue):
queue: dict = get_queues()
values: list = queue[group_id]
if group_id not in queue:
return None
for i in range(len(values)):
if values[i].get("is_playing"):
Expand All @@ -63,9 +62,9 @@ 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 = pickle.loads(queue[group_id])
if group_id not in str(queue):
queue: dict = get_queues()
values: list = queue[group_id]
if group_id not in queue:
return None
for i in range(len(values)):
if values[i].get("is_playing"):
Expand All @@ -88,16 +87,17 @@ def remove_queue(group_id: str) -> None:


def get_queues() -> Union[Dict, None]:
queues = r.hgetall("queues")
rqueues = r.hgetall("queues")
queues = {f.decode(): json.loads(v.decode()) for f, v in rqueues.items()}
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 str(queue):
queue: dict = get_queues()
if group_id not in queue:
return None
values: dict = pickle.loads(queue[group_id])
values: dict = queue[group_id]
for i in range(len(values)):
if values[i].get("is_playing"):
return values[i]["position"]
Expand All @@ -106,28 +106,28 @@ def get_current_position_in_queue(group_id: str) -> Union[int, None]:

def get_last_position_in_queue(group_id: str) -> Union[int, None]:
"""Get the last position of the media that will be played in the queue"""
queue: dict = r.hgetall("queues")
if group_id not in str(queue):
queue: dict = get_queues()
if group_id not in queue:
return None
value: dict = pickle.loads(queue[group_id])[-1]
value: dict = queue[group_id][-1]
print(value)
return value["position"]


def update_is_played_in_queue(group_id: str, action: str) -> Union[bool, None]:
"""Update `is_playing` status in queue"""
queue: dict = r.hgetall("queues")
if group_id not in str(queue):
queue: dict = get_queues()
if group_id not in queue:
return None
values: list = pickle.loads(queue[group_id])
values: list = queue[group_id]
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, pickle.dumps(values))
return r.hset("queues", group_id, json.dumps(values).encode("utf-8"))
if action == "next":
values[i]["is_playing"] = False
values[i + 1]["is_playing"] = True
return r.hset("queues", group_id, pickle.dumps(values))
return r.hset("queues", group_id, json.dumps(values).encode("utf-8"))
return True
2 changes: 1 addition & 1 deletion bot/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@ def setup_plugins():
sys.modules[module_name] = module

print(
f"{colored('[INFO]', 'blue')}: Bot has started {colored(module_name, 'yellow')}"
f"{colored('[INFO]:', 'blue')} Bot has started {colored(module_name, 'yellow')}"
)

0 comments on commit 6d41274

Please sign in to comment.