Skip to content
This repository has been archived by the owner on Oct 16, 2018. It is now read-only.

Commit

Permalink
Added "Audio Quality" options
Browse files Browse the repository at this point in the history
In /preferences, now you can set the audio quality
  • Loading branch information
Javinator9889 committed Apr 26, 2017
1 parent 2b4a743 commit b04da91
Show file tree
Hide file tree
Showing 4 changed files with 116 additions and 11 deletions.
14 changes: 9 additions & 5 deletions TeleBotSongDownloader.py
Expand Up @@ -44,7 +44,9 @@ def key_l2(bot, update):

@run_async
def key_pr(bot, update):
keyboard = [[InlineKeyboardButton("Idioma 🗣", callback_data='lang'),InlineKeyboardButton("Sistema operativo ⚙", callback_data='os')]]
keyboard = [[InlineKeyboardButton("Idioma 🗣", callback_data='lang'),
InlineKeyboardButton("Sistema operativo ⚙", callback_data='os')],
[InlineKeyboardButton("Calidad de audio 🎶", callback_data='ad')]]

reply_markup2 = InlineKeyboardMarkup(keyboard)

Expand All @@ -53,7 +55,9 @@ def key_pr(bot, update):

@run_async
def key_pren(bot, update):
keyboard = [[InlineKeyboardButton("Language 🗣", callback_data='langen'),InlineKeyboardButton("Operative system ⚙", callback_data='osen')]]
keyboard = [[InlineKeyboardButton("Language 🗣", callback_data='langen'),
InlineKeyboardButton("Operative system ⚙", callback_data='osen')],
[InlineKeyboardButton("Audio quality 🎶", callback_data='aden')]]

reply_markup2 = InlineKeyboardMarkup(keyboard)

Expand Down Expand Up @@ -273,7 +277,7 @@ def changes(bot,update): # '/changelog' function
lang(bot,update)
elif 'es' in read_database(chat_id):
bot.sendMessage(chat_id=update.message.chat_id,
text="*Versión actual:* _2.3.10.26.04_\n\n- *SOLUCIÓN DEFINITIVA A LAS DESCARGAS*\n\n- *TRADUCCIÓN COMPLETA A INGLÉS*: usa el comando /preferences para definir tu idioma.\n\n- Nueva duración máxima: *1 hora*.\
text="*Versión actual:* _2.3.15.26.04_\n\n- *ELIGE LA CALIDAD DE AUDIO* de tus canciones en /preferences\n\n- *SOLUCIÓN DEFINITIVA A LAS DESCARGAS*\n\n- *TRADUCCIÓN COMPLETA A INGLÉS*: usa el comando /preferences para definir tu idioma.\n\n- Nueva duración máxima: *1 hora*.\
\n- *METADATOS en todas las descargas*\n- Optimizada la velocidad *de descarga*.\n- Mejorados los *tiempos de espera*.\n- Optimización de los _servicios_ (debido a la nueva longitud máxima admitida).\
\n- Tiempo de espera automático *si la congestión del servidor está por encima del 80%*.\n- Añadido *multiproceso* para atender hasta 50 peticiones simultáneas (en un futuro se _ampliará_).\
\n- Solucionado un error por el cual *no se descargaban los vídeos*.\n- Nuevo mensaje cuando *un vídeo largo no puede ser enviado*.\
Expand All @@ -283,7 +287,7 @@ def changes(bot,update): # '/changelog' function
parse_mode=telegram.ParseMode.MARKDOWN)
elif 'en' in read_database(chat_id):
bot.sendMessage(chat_id=update.message.chat_id,
text="*Current version:* _2.3.10.26.04_\n\n- *DEFINITIVE SOLUTION FOR DOWNLOADS*\n\n- *COMPLETE ENGLISH TRANSLATION*: use /preferences to define your language.\n\n- New maximum duration: *1 hour*.\
text="*Current version:* _2.3.15.26.04_\n\n- *CHOOSE AUDIO QUALITY* of downloaded songs in /preferences\n\n- *DEFINITIVE SOLUTION FOR DOWNLOADS*\n\n- *COMPLETE ENGLISH TRANSLATION*: use /preferences to define your language.\n\n- New maximum duration: *1 hour*.\
\n- *METADATA in all downloads*\n- Optimized *download speed*.\n- Improved *waiting times*.\n- _Service_ optimizations (because of the new video lenght).\n- Automatic wait time *if server congestion is above 80%*.\
\n- Added *multi-process* to handle up to 50 concurrent requests (in a future wil be extended)\n- Fixed an error by which *the videos were not downloaded*.\
\n- New message when *a long video can not be sent*.\n- *Server update*: simultaneous downloads without errors or failures.\
Expand Down Expand Up @@ -434,7 +438,7 @@ def voice(bot,update): # Function for handling

# Prints basic bot information as it is working and the current version
print("\nBot en funcionamiento")
print("\nVersión: 2.3.10.26.04")
print("\nVersión: 2.3.15.26.04")
try:
while 1:
time.sleep(10) # Prevents the bot from disconnecting
Expand Down
69 changes: 67 additions & 2 deletions botones.py
Expand Up @@ -9,7 +9,7 @@
from pafy_test import key_f, key_fen # From file "pafy_test.py"
from sender import sender
from curl import descarga # From file "curl.py"
from database import write_database,read_database,write_os,read_os
from database import write_database,read_database,write_os,read_os,read_audio,set_audio

# This function is for distributing the "callback queries" between different options. Also it's for basic ReplyKeyboardMarkup

Expand Down Expand Up @@ -46,6 +46,28 @@ def key_osen(bot, update,chat_id):
bot.sendMessage(text='What is your operative system? _(only smartphones; this option is irrelevant for PC users)_',
parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=reply_markup2,chat_id=chat_id)

def key_ad(bot,update,chat_id):
keyboard = [[InlineKeyboardButton("Baja Calidad 💾", callback_data='LQ'),
InlineKeyboardButton("Calidad Media 💿", callback_data='MQ')],
[InlineKeyboardButton("Alta Calidad 💽", callback_data='HQ')]]

reply_markup2 = InlineKeyboardMarkup(keyboard)

bot.sendMessage(chat_id=chat_id,text="*ELIJA UNA DE LAS SIGUIENTES OPCIONES DE CALIDAD DE AUDIO*:\n\n- *Baja Calidad* - _@120 kbps_\n- *Calidad Media* - _@256 kbps_\n- *Alta Calidad* - _@320 kbps_\
\n\nLa calidad elegida _repercute directamente_ en los *tiempos de descarga* y el *tamaño del archivo* (cuanto mayor sea la calidad mayor será el tiempo necesario y el tamaño)",
parse_mode=telegram.ParseMode.MARKDOWN,reply_markup = reply_markup2)

def key_aden(bot,update,chat_id):
keyboard = [[InlineKeyboardButton("Low Quality 💾", callback_data='LQ'),
InlineKeyboardButton("Medium Quality 💿", callback_data='MQ')],
[InlineKeyboardButton("High Quality 💽", callback_data='HQ')]]

reply_markup2 = InlineKeyboardMarkup(keyboard)

bot.sendMessage(chat_id = chat_id,text="*CHOOSE ONE OF THE FOLLOWING OPTIONS OF QUALITY:*\n\n- *Low Quality* - _@120 kbps_\n- *Medium Quality* - _@256 kbps_\n- *High Quality* - _@320 kbps_\
\n\nThe chosen quality _has effect directly_ with *download time* and *file size* (when higher quality more time and size)",
parse_mode=telegram.ParseMode.MARKDOWN,reply_markup = reply_markup2)

def botones(bot,update,chat_id,message_id,value,user): # 'value' is obtained from "def buttons" in 'TeleBotSongDownloader.py'
title_file="title_{}.txt".format(chat_id)
video_file = "url_{}.txt".format(chat_id)
Expand Down Expand Up @@ -331,4 +353,47 @@ def botones(bot,update,chat_id,message_id,value,user): # 'value' is obtained fr
chat_id=chat_id,
message_id=message_id)
value="iOS"
write_os(chat_id,user,value)
write_os(chat_id,user,value)
elif value == "ad":
bot.editMessageText(text="Actualizando preferencias de calidad de audio...",
chat_id=chat_id,
message_id=message_id)
key_ad(bot,update,chat_id)
elif value == "aden":
bot.editMessageText(text="Updating audio quality preferences...",
chat_id=chat_id,
message_id=message_id)
key_aden(bot,update,chat_id)
elif value == "LQ":
if 'es' in read_database(chat_id):
bot.editMessageText(text="Calidad de audio guardada correctamente. Usa /preferences para cambiarla en cualquier momento",
chat_id=chat_id,
message_id=message_id)
elif 'en' in read_database(chat_id):
bot.editMessageText(text="Audio quality preferences saved correctly. Use /preferences for changing it whenever you want",
chat_id=chat_id,
message_id=message_id)
value = "120k"
set_audio(chat_id,value)
elif value == "MQ":
if 'es' in read_database(chat_id):
bot.editMessageText(text="Calidad de audio guardada correctamente. Usa /preferences para cambiarla en cualquier momento",
chat_id=chat_id,
message_id=message_id)
elif 'en' in read_database(chat_id):
bot.editMessageText(text="Audio quality preferences saved correctly. Use /preferences for changing it whenever you want",
chat_id=chat_id,
message_id=message_id)
value = "256k"
set_audio(chat_id,value)
elif value == "HQ":
if 'es' in read_database(chat_id):
bot.editMessageText(text="Calidad de audio guardada correctamente. Usa /preferences para cambiarla en cualquier momento",
chat_id=chat_id,
message_id=message_id)
elif 'en' in read_database(chat_id):
bot.editMessageText(text="Audio quality preferences saved correctly. Use /preferences for changing it whenever you want",
chat_id=chat_id,
message_id=message_id)
value = "320k"
set_audio(chat_id,value)
24 changes: 24 additions & 0 deletions database.py
Expand Up @@ -111,4 +111,28 @@ def write_os(chat_id,name,os):
c.execute('SET character_set_connection=utf8;')
c.execute("""UPDATE Usuario SET OS = %s WHERE chat_id = %s""", (os, chat_id))
db.commit()
db.close()

def read_audio(chat_id):
db = pymysql.connect("YOUR_HOST (localhost,127.0.0.1, ...)","YOUR_USER","YOUR_PASSWORD","DATABASE_TABLE_NAME",charset='utf8')
c = db.cursor()
0
c.execute('SET NAMES utf8;')
c.execute('SET CHARACTER SET utf8;')
c.execute('SET character_set_connection=utf8;')
c.execute("""SELECT audio_quality FROM Usuario WHERE chat_id = %s""",(chat_id))
aux = c.fetchone()
value = aux[0]
db.close()
return value

def set_audio(chat_id,value):
db = pymysql.connect("YOUR_HOST (localhost,127.0.0.1, ...)","YOUR_USER","YOUR_PASSWORD","DATABASE_TABLE_NAME",charset='utf8')
c = db.cursor()
0
c.execute('SET NAMES utf8;')
c.execute('SET CHARACTER SET utf8;')
c.execute('SET character_set_connection=utf8;')
c.execute("""UPDATE Usuario SET audio_quality = %s WHERE chat_id = %s""",(value,chat_id))
db.commit()
db.close()
20 changes: 16 additions & 4 deletions pafy_test.py
Expand Up @@ -3,7 +3,7 @@
import os
import os.path as path
import threading
from database import read_database,write_database,cont_database,read_os
from database import read_database,write_database,cont_database,read_os,read_audio
from telegram.ext.dispatcher import run_async
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
Expand Down Expand Up @@ -73,13 +73,25 @@ def video_down(bot,update,chat_id,user):
titulo.close()
idioma = read_database(chat_id)
cont_database(chat_id)
ad_quality = read_audio(chat_id)
if ad_quality == None:
ad_quality = "256k"
if ad_quality == "120k":
calidad = "baja"
calidad_en = "low"
elif ad_quality == "256k":
calidad = "media"
calidad_en = "medium"
elif ad_quality == "320k":
calidad = "alta"
calidad_en = "high"
time.sleep(2)
cov_name = "cover_{}.jpg".format(chat_id)
if 'es' in idioma:
bot.sendMessage(chat_id,text="Estamos descargando la canción. \n\nComo este bot está pensado para descargar música, buscaremos el *título, artista, etc* _independientemente de lo que hayas enviado_\n\n\nPor favor, espere...\n\n*NOTA: si observa que la velocidad de descarga es muy lenta, acceda a* /errors *para obtener asistencia e información*",
bot.sendMessage(chat_id,text="Estamos descargando la canción en *calidad "+calidad+"* (cámbialo en /preferences).\n\nComo este bot está pensado para descargar música, buscaremos el *título, artista, etc* _independientemente de lo que hayas enviado_\n\n\nPor favor, espere...\n\n*NOTA: si observa que la velocidad de descarga es muy lenta, acceda a* /errors *para obtener asistencia e información*",
parse_mode=telegram.ParseMode.MARKDOWN)
elif 'en' in idioma:
bot.sendMessage(chat_id,text="We are downloading the song. \n\nAs this is a bot for downloading music, we will search for *title, artist, etc* _regardless of what you've sent_\n\n\nPlease wait ...\n\n*INFO: If you notice that the download speed is very slow, access* /errors *for assistance and information*",
bot.sendMessage(chat_id,text="We are downloading the song in *"+calidad_en+" quality* (change it in /preferences).\n\nAs this is a bot for downloading music, we will search for *title, artist, etc* _regardless of what you've sent_\n\n\nPlease wait ...\n\n*INFO: If you notice that the download speed is very slow, access* /errors *for assistance and information*",
parse_mode=telegram.ParseMode.MARKDOWN)
api = ask_for_credentials()
song = api.search(name,max_results=1)
Expand Down Expand Up @@ -119,7 +131,7 @@ def video_down(bot,update,chat_id,user):
bot.sendMessage(chat_id,"We have your song ready 🙂\nAs it is a bit bigger than the others, it will take us a bit longer to send it to you _(but you don't have to worry about anything 😉)_",
parse_mode=telegram.ParseMode.MARKDOWN)
print("\n\tConvirtiendo a mp3...")
AudioSegment.from_file(full_name_w,"webm").export(full_name_m,format="mp3",bitrate="256k",cover=picture,tags={'artist': artist, 'album': album, 'title': titulo_met})
AudioSegment.from_file(full_name_w,"webm").export(full_name_m,format="mp3",bitrate=ad_quality,cover=picture,tags={'artist': artist, 'album': album, 'title': titulo_met})
if path.exists(full_name_w):
os.remove(full_name_w)
if path.exists(cov_name):
Expand Down

0 comments on commit b04da91

Please sign in to comment.