Add search music on Spotify and add log

This commit is contained in:
stef-devs 2022-06-20 22:20:31 +02:00
parent 1abccd1661
commit 94466c4fba
4 changed files with 147 additions and 59 deletions

7
.gitignore vendored
View File

@ -1,3 +1,8 @@
ffmpeg.exe ffmpeg.exe
.env .env
test.py test.py
.cache
music_cache
nuvola.py
debug.log
nuvola.txt

194
index.py
View File

@ -18,6 +18,9 @@ import urllib.request
import urllib.parse import urllib.parse
import logging import logging
import deepl import deepl
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
from youtube_search import YoutubeSearch
from dotenv import load_dotenv from dotenv import load_dotenv
from yt_dlp import YoutubeDL from yt_dlp import YoutubeDL
from platform import system from platform import system
@ -29,69 +32,129 @@ from telebot import types, telebot
from pytube import YouTube from pytube import YouTube
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from gc import callbacks from gc import callbacks
import logging
import sys
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler("debug.log"),
logging.StreamHandler(sys.stdout)
]
)
load_dotenv() load_dotenv()
API_TOKEN = os.getenv('BOT_TOKEN') API_TOKEN = os.getenv('BOT_TOKEN')
bot = telebot.TeleBot(API_TOKEN) bot = telebot.TeleBot(API_TOKEN)
print("Il bot si è avviato con successo!") logging.info("Il bot si è avviato con successo!")
#Command /start #Command /start
@bot.message_handler(commands=['start']) @bot.message_handler(commands=['start'])
def send_welcome(message): def send_welcome(message):
chat_id = message.chat.id chat_id = message.chat.id
print("Triggered command START.") logging.info("Triggered command START.")
bot.send_photo(chat_id, photo='https://i.imgur.com/6YPJBze.png') bot.send_photo(chat_id, photo='https://i.imgur.com/6YPJBze.png')
messageText = "✋ Benvenuto su <b>RetniNet!</b>\n\n<b>RetniNet</b> è un bot privato per <b>automatizzare</b> e <b>semplificare</b> cose che facciamo quotidianamente. \n\n👨‍💻 Creato & sviluppato da @Stef58_Official" messageText = "✋ Benvenuto su <b>RetniNet!</b>\n\n<b>RetniNet</b> è un bot privato per <b>automatizzare</b> e <b>semplificare</b> cose che facciamo quotidianamente. \n\n👨‍💻 Creato & sviluppato da @Stef58_Official"
bot.send_message(chat_id,messageText, parse_mode="HTML") bot.send_message(chat_id, messageText, parse_mode="HTML")
#Command /music #Command /music
@bot.message_handler(commands=['music']) @bot.message_handler(commands=['music'])
def select_music(pm): def select_music(pm):
print("Triggered command MUSIC.") logging.info("Triggered command MUSIC.")
sent_msg = bot.send_message(pm.chat.id, "Inserisci il link della canzone:") sent_msg = bot.send_message(pm.chat.id, "Inserisci il link della canzone:")
bot.register_next_step_handler(sent_msg, music_step) bot.register_next_step_handler(sent_msg, music_step)
def music_step(pm): def music_step(pm):
if pm.text.startswith('https://www.youtube.com/') or pm.text.startswith('https://youtu.be/'): if pm.text.startswith('https://www.youtube.com/') or pm.text.startswith('https://youtu.be/'):
ytdl_opts = { ytdl_opts = {
'format': 'bestaudio/best', 'format': 'bestaudio/best',
'outtmpl': '%(title)s.%(ext)s', 'outtmpl': 'music_cache/%(title)s.%(ext)s',
'postprocessors': [{ 'postprocessors': [{
'key': 'FFmpegExtractAudio', 'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3', 'preferredcodec': 'mp3',
'preferredquality': '192', 'preferredquality': '192',
}], }],
} }
elif pm.text.startswith('https://open.spotify.com/track/'):
ytdl_opts = {
'format': 'bestaudio/best',
'outtmpl': 'music_cache/%(title)s.%(ext)s',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
with YoutubeDL(ytdl_opts) as ydl: with YoutubeDL(ytdl_opts) as ydl:
url = pm.text message = pm.text
sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id=os.getenv('SPOTIFY_ID'), client_secret=os.getenv('SPOTIFY_SECRET')))
track = sp.track(message)
name = track["name"]
artist = track["artists"][0]["name"]
results = YoutubeSearch(artist + " - " + name, max_results=1).to_json()
get_link = json.loads(results)
link = get_link['videos'][0]['url_suffix']
print_link = 'https://youtube.com' + link
url = print_link
info = ydl.extract_info(url, download=False) info = ydl.extract_info(url, download=False)
name = info.get('title') name = info.get('title')
id = info.get('id') id = info.get('id')
ydl.download([id]) ydl.download([id])
send_message = "🎶 La canzone <b>" + name + "</b> è stata scaricata con successo!" send_message = "🎶 La canzone <b>" + name + \
"</b> è stata scaricata con successo!"
bot.send_message(pm.chat.id, send_message, parse_mode="HTML") bot.send_message(pm.chat.id, send_message, parse_mode="HTML")
bot.send_audio(pm.chat.id, audio=open(name + '.mp3', 'rb')) bot.send_audio(pm.chat.id, audio=open("music_cache/" + name + '.mp3', 'rb'))
os.remove("music_cache/" + name + '.mp3')
logging.info("\"" + name + "\" è stato scaricato ed eliminato con successo!")
elif pm.text.startswith('https://youtube.com/') or pm.text.startswith('youtube.com/'):
bot.send_message(
pm.chat.id, "🚫 <b>Errore</b>\n\n<b>Il link</b> inserito non è valido!")
else: else:
bot.send_message(pm.chat.id, "🚫 Devi inserire un <b>link</b> valido!") try:
with YoutubeDL(ytdl_opts) as ydl:
url = pm.text
info = ydl.extract_info(url, download=False)
name = info.get('title')
id = info.get('id')
ydl.download([id])
send_message = "🎶 La canzone <b>" + name + \
"</b> è stata scaricata con successo!"
bot.send_message(pm.chat.id, send_message, parse_mode="HTML")
bot.send_audio(pm.chat.id, audio=open("music_cache/" + name + '.mp3', 'rb'))
os.remove("music_cache/" + name + '.mp3')
except:
chat = pm.chat.id
send_msg = "🚫 Errore!\n\n<b>Errore:</b> <i>Impossibile scaricare la canzone</i>"
bot.send_message(chat, send_msg, parse_mode="HTML")
else:
chat = pm.chat.id
bot.send_message(chat, pm.chat.id,
"🚫 Devi inserire un <b>link</b> valido!")
#Command /meteo #Command /meteo
@bot.message_handler(commands=['meteo']) @bot.message_handler(commands=['meteo'])
def meteo(pm): def meteo(pm):
print("Triggered command METEO.") logging.info("Triggered command METEO.")
sent_msg = bot.send_message(pm.chat.id, "🏙️ Inserisci la città:") sent_msg = bot.send_message(pm.chat.id, "🏙️ Inserisci la città:")
bot.register_next_step_handler(sent_msg, meteo_step) bot.register_next_step_handler(sent_msg, meteo_step)
def meteo_step(message): def meteo_step(message):
translator = deepl.Translator(os.getenv('DEEPL_TOKEN')) translator = deepl.Translator(os.getenv('DEEPL_TOKEN'))
result = translator.translate_text('hi', target_lang='IT') result = translator.translate_text('hi', target_lang='IT')
translated_text = result.text translated_text = result.text
city = message.text city = message.text
token_weather = os.environ.get('WEATHER_TOKEN') token_weather = os.environ.get('WEATHER_TOKEN')
response = requests.get("https://api.openweathermap.org/data/2.5/weather?q="+city+",it&APPID="+token_weather).json() response = requests.get("https://api.openweathermap.org/data/2.5/weather?q="+city+",it&APPID="+token_weather).json()
weather = response['weather'][0]['main'] # weather = response['weather'][0]['main']
temp = response['main']['temp'] temp = response['main']['temp']
temp = temp - 273.15 temp = temp - 273.15
weather_translate = translator.translate_text(weather, target_lang='IT') weather_translate = translator.translate_text(weather, target_lang='IT')
@ -100,13 +163,15 @@ def meteo_step(message):
bot.send_message(message.chat.id, "🌧️ La condizione è " + result_weather) bot.send_message(message.chat.id, "🌧️ La condizione è " + result_weather)
#Command /stats #Command /stats
@bot.message_handler(commands=['stats']) @bot.message_handler(commands=['stats'])
def uptime(message): def uptime(message):
print("Triggered command STATS.") print("Triggered command STATS.")
cpuUsage = psutil.cpu_percent(interval=1) cpuUsage = psutil.cpu_percent(interval=1)
ramTotal = int(psutil.virtual_memory().total/(1024*1024)) #GB ramTotal = int(psutil.virtual_memory().total/(1024*1024)) # GB
ramUsage = int(psutil.virtual_memory().used/(1024*1024)) #GB ramUsage = int(psutil.virtual_memory().used/(1024*1024)) # GB
ramFree = int(psutil.virtual_memory().free/(1024*1024)) #GB ramFree = int(psutil.virtual_memory().free/(1024*1024)) # GB
ramUsagePercent = psutil.virtual_memory().percent ramUsagePercent = psutil.virtual_memory().percent
msg = ''' msg = '''
CPU & RAM Info CPU & RAM Info
@ -116,84 +181,99 @@ RAM
Totale = {} MB Totale = {} MB
Usato = {} MB Usato = {} MB
Libero = {} MB Libero = {} MB
In uso = {} %\n'''.format(cpuUsage,ramTotal,ramUsage,ramFree,ramUsagePercent) In uso = {} %\n'''.format(cpuUsage, ramTotal, ramUsage, ramFree, ramUsagePercent)
bot.send_message(message.chat.id,msg) bot.send_message(message.chat.id, msg)
#Command /pastebin #Command /pastebin
@bot.message_handler(commands=['pastebin']) @bot.message_handler(commands=['pastebin'])
def pastebin(message): def pastebin(message):
print("Triggered command PASTEBIN.") logging.info("Triggered command PASTEBIN.")
sent_msg = bot.send_message(message.chat.id, "📋 Inserisci il testo:") sent_msg = bot.send_message(message.chat.id, "📋 Inserisci il testo:")
bot.register_next_step_handler(sent_msg, pastebin_step) bot.register_next_step_handler(sent_msg, pastebin_step)
def pastebin_step(message): def pastebin_step(message):
chat = message.chat.id chat = message.chat.id
text = message.text text = message.text
site = 'https://pastebin.com/api/api_post.php' site = 'https://pastebin.com/api/api_post.php'
dev_key = os.environ.get('PASTEBIN_TOKEN') dev_key = os.environ.get('PASTEBIN_TOKEN')
code = text code = text
our_data = urllib.parse.urlencode({"api_dev_key": dev_key, "api_option": "paste", "api_paste_code": code}) our_data = urllib.parse.urlencode(
our_data = our_data.encode() {"api_dev_key": dev_key, "api_option": "paste", "api_paste_code": code})
our_data = our_data.encode()
resp = urllib.request.urlopen(site, our_data) resp = urllib.request.urlopen(site, our_data)
resp = resp.read() resp = resp.read()
send_msg = "📋 Il tuo <b>codice</b> è stato inviato con successo!\n\n<b>Link:</b> " + str(resp) send_msg = "📋 Il tuo <b>codice</b> è stato inviato con successo!\n\n<b>Link:</b> " + \
bot.send_message(chat,send_msg, parse_mode="HTML") str(resp)
bot.send_message(chat, send_msg, parse_mode="HTML")
#Command /epicgames #Command /epicgames
@bot.message_handler(commands=['epicgames']) @bot.message_handler(commands=['epicgames'])
def epicgames(message): def epicgames(message):
text = message.text text = message.text
bot.send_message(message.chat.id, "🎮 Vuoi vedere il gioco disponibile al momento o quello futuro? (disponibile/futuro)") bot.send_message(
message.chat.id, "🎮 Vuoi vedere il gioco disponibile al momento o quello futuro? (disponibile/futuro)")
bot.register_next_step_handler(message, epicgames_step) bot.register_next_step_handler(message, epicgames_step)
def epicgames_step(message): def epicgames_step(message):
text = message.text text = message.text
if text == 'disponibile': if text == 'disponibile' or text == 'Disponibile':
print("Triggered command EPICGAMES DISPONIBILE.") logging.info("Triggered command EPICGAMES DISPONIBILE.")
#URL API # URL API
url = "https://api.plenusbot.xyz/epic_games?country=IT" url = "https://api.plenusbot.xyz/epic_games?country=IT"
response = requests.get(url).json() response = requests.get(url).json()
#Title of current games # Title of current games
current_games = response['currentGames'][0]['title'] current_games = response['currentGames'][0]['title']
#Image current games # Image current games
image_currentgames = response['currentGames'][0]['keyImages'][0]['url'] image_currentgames = response['currentGames'][0]['keyImages'][0]['url']
#Description current games # Description current games
current_games_description = response['currentGames'][0]['description'] current_games_description = response['currentGames'][0]['description']
#Token for translate # Token for translate
translator = deepl.Translator(os.getenv('DEEPL_TOKEN')) translator = deepl.Translator(os.getenv('DEEPL_TOKEN'))
#Translate description current games # Translate description current games
description_translate = translator.translate_text(current_games_description, target_lang='IT') description_translate = translator.translate_text(
current_games_description, target_lang='IT')
result_description = description_translate.text result_description = description_translate.text
send_img = bot.send_photo(message.chat.id, image_currentgames) send_img = bot.send_photo(message.chat.id, image_currentgames)
sent_msg = bot.send_message(message.chat.id, "🎮 Il gioco gratis di oggi è " + current_games + "\n\n" + result_description) sent_msg = bot.send_message(
message.chat.id, "🎮 Il gioco gratis di oggi è " + current_games + "\n\n" + result_description)
else: else:
print("Triggered command EPICGAMES FUTURO.") logging.info("Triggered command EPICGAMES FUTURO.")
#URL API # URL API
url = "https://api.plenusbot.xyz/epic_games?country=IT" url = "https://api.plenusbot.xyz/epic_games?country=IT"
response = requests.get(url).json() response = requests.get(url).json()
#Title of future games # Title of future games
future_games1 = response['nextGames'][0]['title'] future_games1 = response['nextGames'][0]['title']
#Image future games # Image future games
image_futuregames1 = response['nextGames'][0]['keyImages'][0]['url'] image_futuregames1 = response['nextGames'][0]['keyImages'][0]['url']
#Description future games # Description future games
future_games_description1 = response['nextGames'][0]['description'] future_games_description1 = response['nextGames'][0]['description']
#Token for translate # Token for translate
translator = deepl.Translator(os.getenv('DEEPL_TOKEN')) translator = deepl.Translator(os.getenv('DEEPL_TOKEN'))
description_translate1 = translator.translate_text(future_games_description1, target_lang='IT') description_translate1 = translator.translate_text(
future_games_description1, target_lang='IT')
result_description1 = description_translate1.text result_description1 = description_translate1.text
send_img = bot.send_photo(message.chat.id, image_futuregames1) send_img = bot.send_photo(message.chat.id, image_futuregames1)
sent_msg = bot.send_message(message.chat.id, "🎮 Il gioco futuro è " + future_games1 + "\n\n" + result_description1) sent_msg = bot.send_message(
#Title of future games message.chat.id, "🎮 Il gioco futuro è " + future_games1 + "\n\n" + result_description1)
# Title of future games
future_games2 = response['nextGames'][1]['title'] future_games2 = response['nextGames'][1]['title']
#Image future games # Image future games
image_futuregames2 = response['nextGames'][1]['keyImages'][0]['url'] image_futuregames2 = response['nextGames'][1]['keyImages'][0]['url']
#Description future games # Description future games
future_games_description2 = response['nextGames'][1]['description'] future_games_description2 = response['nextGames'][1]['description']
#Traslate description future games # Traslate description future games
description_translate2 = translator.translate_text(future_games_description2, target_lang='IT') description_translate2 = translator.translate_text(
future_games_description2, target_lang='IT')
result_description2 = description_translate2.text result_description2 = description_translate2.text
send_img = bot.send_photo(message.chat.id, image_futuregames2) send_img = bot.send_photo(message.chat.id, image_futuregames2)
sent_msg = bot.send_message(message.chat.id, "🎮 Il gioco futuro è " + future_games2 + "\n\n" + result_description2) sent_msg = bot.send_message(
message.chat.id, "🎮 Il gioco futuro è " + future_games2 + "\n\n" + result_description2)
bot.polling()
bot.polling()

View File

View File

@ -1,4 +1,3 @@
bs4 == 0.0.1 bs4 == 0.0.1
deepl == 1.8.0 deepl == 1.8.0
@ -21,10 +20,14 @@ pytube == 12.1.0
requests == 2.25.1 requests == 2.25.1
spotipy == 2.20.0
telebot == 0.0.4 telebot == 0.0.4
tqdm == 4.64.0 tqdm == 4.64.0
youtube_search == 2.1.0
yt_dlp == 2022.5.18 yt_dlp == 2022.5.18
pytelegrambotapi == 4.5.1 pytelegrambotapi == 4.5.1