Skip to content

Commit

Permalink
feat: youtube support
Browse files Browse the repository at this point in the history
  • Loading branch information
HolgerHuo committed Oct 3, 2022
1 parent a9ec2c4 commit 493ed3c
Show file tree
Hide file tree
Showing 4 changed files with 82 additions and 5 deletions.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
# Telegram Netease Bot - Telegram 网易云音乐 Bot

Note: As the initial version of this bot is of low quality and is hard to extent horizontally, future development on this version may be dropped. A rewrite of this program is expected to be born some time around Jan. 2023.
---

![GitHub last commit](https://img.shields.io/github/last-commit/holgerhuo/telegram-netease-bot)![GitHub release (latest by date)](https://img.shields.io/github/v/release/holgerhuo/telegram-netease-bot)![GitHub](https://img.shields.io/github/license/holgerhuo/telegram-netease-bot)![GitHub all releases](https://img.shields.io/github/downloads/holgerhuo/telegram-netease-bot/total)![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/holgerhuo/telegram-netease-bot)

A python telegram bot enabling you to send Netease Cloud Music in chats
A python telegram bot enabling you to send **Netease Cloud Music** and **YouTube music (extracted from videos)** in chats

## ✨ Features

Expand Down
49 changes: 49 additions & 0 deletions providers/youtube.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import yt_dlp
from requests import get
import logging, os
import helper

logger = logging.getLogger(__name__)

def get_song_info(keyword):
def search(arg):
def less_than_10mins(info, *, incomplete):
duration = info.get('duration')
if duration and duration > 600:
return 'The video is too long'

def generate_abspath(song):
song['file'] = os.path.abspath(song['requested_downloads'][0]['filepath'])
iterable_obj = iter(song['thumbnails'])

while True:
try:
item = next(iterable_obj)
if 'filepath' in item:
song['thumb'] = os.path.abspath(item['filepath'])
except StopIteration:
break

return song

tmp_dir = helper.tmp_dir+'youtube'+'/'
if not os.path.exists(tmp_dir):
os.makedirs(tmp_dir)

YDL_OPTIONS = {'logger': logger, 'noprogress': True, 'quiet': True, 'format': 'bestaudio', 'match_filter': less_than_10mins, 'keepvideo': True , 'writethumbnail': True, 'paths': {'home': tmp_dir},'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'm4a'}], 'overwrites': False, 'outtmpl': '%(id)s.%(ext)s'}
with yt_dlp.YoutubeDL(YDL_OPTIONS) as ydl:
try:
get(arg)
except:
results = ydl.sanitize_info(ydl.extract_info(f"ytsearch:{arg}", download=True))
result = results['entries'][0] if results['entries'] and results['entries'][0] else None
if result:
return generate_abspath(result)
else:
return None
else:
result = ydl.sanitize_info(ydl.extract_info(arg, download=True))
if result['duration'] > 600:
return None
return generate_abspath(result)
return search(keyword)
Binary file modified requirements.txt
Binary file not shown.
33 changes: 29 additions & 4 deletions run.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import helper
import utils.cache_handler as cache
from utils.image_handler import gen_thumb
import providers.youtube as youtube
import telebot
from telebot import util

logger = logging.getLogger('TNB')
logging.basicConfig(level=getattr(logging, helper.log_level.upper(), 10),
Expand All @@ -14,8 +14,7 @@
if 'tgapi' in helper.config['general']:
from telebot import apihelper
apihelper.API_URL = helper.config['general']['tgapi']
bot = telebot.TeleBot(helper.token, threaded=True)
bot.worker_pool = util.ThreadPool(num_threads=helper.threads)
bot = telebot.TeleBot(helper.token, threaded=True, num_threads=helper.threads)

# Construct Song Class
class Song(object):
Expand All @@ -36,7 +35,7 @@ def __init__(self, keyword, id=None, title=None, artist=None, album=None, alt=No
@bot.message_handler(commands=['help', 'start'])
def send_welcome(message):
bot.send_chat_action(message.chat.id, 'typing')
bot.reply_to(message, """欢迎使用669点歌台!\n\n发送\n<b>点歌</b> 歌曲名称\n进行网易云搜索!\n\nPowered by <b><a href='https://github.com/HolgerHuo/telegram-netease-bot/'>TelegramNeteaseBot</a></b>\n<a href='https://dragon-fly.club/'>DragonFly Club</a>""",parse_mode='HTML')
bot.reply_to(message, """欢迎使用669点歌台!\n\n发送\n<b>点歌/dg/wy</b> 歌曲名称\n进行网易云搜索\n<b>yt/油管</b> 歌曲名称\n进行YouTube搜索\n\nPowered by <b><a href='https://github.com/HolgerHuo/telegram-netease-bot/'>TelegramNeteaseBot</a></b>\n<a href='https://dragon-fly.club/'>DragonFly Club</a>""",parse_mode='HTML')

# Handle 点歌
@bot.message_handler(regexp='^(?:点歌|dg|wy) .*')
Expand Down Expand Up @@ -100,5 +99,31 @@ def send_song(message, reply, song):
bot.delete_message(chat_id=message.chat.id, message_id=reply.id)
logger.info(song.title+' - '+song.artist+" has been sent to "+str(message.chat.id))

@bot.message_handler(regexp='^(?:yt|油管|视频) .*')
def handle_youtube(message):
reply = bot.reply_to(message, text="正在搜索\n<b>"+message.text[3:]+"</b>...", parse_mode='HTML')
try:
song = youtube.get_song_info(message.text[3:])
except Exception: # Catch search error
bot.edit_message_text(chat_id=message.chat.id, message_id=reply.id, text="搜索\n<b>"+message.text[3:]+"</b>\n失败!请重试!", parse_mode='HTML')
else:
if not song: # Return song not found error
bot.edit_message_text(chat_id=message.chat.id, message_id=reply.id, text="<b>"+message.text[3:]+"</b>\n无法被找到或超过10分钟", parse_mode='HTML')
else:
if 'track' in song:
song['title'] = song['track']
name = "「<b>"+song['title']+"</b>」\nby "+song['artist'] if 'artist' in song else "「<b>"+song['title']+"</b>」"
if not 'artist' in song:
song['artist'] = None
bot.edit_message_text(chat_id=message.chat.id, message_id=reply.id, text="正在发送\n"+name, parse_mode='HTML')
bot.send_chat_action(message.chat.id, "upload_audio")
with open(song['file'], 'rb') as a:
thumb = open(song['thumb'], 'rb') if 'thumb' in song else None
bot.send_audio(chat_id=message.chat.id, reply_to_message_id=message.message_id, audio=a, caption=name, parse_mode='HTML', title=song['title'], performer=song['artist'], thumb=thumb)
if thumb:
thumb.close()
bot.delete_message(chat_id=message.chat.id, message_id=reply.id)
logger.info(song['title']+" has been sent to "+str(message.chat.id))

# Start polling
bot.infinity_polling()

0 comments on commit 493ed3c

Please sign in to comment.