Skip to content

Commit

Permalink
Improvement to code ™️
Browse files Browse the repository at this point in the history
Improvements
  • Loading branch information
Ashik Muhammed authored Jan 1, 2022
2 parents 206afd0 + 30662d2 commit a384379
Show file tree
Hide file tree
Showing 3 changed files with 179 additions and 56 deletions.
8 changes: 8 additions & 0 deletions app.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@
"SUPPORT": {
"description": "Your support chat Username Without @",
"value": "NAZRIYASUPPORT"
},
"BOT_NAME": {
"description": "your Bot name ",
"value": "Song Downloader bot"
},
"BOT_USERNAME": {
"description": "Your bot Username Without @",
"value": "NazriyaSongBot"
}
},
"addons": [],
Expand Down
225 changes: 169 additions & 56 deletions bot.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
# This Repo was not fully owned by me. Some codes are scraped from respected DEVOLEPERS whom where mine friends.
# check Readme.md For More.

from __future__ import unicode_literals

import logging
logger = logging.getLogger(__name__)
import os, re, time, math, json, string, random, traceback, wget, asyncio, datetime, aiofiles, aiofiles.os, requests, youtube_dl, lyricsgenius
import os, re, time, math, json, string, random, traceback, wget, asyncio, datetime, aiofiles, aiofiles.os, requests, youtube_dl, lyricsgenius, wget
from config import Config
from random import choice
from pyrogram import Client, filters
from youtube_search import YoutubeSearch
from youtubesearchpython import VideosSearch
from yt_dlp import YoutubeDL
from database import Database
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message, InlineQuery, InlineQueryResultArticle, InputTextMessageContent
from pyrogram.errors import FloodWait, InputUserDeactivated, UserIsBlocked, PeerIdInvalid
Expand Down Expand Up @@ -154,78 +157,188 @@ async def send_msg(user_id, message):
return 500, f"{user_id} : {traceback.format_exc()}\n"


def time_to_seconds(time):
stringt = str(time)
return sum(int(x) * 60 ** i for i, x in enumerate(reversed(stringt.split(':'))))



@Bot.on_message(filters.command(['song']))
def a(client, message):
query = ''
for i in message.command[1:]:
query += ' ' + str(i)
print(query)
m = message.reply('`Searching... Please Wait...`')
ydl_opts = {"format": "bestaudio[ext=m4a]"}
@Bot.on_message(command(["song"]) & ~filters.edited)
def song(_, message):
query = " ".join(message.command[1:])
m = message.reply("🔎 Sᴇᴀʀᴄʜɪɴɢ Sᴏɴɢ ᴏɴ Yᴏᴜᴛᴜʙᴇ..! ./n **Upload Getting Slowed due to Heavy Traffic** [Learn More](https://en.m.wikipedia.org/wiki/Network_traffic)")
ydl_ops = {"format": "bestaudio[ext=m4a]"}
try:
results = []
count = 0
while len(results) == 0 and count < 6:
if count>0:
time.sleep(1)
results = YoutubeSearch(query, max_results=1).to_dict()
count += 1
# results = YoutubeSearch(query, max_results=1).to_dict()
try:
link = f"https://youtube.com{results[0]['url_suffix']}"
# print(results)
title = results[0]["title"]
thumbnail = results[0]["thumbnails"][0]
duration = results[0]["duration"]
views = results[0]["views"]

## UNCOMMENT THIS IF YOU WANT A LIMIT ON DURATION. CHANGE 1800 TO YOUR OWN PREFFERED DURATION AND EDIT THE MESSAGE (30 minutes cap) LIMIT IN SECONDS
# if time_to_seconds(duration) >= 7000: # duration limit
# m.edit("Exceeded 30mins cap")
# return

performer = f"[@NazriyaSongBot]"
thumb_name = f'thumb{message.message_id}.jpg'
thumb = requests.get(thumbnail, allow_redirects=True)
open(thumb_name, 'wb').write(thumb.content)

except Exception as e:
print(e)
m.edit('**No Results Found With This Data!**')
return
results = YoutubeSearch(query, max_results=1).to_dict()
link = f"https://youtube.com{results[0]['url_suffix']}"
title = results[0]["title"][:40]
thumbnail = results[0]["thumbnails"][0]
thumb_name = f"{title}.jpg"
thumb = requests.get(thumbnail, allow_redirects=True)
open(thumb_name, "wb").write(thumb.content)
duration = results[0]["duration"]

except Exception as e:
m.edit(
"**Enter The Song Name with /song command.!**"
)
m.edit("❌ Sᴏʀʀʏ I ᴄᴀɴ'ᴛ Fɪɴᴅ ʏᴏᴜʀ Rᴇǫᴜᴇsᴛᴇᴅ Sᴏɴɢ 🙁.\n\nTʀʏ Aɴᴏᴛʜᴇʀ Sᴏɴɢ Nᴀᴍᴇ ᴏʀ Cʜᴇᴄᴋ Sᴘᴇʟʟɪɴɢ..!\n\nIғ ʏᴏᴜ Fᴀᴄɪɴɢ sᴀᴍᴇ ɪssᴜᴇs ғᴏʀ sᴇᴄᴏɴᴅ Tɪᴍᴇ Rᴇᴘᴏʀᴛ ɪᴛ ᴏɴ support Group")
print(str(e))
return
m.edit("`AM...Uploading To TG now... Please Wait...`")
m.edit("📥 ∂σωиℓσα∂ιиg ѕσиg тσ ∂αтαвαѕє...ρℓєαѕє ωαιт..!")
try:
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
with yt_dlp.YoutubeDL(ydl_ops) as ydl:
info_dict = ydl.extract_info(link, download=False)
audio_file = ydl.prepare_filename(info_dict)
ydl.process_info(info_dict)
rep = f'❍📖 <b>Title:</b> <a href="{link}">{title}</a>\n❍⌚ <b>Duration:</b> <code>{duration}</code>\n❍📤 <b>Uploaded By:</b> <a href="https://t.me/NazriyaSongBot">NazriyaSongBot</a>'
secmul, dur, dur_arr = 1, 0, duration.split(':')
for i in range(len(dur_arr)-1, -1, -1):
dur += (int(dur_arr[i]) * secmul)
rep = f"🎵 Sᴏɴɢ Uᴘʟᴏᴀᴅᴇᴅ ғʀᴏᴍ YᴏᴜTᴜʙᴇ Mᴜsɪᴄ..!.\n\nPᴏᴡᴇʀᴇᴅ ʙʏ [{bat}](https://t.me/{bn})"
secmul, dur, dur_arr = 1, 0, duration.split(":")
for i in range(len(dur_arr) - 1, -1, -1):
dur += int(float(dur_arr[i])) * secmul
secmul *= 60
message.reply_audio(audio_file, caption=rep, parse_mode='HTML',quote=False, title=title, duration=dur, performer=performer, thumb=thumb_name)
m.edit("📤 υρℓσα∂ιиg fιℓє тσ тєℓєgяαм...")
message.reply_audio(
audio_file,
caption=rep,
thumb=thumb_name,
parse_mode="md",
title=title,
duration=dur,
)
m.delete()
except Exception as e:
m.edit('**Something Went Wrong Report This at @NAZRIYASUPPORT!!**')
m.edit("❌ Error Contact [support Group](https://t.me/{SUPPORT})")
print(e)

try:
os.remove(audio_file)
os.remove(thumb_name)
except Exception as e:
print(e)


def get_text(message: Message) -> [None, str]:
text_to_return = message.text
if message.text is None:
return None
if " " not in text_to_return:
return None

try:
return message.text.split(None, 1)[1]
except IndexError:
return None


async def progress(current, total, message, start, type_of_ps, file_name=None):
now = time.time()
diff = now - start
if round(diff % 10.00) == 0 or current == total:
percentage = current * 100 / total
speed = current / diff
elapsed_time = round(diff) * 1000
if elapsed_time == 0:
return
time_to_completion = round((total - current) / speed) * 1000
estimated_total_time = elapsed_time + time_to_completion
progress_str = "{0}{1} {2}%\n".format(
"".join("💿" for _ in range(math.floor(percentage / 10))),
"".join("📀" for _ in range(10 - math.floor(percentage / 10))),
round(percentage, 2),
)

tmp = progress_str + "{0} of {1}\nETA: {2}".format(
humanbytes(current), humanbytes(total), time_formatter(estimated_total_time)
)
if file_name:
try:
await message.edit(
"{}\n**File Name:** `{}`\n{}".format(type_of_ps, file_name, tmp)
)
except FloodWait as e:
await asyncio.sleep(e.x)
except MessageNotModified:
pass
else:
try:
await message.edit("{}\n{}".format(type_of_ps, tmp))
except FloodWait as e:
await asyncio.sleep(e.x)
except MessageNotModified:
pass


def get_user(message: Message, text: str) -> [int, str, None]:
asplit = None if text is None else text.split(" ", 1)
user_s = None
reason_ = None
if message.reply_to_message:
user_s = message.reply_to_message.from_user.id
reason_ = text or None
elif asplit is None:
return None, None
elif len(asplit[0]) > 0:
user_s = int(asplit[0]) if asplit[0].isdigit() else asplit[0]
if len(asplit) == 2:
reason_ = asplit[1]
return user_s, reason_


def get_readable_time(seconds: int) -> str:
count = 0
ping_time = ""
time_list = []
time_suffix_list = ["s", "m", "h", "days"]

while count < 4:
count += 1
remainder, result = divmod(seconds, 60) if count < 3 else divmod(seconds, 24)
if seconds == 0 and remainder == 0:
break
time_list.append(int(result))
seconds = int(remainder)

for x in range(len(time_list)):
time_list[x] = str(time_list[x]) + time_suffix_list[x]
if len(time_list) == 4:
ping_time += time_list.pop() + ", "

time_list.reverse()
ping_time += ":".join(time_list)

return ping_time


def time_formatter(milliseconds: int) -> str:
seconds, milliseconds = divmod(int(milliseconds), 1000)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
tmp = (
((str(days) + " day(s), ") if days else "")
+ ((str(hours) + " hour(s), ") if hours else "")
+ ((str(minutes) + " minute(s), ") if minutes else "")
+ ((str(seconds) + " second(s), ") if seconds else "")
+ ((str(milliseconds) + " millisecond(s), ") if milliseconds else "")
)
return tmp[:-2]


def get_file_extension_from_url(url):
url_path = urlparse(url).path
basename = os.path.basename(url_path)
return basename.split(".")[-1]


async def download_song(url):
song_name = f"{randint(6969, 6999)}.mp3"
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
if resp.status == 200:
f = await aiofiles.open(song_name, mode="wb")
await f.write(await resp.read())
await f.close()
return song_name


def time_to_seconds(times):
stringt = str(times)
return sum(int(x) * 60 ** i for i, x in enumerate(reversed(stringt.split(":"))))






@Bot.on_inline_query()
Expand Down
2 changes: 2 additions & 0 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ class Config(object):
DATABASE = os.environ.get("DB_URI")
OWNER_ID = set(int(x) for x in os.environ.get("OWNER_ID", "1961162381").split())
SUPPORT = os.environ.get("SUPPORT")
BOT_NAME = os.environ.get("bat")
BOT_USERNAME = os.environ.get("bn")

0 comments on commit a384379

Please sign in to comment.