Skip to content

Commit

Permalink
Refactored
Browse files Browse the repository at this point in the history
  • Loading branch information
SantiiRepair committed Oct 9, 2023
1 parent 51b141a commit 0463ba1
Show file tree
Hide file tree
Showing 7 changed files with 142 additions and 96 deletions.
8 changes: 4 additions & 4 deletions bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
_BOT_TOKEN = config.BOT_TOKEN
_SESSION_STRING = config.SESSION_STRING
_POSTGRES_DB = config.POSTGRES_DB
_POSTGRES_USER = config._POSTGRES_USER
_POSTGRES_USER = config.POSTGRES_USER
_POSTGRES_PASSWORD = config.POSTGRES_PASSWORD
_POSTGRES_HOST = config.POSTGRES_HOST
_POSTGRES_PORT = config.POSTGRES_PORT
Expand Down Expand Up @@ -58,8 +58,8 @@

kreacher = Client(
"bot.kreacher",
api_id=API_ID,
api_hash=API_HASH,
api_id=_API_ID,
api_hash=_API_HASH,
bot_token=_BOT_TOKEN,
)

Expand All @@ -73,7 +73,7 @@
# ------------------------------------------------------------------------------

engine = db.create_engine(
f"postgresql://{_POSTGRES_USER}:{_POSTGRES_PASSWORD}@{_POSTGRES_HOST}:{POSTGRES_PORT}/{_POSTGRES_DB}",
f"postgresql://{_POSTGRES_USER}:{_POSTGRES_PASSWORD}@{_POSTGRES_HOST}:{_POSTGRES_PORT}/{_POSTGRES_DB}",
echo=True,
)
conn = engine.connect()
Expand Down
18 changes: 11 additions & 7 deletions bot/helpers/queues.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
from bot import r
from typing import Tuple, Union
from typing import Dict, Tuple, Union


def add_to_queue(
def add_or_create_queue(
group_id: str,
from_user: str,
is_playing: bool,
date: str,
file: str,
type_of: str,
position=1,
) -> bool:
is_playing=False,
position=0,
) -> Union[Tuple, bool]:
"""Add or create queue in `group_id` field"""
values = [
{
Expand All @@ -27,11 +27,11 @@ def add_to_queue(
queue[group_id].append(values)
hset = r.hset("queues", group_id, queue[group_id])
if hset == 0:
return True
return True, position
return False
hset = r.hset("queues", group_id, values)
if hset == 1:
return True
return True, position
return False


Expand Down Expand Up @@ -103,6 +103,10 @@ def get_last_position_in_queue(group_id: str) -> Union[int, None]:
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")
Expand Down
4 changes: 2 additions & 2 deletions bot/plugins/commands/play_song.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,8 @@ async def _(client: Client, message: Message):
progress=progress,
progress_args=(client, message.chat, msg),
)
proto = f"https://t.me/c/{message.chat.id}/{message.reply_to_message.id}"
msg_mention = proto.replace("/c/-100", "/c/")
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 QUEUE:
# pos = add_to_queue(message.chat, name, url, ref, "audio")
await msg.delete()
Expand Down
114 changes: 90 additions & 24 deletions bot/plugins/commands/play_video.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,21 @@
import uuid
import logging
from asyncio import sleep
from pyrogram import filters, Client
from datetime import datetime
from pyrogram.types import Message
from bot.helpers.pkl import load_pkl
from bot.helpers.user_info import user_info
from bot import assistant, kreacher, on_call, VOICE_CHATS
from bot.helpers.progress import progress
from pyrogram import filters, Client
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup


from bot.helpers.progress import progress
from bot.helpers.yt import ytdl, ytsearch
from bot.helpers.user_info import user_info
from bot import assistant, kreacher, on_call, VOICE_CHATS
from bot.helpers.queues import (
clear_queue,
add_or_create_queue,
get_queues,
get_last_position_in_queue,
remove_queue,
)

fotoplay = "https://telegra.ph/file/b6402152be44d90836339.jpg"
Expand All @@ -26,7 +31,6 @@

@kreacher.on_message(filters.regex(pattern="^[!?/]play_video"))
async def _(client: Client, message: Message):
QUEUE = await load_pkl(queues, "rb", "dict")
data = await user_info(message.from_user)
try:
msg = await message.reply("\u23F3 **__Processing...__**")
Expand All @@ -42,13 +46,37 @@ 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():
position = get_last_position_in_queue(str(message.chat.id)) + 1
add_or_create_queue(
message.chat.id,
from_user=str(message.from_user.id),
date=str(datetime.now()),
file=query,
type_of="video_stream",
position=position,
)
return await msg.edit(
f"__Added to queue at {position} \n\n Title: [{name}]({query})\nDuration: {duration} Minutes\n Requested by:__ [{data['first_name']}]({data['mention']})",
reply_markup=InlineKeyboardMarkup(
[[InlineKeyboardButton("cʟᴏꜱᴇ", callback_data="cls")]]
),
)
elif message.chat.id not in get_queues():
add_or_create_queue(
message.chat.id,
from_user=str(message.from_user.id),
date=str(datetime.now()),
is_playing=True,
file=query,
type_of="video_stream",
)
await msg.edit("🔄 **__Starting live video stream...__**")
await sleep(2)
await on_call.start_video(
query,
enable_experimental_lip_sync=True,
repeat=False,
with_audio=True,
)
# await msg.delete()
await msg.edit(
Expand Down Expand Up @@ -80,24 +108,37 @@ async def _(client: Client, message: Message):
name = search[0]
ref = search[1]
duration = search[2]
# thumb = await gen_thumb(videoid)
fmt = "best[height<=?720][width<=?1280]"
hm, url = await ytdl(fmt, ref)
if hm == 0:
await msg.edit(f"`{url}`")
_, 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 YouTube video.\n\nTry searching with more specific title.__**",
)
if message.chat.id in get_queues():
position = get_last_position_in_queue(str(message.chat.id)) + 1
add_or_create_queue(
message.chat.id,
from_user=str(message.from_user.id),
date=str(datetime.now()),
file=url,
type_of="video_yt",
position=position,
)
if message.chat.id in QUEUE:
# pos = await add_to_queue(message.chat, name, url, ref, "audio")
return await msg.edit(
f"__Added to queue at \n\n Title: [{name}]({url})\nDuration: {duration} Minutes\n Requested by:__ [{data['first_name']}]({data['mention']})",
# file=thumb,
f"__Added to queue at {position} \n\n Title: [{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():
add_or_create_queue(
message.chat.id,
from_user=str(message.from_user.id),
date=str(datetime.now()),
is_playing=True,
file=url,
type_of="video_yt",
)
if VOICE_CHATS.get(message.chat.id) is None:
await msg.edit("🪄 **__Joining the voice chat...__**")
await on_call.start(message.chat.id)
Expand All @@ -107,9 +148,7 @@ async def _(client: Client, message: Message):
url,
enable_experimental_lip_sync=True,
repeat=False,
with_audio=True,
)
# await add_to_queue(message.chat, name, url, ref, "audio")
await msg.edit(
f"**__Started Streaming__**\n\n **Title**: [{name}]({url})\n **Duration:** {duration} **Minutes\n Requested by:** [{data['first_name']}]({data['mention']})",
# file=thumb,
Expand Down Expand Up @@ -138,12 +177,39 @@ async def _(client: Client, message: Message):
progress=progress,
progress_args=(client, message.chat, msg),
)
if message.chat.id in get_queues():
position = get_last_position_in_queue(str(message.chat.id)) + 1
add_or_create_queue(
message.chat.id,
from_user=str(message.from_user.id),
date=str(datetime.now()),
file=media,
type_of="video_media",
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']})",
reply_markup=InlineKeyboardMarkup(
[[InlineKeyboardButton("cʟᴏꜱᴇ", callback_data="cls")]]
),
)
if message.chat.id not in get_queues():
add_or_create_queue(
message.chat.id,
from_user=str(message.from_user.id),
date=str(datetime.now()),
is_playing=True,
file=media,
type_of="video_media",
)
if VOICE_CHATS.get(message.chat.id) is None:
await msg.edit("**__Joining the voice chat...__** \u23F3")
await on_call.start(message.chat.id)
VOICE_CHATS[message.chat.id] = on_call
await sleep(2)
await on_call.start_video(media, with_audio=True, repeat=False)
await on_call.start_video(
media, enable_experimental_lip_sync=True, repeat=False
)
# await msg.delete()
await msg.edit(
"**Started video streaming!**",
Expand All @@ -161,12 +227,12 @@ async def _(client: Client, message: Message):
],
),
)
except Exception as e:
logging.error(e)
except Exception as err:
logging.error(err)
await msg.edit(
f"**__Oops master, something wrong has happened.__** \n\n`Error: {e}`",
f"**__Oops master, something wrong has happened.__** \n\n`Error: {err}`",
)
if message.chat.id in VOICE_CHATS:
await VOICE_CHATS[message.chat.id].stop()
await clear_queue(message.chat)
remove_queue(str(message.chat.id))
VOICE_CHATS.pop(message.chat.id)
21 changes: 13 additions & 8 deletions bot/plugins/commands/speedtest.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import asyncio
import logging

# pylint: disable=import-self
from speedtest import Speedtest
from pyrogram import filters, Client
from pyrogram.types import Message
from pyrogram import filters, Client

from bot import kreacher


Expand All @@ -13,8 +17,9 @@ def testspeed():
test.upload()
test.results.share()
result = test.results.dict()
except Exception as e:
raise e
except Exception as err:
logging.error(err)
raise err
return result


Expand All @@ -25,11 +30,11 @@ async def _(client: Client, message: Message):
msg = await message.reply(
"""**__Kreacher is here to serve you.
Running Speedtest...__** \U0001F4F6"""
Running Speedtest...__** 📶"""
)

loop = asyncio.get_event_loop()
result = await loop.run_in_executor(None, testspeed)
ay = asyncio.get_event_loop()
result = await ay.run_in_executor(None, testspeed)

output = f"""**Speedtest Results**
Expand All @@ -45,7 +50,7 @@ async def _(client: Client, message: Message):
**__Ping__**: {result['ping']}"""
await kreacher.send_photo(chat.id, photo=result["share"], caption=output)
return await msg.delete()
except Exception as e:
except Exception as err:
return await msg.edit(
f"__Oops master, something wrong has happened.__ \n\n`Error: {e}`",
f"__Oops master, something wrong has happened.__ \n\n`Error: {err}`",
)
Loading

0 comments on commit 0463ba1

Please sign in to comment.