Skip to content

Commit

Permalink
fix error [ #45 ] : fix youtube uploading
Browse files Browse the repository at this point in the history
  • Loading branch information
kalanakt committed Aug 24, 2022
1 parent 92b1b8a commit 9cbc7e0
Show file tree
Hide file tree
Showing 4 changed files with 214 additions and 2 deletions.
1 change: 0 additions & 1 deletion Uploader/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ async def button(bot, update):
)
elif "close" in update.data:
await update.message.delete(True)

elif "|" in update.data:
await youtube_dl_call_back(bot, update)
elif "=" in update.data:
Expand Down
21 changes: 20 additions & 1 deletion Uploader/echo.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
import asyncio
import logging

from opencc import OpenCC

from pyrogram.types import Thumbnail
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
Expand All @@ -44,6 +46,8 @@
logger = logging.getLogger(__name__)
logging.getLogger("pyrogram").setLevel(logging.WARNING)

s2tw = OpenCC('s2tw.json').convert


@Client.on_message(filters.private & filters.regex(pattern=".*http.*"))
async def echo(bot, update):
Expand All @@ -53,7 +57,22 @@ async def echo(bot, update):
youtube_dl_password = None
file_name = None

print(url)
if "youtu.be" in url:
return await update.reply_text(
"**Choose Download type**",
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
"Audio 🎵", callback_data="ytdl_audio"),
InlineKeyboardButton(
"Video 🎬", callback_data="ytdl_video")
]
]
),
quote=True
)

if "|" in url:
url_parts = url.split("|")
if len(url_parts) == 2:
Expand Down
61 changes: 61 additions & 0 deletions Uploader/functions/help_ytdl.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# MIT License

# Copyright (c) 2022 Hash Minner

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE

import os
import time
import requests
import logging

from urllib.parse import urlparse

logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


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


def get_resolution(info_dict):
if {"width", "height"} <= info_dict.keys():
width = int(info_dict['width'])
height = int(info_dict['height'])
# https://support.google.com/youtube/answer/6375112
elif info_dict['height'] == 1080:
width = 1920
height = 1080
elif info_dict['height'] == 720:
width = 1280
height = 720
elif info_dict['height'] == 480:
width = 854
height = 480
elif info_dict['height'] == 360:
width = 640
height = 360
elif info_dict['height'] == 240:
width = 426
height = 240
return (width, height)
133 changes: 133 additions & 0 deletions Uploader/youtube.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# MIT License

# Copyright (c) 2022 Hash Minner

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE

import os
from urllib.parse import urlparse
import wget
import asyncio

from pyrogram import Client, filters, enums
from pyrogram.types import Message
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardMarkup, KeyboardButton

from functions.help_ytdl import get_file_extension_from_url, get_resolution

from opencc import OpenCC
from youtube_dl import YoutubeDL

YTDL_REGEX = (r"^((?:https?:)?\/\/)")
s2tw = OpenCC('s2tw.json').convert


@Client.on_callback_query(filters.regex("^ytdl_audio$"))
async def callback_query_ytdl_audio(_, callback_query):
try:
url = callback_query.message.reply_to_message.text
ydl_opts = {
'format': 'bestaudio',
'outtmpl': '%(title)s - %(extractor)s-%(id)s.%(ext)s',
'writethumbnail': True
}
with YoutubeDL(ydl_opts) as ydl:
message = callback_query.message
await message.reply_chat_action(enums.ChatAction.TYPING)
info_dict = ydl.extract_info(url, download=False)
# download
await callback_query.edit_message_text("**Downloading audio...**")
ydl.process_info(info_dict)
# upload
audio_file = ydl.prepare_filename(info_dict)
task = asyncio.create_task(send_audio(message, info_dict,
audio_file))
while not task.done():
await asyncio.sleep(3)
await message.reply_chat_action(enums.ChatAction.UPLOAD_DOCUMENT)
await message.reply_chat_action(enums.ChatAction.CANCEL)
await message.delete()
except Exception as e:
await message.reply_text(e)
await callback_query.message.reply_to_message.delete()
await callback_query.message.delete()

async def send_audio(message: Message, info_dict, audio_file):
basename = audio_file.rsplit(".", 1)[-2]
if info_dict['ext'] == 'webm':
audio_file_weba = f"{basename}.weba"
os.rename(audio_file, audio_file_weba)
audio_file = audio_file_weba
thumbnail_url = info_dict['thumbnail']
thumbnail_file = f"{basename}.{get_file_extension_from_url(thumbnail_url)}"
webpage_url = info_dict['webpage_url']
title = s2tw(info_dict['title'])
caption = f'<b><a href=\"{webpage_url}\">{title}</a></b>'
duration = int(float(info_dict['duration']))
performer = s2tw(info_dict['uploader'])
await message.reply_audio(audio_file, caption=caption, duration=duration, performer=performer, title=title, parse_mode=enums.ParseMode.HTML, thumb=thumbnail_file)

os.remove(audio_file)
os.remove(thumbnail_file)


@Client.on_callback_query(filters.regex("^ytdl_video$"))
async def callback_query_ytdl_video(_, callback_query):
try:
# url = callback_query.message.text
url = callback_query.message.reply_to_message.text
ydl_opts = {
'format': 'best[ext=mp4]',
'outtmpl': '%(title)s - %(extractor)s-%(id)s.%(ext)s',
'writethumbnail': True
}
with YoutubeDL(ydl_opts) as ydl:
message = callback_query.message
await message.reply_chat_action(enums.ChatAction.TYPING)
info_dict = ydl.extract_info(url, download=False)
# download
await callback_query.edit_message_text("**Downloading video...**")
ydl.process_info(info_dict)
# upload
video_file = ydl.prepare_filename(info_dict)
task = asyncio.create_task(send_video(message, info_dict,
video_file))
while not task.done():
await asyncio.sleep(3)
await message.reply_chat_action(enums.ChatAction.UPLOAD_DOCUMENT)
await message.reply_chat_action(enums.ChatAction.CANCEL)
await message.delete()
except Exception as e:
await message.reply_text(e)
await callback_query.message.reply_to_message.delete()
await callback_query.message.delete()

async def send_video(message: Message, info_dict, video_file):
basename = video_file.rsplit(".", 1)[-2]
thumbnail_url = info_dict['thumbnail']
thumbnail_file = f"{basename}.{get_file_extension_from_url(thumbnail_url)}"
webpage_url = info_dict['webpage_url']
title = s2tw(info_dict['title'])
caption = f'<b><a href=\"{webpage_url}\">{title}</a></b>'
duration = int(float(info_dict['duration']))
width, height = get_resolution(info_dict)
await message.reply_video(video_file, caption=caption, duration=duration, width=width, height=height, parse_mode=enums.ParseMode.HTML, thumb=thumbnail_file)

os.remove(video_file)
os.remove(thumbnail_file)

0 comments on commit 9cbc7e0

Please sign in to comment.