def photo(bot, update):  # Function for handling photo-messages
    user = update.message.from_user['first_name']
    chat_id = update.message.chat_id
    name = unidecode(user)
    print("\tRecibida imagen")
    print("Usuario + ID: ", name, chat_id)
    if read_database(chat_id) == None:
        bot.sendMessage(
            chat_id,
            text=
            "Antes de continuar, debes actualizar tus preferencias de idioma\n\nBefore you continue, you have to update your language preferences"
        )
        lang(bot, update)
    elif 'es' in read_database(chat_id):
        bot.sendMessage(
            chat_id,
            text=
            "*¡¡NO VEO!!* *¡¡ME HE QUEDADO CIEGO!!*\nAh, no... Que no tengo ojos 😅",
            parse_mode=telegram.ParseMode.MARKDOWN)
    elif 'en' in read_database(chat_id):
        bot.sendMessage(
            chat_id,
            text=
            "*I CAN'T SEE ANYTHING!!* *I'M BLIND!!*\nAh, no... I have no eyes 😅",
            parse_mode=telegram.ParseMode.MARKDOWN)
def start(bot, update):  # '/start' handler function
    print("\tEjecutando '/start'...")
    user = update.message.from_user['first_name']  # Get username and
    chat_id = update.message.chat_id  # chat_id for basic logging information
    name = unidecode(
        user
    )  # 'username' is always decoded to "utf-8" for avoiding problems with special characters (á,é,í,ó,ú,ñ,😄 (emojis),etc)
    print("Usuario + ID: ", name, chat_id)
    if read_database(
            chat_id
    ) == None:  # 'read_database' function reads language preferences for choosing a language or other
        bot.sendMessage(
            chat_id,
            text=
            "Antes de continuar, debes actualizar tus preferencias de idioma\n\nBefore you continue, you have to update your language preferences"
        )
        lang(bot, update)
    elif 'es' in read_database(chat_id):  # 'es' because of "español"
        bot.sendMessage(
            chat_id,
            text="Hola " + name +
            ", bienvenido 😄 \n\n*Para descargar una canción puedes:*\nEnviarme el *NOMBRE Y ARTISTA 🎤*\n_LA URL DE LA CANCIÓN 🎶_\nUtiliza /vid _PARA BUSCAR TUS CANCIONES_ 🔍\n\nPara descubir _más sobre el bot, utiliza_ /help",
            parse_mode=telegram.ParseMode.MARKDOWN)
    elif 'en' in read_database(chat_id):  # 'en' because of "English"
        bot.sendMessage(
            chat_id,
            text="Hello " + name +
            ", welcome 😄 \n\n*For downloading a song you can:*\nSend me the *NAME AND ARTIST 🎤*\n_THE SONG URL 🎶_\nUse /vid _FOR LOOKING FOR SONGS_ 🔍\n\nFor discovering _more about the bot, use_ /help",
            parse_mode=telegram.ParseMode.MARKDOWN)
def location(bot, update):  # Function for handling location-messages
    user = update.message.from_user['first_name']
    chat_id = update.message.chat_id
    name = unidecode(user)
    print("\tRecibida ubicación")
    print("Usuario + ID: ", name, chat_id)
    if read_database(chat_id) == None:
        bot.sendMessage(
            chat_id,
            text=
            "Antes de continuar, debes actualizar tus preferencias de idioma\n\nBefore you continue, you have to update your language preferences"
        )
        lang(bot, update)
    elif 'es' in read_database(chat_id):
        bot.sendMessage(
            chat_id,
            text=
            "ERROR 404\n\n¡¡NOS HAN DESCUBIERTO!! 🛰 INICIANDO PROTOCOLO DE AUTODESTRUCCIÓN...",
            parse_mode=telegram.ParseMode.MARKDOWN)
    elif 'en' in read_database(chat_id):
        bot.sendMessage(
            chat_id,
            text=
            "ERROR 404\n\nWE HAVE BEEN DISCOVERED!! 🛰 STARTING SELF-DESTRUCTION PROTOCOL...",
            parse_mode=telegram.ParseMode.MARKDOWN)
def privacy(bot, update):  # '/privacy' function
    print("\tEjecutando '/privacy'...")
    user = update.message.from_user['first_name']
    chat_id = update.message.chat_id
    name = unidecode(user)
    print("Usuario + ID: ", name, chat_id)
    if read_database(chat_id) == None:
        bot.sendMessage(
            chat_id,
            text=
            "Antes de continuar, debes actualizar tus preferencias de idioma\n\nBefore you continue, you have to update your language preferences"
        )
        lang(bot, update)
    elif 'es' in read_database(chat_id):
        bot.sendMessage(
            chat_id,
            text=
            "@dwnmp3Bot únicamente guarda y conserva tu *nombre público* 🗣 y el *id del chat* 🆔 (requerido para enviar los archivos necesarios) junto con tus *preferencias de idioma* y de *sistema operativo* (para que no tengas que escribirlo cada vez). Finalmente, con fines méramente estadísticos, llevamos una cuenta con *la cantidad de descargas realizadas* ⤵\n\nGracias por confiar en nosotros 😃",
            parse_mode=telegram.ParseMode.MARKDOWN)
    elif 'en' in read_database(chat_id):
        bot.sendMessage(
            chat_id,
            text=
            "@dwnmp3Bot is only saving your *public name* 🗣 and *chat id* 🆔 (requiered for sending files) with your *language preferences* and *operating system* ones (in order to not to make you writing them each time). Finally, with stadistical purposes, we count *how many downloads you have done* ⤵\n\nThanks for trusting us 😃",
            parse_mode=telegram.ParseMode.MARKDOWN)
def video(bot, update):  # Function for handling video-messages
    user = update.message.from_user['first_name']
    chat_id = update.message.chat_id
    name = unidecode(user)
    print("\tRecibido vídeo")
    print("Usuario + ID: ", name, chat_id)
    if read_database(chat_id) == None:
        bot.sendMessage(
            chat_id,
            text=
            "Antes de continuar, debes actualizar tus preferencias de idioma\n\nBefore you continue, you have to update your language preferences"
        )
        lang(bot, update)
    elif 'es' in read_database(chat_id):
        bot.sendMessage(
            chat_id,
            text=
            "Gracias pero yo soy más de cine mudo escocés subtitulado en ruso 😶. Prueba a descargar algo",
            parse_mode=telegram.ParseMode.MARKDOWN)
    elif 'en' in read_database(chat_id):
        bot.sendMessage(
            chat_id,
            text=
            "Thank you so much but I prefer Scottish silent movies with Russian subtitles 😶. Try to download something",
            parse_mode=telegram.ParseMode.MARKDOWN)
def nothing(
    bot, update
):  # 'nothing' function for unexpected messages (documents, contacts, etc)
    user = update.message.from_user['first_name']
    chat_id = update.message.chat_id
    name = unidecode(user)
    print("Usuario + ID: ", name, chat_id)
    if read_database(chat_id) == None:
        bot.sendMessage(
            chat_id,
            text=
            "Antes de continuar, debes actualizar tus preferencias de idioma\n\nBefore you continue, you have to update your language preferences"
        )
        lang(bot, update)
    elif 'es' in read_database(chat_id):
        bot.sendMessage(
            chat_id=update.message.chat_id,
            text=
            "No puedo hacer nada con lo que me has enviado 🤔\n\nEscribe   /help   para obtener ayuda"
        )
    elif 'en' in read_database(chat_id):
        bot.sendMessage(
            chat_id,
            text=
            "I can not do anything with what you have sent me 🤔\n\nType  /help   to get help"
        )
def help(bot, update):  # '/help' handler function
    print("\tEjecutando '/help'...")
    user = update.message.from_user['first_name']
    chat_id = update.message.chat_id
    name = unidecode(user)
    print("Usuario + ID: ", name, chat_id)
    if read_database(
            chat_id
    ) == None:  # Always check language preferences for avoiding message errors (no lang defined)
        bot.sendMessage(
            chat_id,
            text=
            "Antes de continuar, debes actualizar tus preferencias de idioma\n\nBefore you continue, you have to update your language preferences"
        )
        lang(bot, update)
    elif 'es' in read_database(chat_id):
        bot.sendMessage(
            chat_id,
            text=
            "A continuación tienes la lista de comandos:\n\n - /vid, para aprender a *utilizar el bot* @vid para buscar vídeos 🔍\
      \n\n - /privacy, donde podrás conocer *las políticas de privacidad* 👮\n\n - /preferences, para cambiar *tus preferencias de idioma 🗣* o *sistema operativo ⚙* cuando quieras\
      \n\n - /errors, para *recibir asistencia* 🛠\n\n\
 - /changelog, orientado más a los _desarrolladores_ 🤓 pero abierto a todo el mundo: la *lista de cambios y mejoras* que se incluyen con cada actualización del bot y enlace al proyecto de GitHub\n\n\n",
            parse_mode=telegram.ParseMode.MARKDOWN)
    elif 'en' in read_database(chat_id):
        bot.sendMessage(
            chat_id,
            text=
            "Now you have command list:\n\n - /vid, for learning *how to use the bot* @vid for searching videos 🔍\
      \n\n - /privacy, where you can see *privacy policies* 👮\n\n - /preferences, for changing *your language preferences 🗣* or *operative system ones ⚙* whenever you want\
      \n\n - /errors, for *getting help* 🛠\n\n\
 - /changelog, designed for _developers_ 🤓 but accessible for everyone: list of *changes and improvements* included in each bot update and link to GitHub project\n\n\n",
            parse_mode=telegram.ParseMode.MARKDOWN)
 def test_regex(self):
     """checks that inventory file is ingested correctly"""
     raw_exhibitions = database.read_database(
         '../test_database/data_inventory.txt')
     exhibitions = [
         ('romans',
          '    233(\n        de  roemischerhelm.mp3  roemischerhelm.tex\n        en  romanhelmet.mp3     romanhelmet.tex\n    )\n    10(\n        de  becher_rom.mp3      becher_rom.tex\n        en  cup_rome.mp3        cup_rome.tex\n    )\n'
          ),
         ('middle_ages',
          '    15(\n        de  mittelalterlicher_schaedel.mp3  mittelalterlicher_schaedel.tex\n        en  skull_medieval.mp3              skull_medieval.tex\n    )\n    11(\n        de  morgenstern.mp3         morgenstern.tex\n        en  primitive_weapon.mp3    primitive_weapon.tex\n    )\n'
          )
     ]
     self.assertEqual(exhibitions,
                      database.exhibition_regex.findall(raw_exhibitions))
     objects = \
         [('233',
           'de  roemischerhelm.mp3  roemischerhelm.tex\n        en  romanhelmet.mp3     romanhelmet.tex\n    '),
          ('10',
           'de  becher_rom.mp3      becher_rom.tex\n        en  cup_rome.mp3        cup_rome.tex\n    ')]
     self.assertEqual(objects,
                      database.object_regex.findall(exhibitions[0][1]))
     languages = [('de', 'roemischerhelm.mp3', 'roemischerhelm.tex'),
                  ('en', 'romanhelmet.mp3', 'romanhelmet.tex')]
     self.assertEqual(languages,
                      database.language_regex.findall(objects[0][1]))
    def test_parse_database(self):
        """checks that the correct dictionary tree is generated"""
        inventory = \
            {
                'romans': {
                    '233': {
                        'de': ['roemischerhelm.mp3', 'roemischerhelm.tex'],
                        'en': ['romanhelmet.mp3', 'romanhelmet.tex']
                    },
                    '10': {
                        'de': ['becher_rom.mp3', 'becher_rom.tex'],
                        'en': ['cup_rome.mp3', 'cup_rome.tex']
                    },

                },
                'middle_ages': {
                    '15': {
                        'de': ['mittelalterlicher_schaedel.mp3', 'mittelalterlicher_schaedel.tex'],
                        'en': ['skull_medieval.mp3', 'skull_medieval.tex']
                    },
                    '11': {
                        'de': ['morgenstern.mp3', 'morgenstern.tex'],
                        'en': ['primitive_weapon.mp3', 'primitive_weapon.tex']
                    }
                }
            }
        self.assertEqual(
            inventory,
            database.parse_inventory(
                database.read_database('../test_database/data_inventory.txt')))
Beispiel #10
0
def get_database(filename=DATABASE_FILENAME):
    global db_loaded

    if not db_loaded:
        db_loaded = database.read_database(filename)

    return db_loaded
Beispiel #11
0
 def test_package_maker(self):
     """checks if dictionary tree contains correct values form test inventory file"""
     compiled_inventory = ['233', '10']
     compiled_package = ['romanhelmet.mp3', 'cup_rome.mp3']
     self.assertEqual((compiled_inventory, compiled_package),
                      database.compile_inventory_package(
                          ['romans'], ['en'],
                          database.parse_inventory(
                              database.read_database(
                                  '../test_database/data_inventory.txt'))))
     compiled_inventory = ['233', '10']
     compiled_package = [
         'roemischerhelm.mp3', 'romanhelmet.mp3', 'becher_rom.mp3',
         'cup_rome.mp3'
     ]
     self.assertEqual((compiled_inventory, compiled_package),
                      database.compile_inventory_package(
                          ['romans'], ['de', 'en'],
                          database.parse_inventory(
                              database.read_database(
                                  '../test_database/data_inventory.txt'))))
     compiled_inventory = ['233', '10', '15', '11']
     compiled_package = [
         'roemischerhelm.mp3', 'romanhelmet.mp3', 'becher_rom.mp3',
         'cup_rome.mp3', 'mittelalterlicher_schaedel.mp3',
         'skull_medieval.mp3', 'morgenstern.mp3', 'primitive_weapon.mp3'
     ]
     self.assertEqual((compiled_inventory, compiled_package),
                      database.compile_inventory_package(
                          ['romans', 'middle_ages'], ['de', 'en'],
                          database.parse_inventory(
                              database.read_database(
                                  '../test_database/data_inventory.txt'))))
     self.assertEqual((compiled_inventory, compiled_package),
                      database.compile_inventory_package(
                          ['romans', 'middle_ages'], ['de', 'en'],
                          database.parse_inventory(
                              database.read_database(
                                  '../test_database/data_inventory.txt'))))
     self.assertEqual(
         (compiled_inventory, compiled_package),
         database.compile_inventory_package(
             database.read_preset('../test_database/test_preset.txt')[1],
             database.read_preset('../test_database/test_preset.txt')[0],
             database.parse_inventory(
                 database.read_database(
                     '../test_database/data_inventory.txt'))))
def errors(bot, update):  # '/errors' function
    print("\tEjecutando '/errors'...")
    chat_id = update.message.chat_id
    user = update.message.from_user['first_name']
    name = unidecode(user)
    print("Usuario + ID: ", name, chat_id)
    if read_database(chat_id) == None:
        bot.sendMessage(
            chat_id,
            text=
            "Antes de continuar, debes actualizar tus preferencias de idioma\n\nBefore you continue, you have to update your language preferences"
        )
        lang(bot, update)
    elif 'es' in read_database(chat_id):
        mensaje_bot(bot, update, chat_id)
    elif 'en' in read_database(chat_id):
        message_bot(bot, update, chat_id)
Beispiel #13
0
 def test_compiled_package(self):
     total_inventory = database.parse_inventory(
         database.read_database('../test_database/data_inventory.txt'))
     preset = database.read_preset('../test_database/test_preset.txt')
     compiled_inventory, compiled_package = database.compile_inventory_package(
         preset[1], preset[0], total_inventory)
     database.compile_package(compiled_package,
                              '../test_database',
                              '../test_database/test_package',
                              audio_format='.ad4')
Beispiel #14
0
def choose_structures( howmany, filename="database", prefix=None ):
  from random import randint
  from pylada import crystal, enumeration
  import database

  N = 0
  for structure in database.read_database(filename, withperms=True): N  += 1

  which = set([])
  while len(which) != howmany: which.add(randint(0,N-1))
  which = sorted(list(which))
  for n, structure in enumerate(database.read_database(filename, withperms=True)):
    if n != which[0]: continue

    which.pop(0)

    dirname = create_structure_dir(structure, prefix)
    structure.name += ", database %s, structure %i" % (filename, n)
    crystal.print_poscar(structure, ("Al", "Mg", "O"), dirname )

    if len(which) == 0: break
def lang(
    bot, update
):  # '/lang' handler function (disabled - it's only used when called by another function)
    print("\tEjecutando '/lang'...")
    user = update.message.from_user['first_name']
    chat_id = update.message.chat_id
    name = unidecode(user)
    print("Usuario + ID: ", name, chat_id)
    if read_database(chat_id) == None:
        key_l(bot, update)
    else:
        key_l2(bot, update)
def changes(bot, update):  # '/changelog' function
    user = update.message.from_user['first_name']
    chat_id = update.message.chat_id
    name = unidecode(user)
    print("\tEjecutando '/changelog'")
    print("Usuario + ID: ", name, chat_id)
    github = "https://github.com/Javinator9889/telegram-yt_mp3-bot"
    if read_database(chat_id) == None:
        bot.sendMessage(
            chat_id,
            text=
            "Antes de continuar, debes actualizar tus preferencias de idioma\n\nBefore you continue, you have to update your language preferences"
        )
        lang(bot, update)
    elif 'es' in read_database(chat_id):
        bot.sendMessage(
            chat_id=update.message.chat_id,
            text=
            "*Versión actual:* _2.3.21.07.05_\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 y media*.\
      \n- *METADATOS en todas las descargas*\n- EL BOT AHORA ESTÁ ACTIVO 24/7\n- Las canciones *se almacenan* para un envío más rápido\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*.\
      \n- *Actualización del servidor*: descargas simultáneas sin errores ni fallos\
      \n- *Diálogos en la función* /errors: ahora, al escribir el comando /errors, interactúas con el bot para ofrecer la mejor asistencia.\
      \n- *Nuevo algoritmo de búsqueda*\n- Solucionado *un bug* por el cual _las descargas se bloqueaban_ y no comenzaban. Disculpad las molestias.\n- *Diálogos* optimizados\n- *Correcciones menores de errores*.\n\n*ACCEDE AL PROYECTO EN GitHub* [justo aquí]("
            + github + ")",
            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.21.07.05_\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 and a half*.\
      \n- *METADATA in all downloads*\n- BOT IS NOW ON 24/7\n- Songs are *stored* for a faster sending\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.\
      \n- *Dialogs in the function* /errors: now, when writing the /errors command, you will be able to interact with the bot to offer you the best support.\
      \n- Solved *a bug* which _locked downloads_ and made them not starting. Sorry for the inconvenience\n- *Optimized* dialogs\n- *New search algorithm*\n- *Minur bug fixes*\n\n*ACCESS TO GitHub PROJECT* [right here]("
            + github + ")",
            parse_mode=telegram.ParseMode.MARKDOWN)
Beispiel #17
0
 def test_compiled_eeprom(self):
     """tests if eeprom ticket contains correct values"""
     total_inventory = database.parse_inventory(
         database.read_database('../test_database/data_inventory.txt'))
     language = 'de'
     payed_exhibitions = ['romans']
     expected_eeprom = (0, [233, 10, 15, 11], [2, 2, 0, 0])
     compiled_inventory, compiled_package = database.compile_inventory_package(
         ['romans', 'middle_ages'], ['de', 'en'], total_inventory)
     compiled_test_eeprom = database.compile_eeprom(payed_exhibitions, 'de',
                                                    compiled_inventory,
                                                    total_inventory)
     self.assertEqual(expected_eeprom, compiled_test_eeprom)
def pref(
    bot, update
):  # '/preferences' handler function, replacing the old '/lang' function with additional features
    print("\tEjecutando '/preferences'...")
    user = update.message.from_user['first_name']
    chat_id = update.message.chat_id
    name = unidecode(user)
    print("Usuario + ID: ", name, chat_id)
    if read_database(chat_id) == None:
        bot.sendMessage(
            chat_id,
            text=
            "Antes de continuar, debes actualizar tus preferencias de idioma\n\nBefore you continue, you have to update your language preferences"
        )
        lang(bot, update)
    elif 'es' in read_database(chat_id):
        key_pr(
            bot, update
        )  # Different keyboards redirects to "language" function or "operative system" function
    elif 'en' in read_database(chat_id):
        key_pren(
            bot, update
        )  # If a function name is like "key_pr" + en then it means "English" function (key_prEN)
def song(bot, update):  # Function for handling audio-messages
    user = update.message.from_user['first_name']
    chat_id = update.message.chat_id
    name = unidecode(user)
    print("\tRecibida canción")
    print("Usuario + ID: ", name, chat_id)
    if read_database(chat_id) == None:
        bot.sendMessage(
            chat_id,
            text=
            "Antes de continuar, debes actualizar tus preferencias de idioma\n\nBefore you continue, you have to update your language preferences"
        )
        lang(bot, update)
    elif 'es' in read_database(chat_id):
        bot.sendMessage(
            chat_id,
            text="Tienes un gusto horrible... Mejor te envío yo algo 😜",
            parse_mode=telegram.ParseMode.MARKDOWN)
    elif 'en' in read_database(chat_id):
        bot.sendMessage(
            chat_id,
            text=
            "You have a horrible taste in music... I better send you something 😜",
            parse_mode=telegram.ParseMode.MARKDOWN)
def voice(bot, update):  # Function for handling voice-messages
    user = update.message.from_user['first_name']
    chat_id = update.message.chat_id
    name = unidecode(user)
    print("\tRecibido audio")
    print("Usuario + ID: ", name, chat_id)
    if read_database(chat_id) == None:
        bot.sendMessage(
            chat_id,
            text=
            "Antes de continuar, debes actualizar tus preferencias de idioma\n\nBefore you continue, you have to update your language preferences"
        )
        lang(bot, update)
    elif 'es' in read_database(chat_id):
        bot.sendMessage(
            chat_id,
            text=
            "Una voz preciosa, pero particularmente prefiero a _Lady GaGa_ 💃",
            parse_mode=telegram.ParseMode.MARKDOWN)
    elif 'en' in read_database(chat_id):
        bot.sendMessage(
            chat_id,
            text="What a beautiful voice, but I prefer _Lady GaGa_ 💃",
            parse_mode=telegram.ParseMode.MARKDOWN)
Beispiel #21
0
def load_eeprom(inventory_file, preset_file, exhibitions, language):
    """writes a ticket to eeprom
    :param inventory_file: file specifying which audio files belong to which exhibiton and language
    :param preset_file: file specifying which exhibitions are to be written to sd
    :param exhibitions: paid exhibitions
    :param language: language chosen by visitor"""
    presets = database.read_preset(preset_file)
    complete_inventory = database.parse_inventory(
        database.read_database(inventory_file))
    compiled_inventory, compiled_package = database.compile_inventory_package(
        presets[1], presets[0], complete_inventory)
    eeprom_conents = database.compile_eeprom(exhibitions, language,
                                             compiled_inventory,
                                             complete_inventory)
    device = eeprom.init_serial()
    eeprom.write_inventory(eeprom_conents[1], eeprom_conents[2],
                           eeprom_conents[0], device)
Beispiel #22
0
def make_package(inventory_file, preset_file, package_path, format):
    """generates a audio package from audio file found in current directory\n
    :param inventory_file: file specifying which audio files belong to which exhibiton and language\n
    :param preset_file: file specifying which exhibitions are to be written to sd\n
    :param package_path: folder to which all files in package are copied
    :param format: audio file format"""
    if not os.path.isdir(package_path):
        os.makedirs(package_path)
    total_inventory = database.parse_inventory(
        database.read_database(inventory_file))
    preset = database.read_preset(preset_file)
    compiled_inventory, compiled_package = database.compile_inventory_package(
        preset[1], preset[0], total_inventory)
    database.compile_package(compiled_package,
                             '.',
                             package_path,
                             audio_format=format)
Beispiel #23
0
def update_info_database(complete_rewrite=True):
    print('Updating `info_database.json`, '
          f'`complete_rewrite={complete_rewrite}`')
    status_database = read_database(only_processed=True)
    if complete_rewrite:
        info_database = {}
    else:
        with database_path.open() as f:
            info_database = json.load(f)
    dir_names = [ent['name'] for ent in status_database]
    for name in dir_names:
        if name in info_database:
            continue
        result_dir = output / name
        with open(result_dir / 'info.json') as f:
            info = json.load(f)
        info_database[name] = info

    with database_path.open() as f:
        with database_path.open('w') as f:
            json.dump(info_database, f, indent=2)
Beispiel #24
0
    from calc_manage import (clean_history_file, prepare_run,
                             manually_remove_from_struct_des, update_des,
                             inherit_icalc, add_loop, res_loop, complete_run,
                             add_des)

    from functions import calc_ac, plot_charge_den
    from inout import write_xyz

    from database import read_database, write_database
    from set_functions import read_vasp_sets
    from project_funcs import redox, potential_barriers, calc_antisite_defects
    from project_funcs import workflow
    from project_funcs import calc_barriers, cathode_screening
    from analysis import calc_redox

    header.conv, header.varset, size_on_start = read_database()

    calc = header.calc
    conv = header.conv
    varset = header.varset
    # header.db = calc;
    db = header.db
    header.struct_des = update_des(header.struct_des, header.MANUALLY_ADDED)
    #read manually added calculations from project_conf.py file
    struct_des = header.struct_des
    import project_sets  # should be after read_database

    varset = read_vasp_sets(project_sets.user_vasp_sets,
                            override_global=0)  #3. read user sets

    # header.history = clean_history_file(header.history)
def vid(bot, update):  # '/vid' function
    print("\tEjecutando '/vid'...")
    user = update.message.from_user['first_name']
    chat_id = update.message.chat_id
    name = unidecode(user)
    print("Usuario + ID: ", name, chat_id)
    if read_database(chat_id) == None:
        bot.sendMessage(
            chat_id,
            text=
            "Antes de continuar, debes actualizar tus preferencias de idioma\n\nBefore you continue, you have to update your language preferences"
        )
        lang(bot, update)
    elif 'es' in read_database(chat_id):
        bot.sendMessage(chat_id, "Voy a enseñarte a utilizar el bot @vid")
        time.sleep(3)
        step1 = open('/home/javialonso/BOT/paso1.png', 'rb')
        bot.sendPhoto(chat_id, step1)
        bot.sendMessage(chat_id,
                        "Escribes en el teclado @vid para llamar al bot")
        time.sleep(7)
        step2 = open('/home/javialonso/BOT/paso2.png', 'rb')
        bot.sendPhoto(chat_id, step2)
        bot.sendMessage(
            chat_id,
            text=
            "Empiezas a escribir el *título del vídeo* que quieras encontrar",
            parse_mode=telegram.ParseMode.MARKDOWN)
        time.sleep(7)
        step3 = open('/home/javialonso/BOT/paso3.png', 'rb')
        bot.sendPhoto(chat_id, step3)
        bot.sendMessage(
            chat_id,
            text=
            "Una vez encuentres el vídeo que quieras descargar, *pulsas sobre él directamente*",
            parse_mode=telegram.ParseMode.MARKDOWN)
        time.sleep(7)
        step4 = open('/home/javialonso/BOT/paso4.png', 'rb')
        bot.sendPhoto(chat_id, step4)
        bot.sendMessage(
            chat_id,
            "Se enviará el vídeo seleccionado y comenzará la descarga automáticamente"
        )
        time.sleep(3)
        final = open('/home/javialonso/BOT/paso5.png', 'rb')
        bot.sendPhoto(chat_id, final)
        bot.sendMessage(chat_id, "Listo, ya sabes cómo utilzar el bot @vid 😃")
    elif 'en' in read_database(chat_id):
        bot.sendMessage(chat_id,
                        "I'm going to show you how to use the bot @vid")
        time.sleep(3)
        step1 = open('/home/javialonso/BOT/paso1.png', 'rb')
        bot.sendPhoto(chat_id, step1)
        bot.sendMessage(chat_id,
                        "First, type *as a message* @vid to call the bot",
                        parse_mode=telegram.ParseMode.MARKDOWN)
        time.sleep(7)
        step2 = open('/home/javialonso/BOT/paso2.png', 'rb')
        bot.sendPhoto(chat_id, step2)
        bot.sendMessage(
            chat_id,
            text="Then, *start typing the title* of the video you want to find",
            parse_mode=telegram.ParseMode.MARKDOWN)
        time.sleep(7)
        step3 = open('/home/javialonso/BOT/paso3.png', 'rb')
        bot.sendPhoto(chat_id, step3)
        bot.sendMessage(
            chat_id,
            text=
            "When you see the video you want to download, *press on it directly*",
            parse_mode=telegram.ParseMode.MARKDOWN)
        time.sleep(7)
        step4 = open('/home/javialonso/BOT/paso4.png', 'rb')
        bot.sendPhoto(chat_id, step4)
        bot.sendMessage(
            chat_id,
            "The chosen video will be sent and the download will start")
        time.sleep(3)
        final = open('/home/javialonso/BOT/paso5.png', 'rb')
        bot.sendPhoto(chat_id, final)
        bot.sendMessage(chat_id,
                        "It's done, now you know how to use the bot @vid 😃")
from pathlib import Path
import json
import numpy as np
from subprocess import run
from database import clean_database, read_database, add_to_database
from info_database import update_info_database
from datetime import datetime

output = Path('/data3/bolensadrien/output')

clean_database()

database_entries = read_database()
yes_all = False
for entry in database_entries:
    status = entry['status']
    raw_files_exist = entry.get('raw_files_exist', False)
    entry['raw_files_exist'] = raw_files_exist
    name = entry['name']
    result_dir = output / name

    if status == 'processed' or status == 'overtime':
        if raw_files_exist:
            answer = None
            while answer not in ("yes", "no"):
                print(f"{name} still contains the raw results files.")
                answer = input(f"Delete the arrays folder and slurm files? ")
                if answer == "yes":
                    #  prof_file = result_dir / 'array-1' / 'file.prof'
                    #  if prof_file.is_file():
                    #      run(['cp', prof_file, result_dir])
Beispiel #27
0
def video_down(bot, update, chat_id, user):
    try:
        print("BUSCANDO SI EXISTE LA CANCIÓN...")
        save_path = 'PATH_WHERE_YOU_WANT_TO_SAVE_SONGS'
        title_file = "title_{}.txt".format(chat_id)
        video_file = "url_{}.txt".format(chat_id)
        link = open(video_file, 'r')
        titulo = open(title_file, 'r')
        url = link.readline()
        name = titulo.readline()
        print("\n\tEnlace de YouTube: ", url)
        print("\n\tTítulo: ", name)
        link.close()
        titulo.close()
        Id = get_yt_video_id(url)
        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"
        full_name = "{}_{}_{}.".format(name, Id, ad_quality)
        mp3_name = "{}_{}_{}.mp3".format(name, Id, ad_quality)
        complete_name_file = save_path + mp3_name
        mp3_file = Path(complete_name_file)
        if mp3_file.exists():
            print("CANCIÓN ENCONTRADA")
            song = open(complete_name_file, 'rb')
            if 'es' in read_database(chat_id):
                bot.sendMessage(
                    chat_id,
                    text=
                    "Estamos enviando la canción directamente con *calidad " +
                    calidad +
                    "* (cámbialo en /preferences).\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 read_database(chat_id):
                bot.sendMessage(
                    chat_id,
                    text="We are sending you the song directly in *" +
                    calidad_en +
                    " quality* (change it in /preferences).\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)
            if 'en' in read_database(chat_id):
                message = bot.sendMessage(
                    chat_id=chat_id,
                    text="*Request status:* _sending song_ 📲",
                    parse_mode=telegram.ParseMode.MARKDOWN)
            elif 'es' in read_database(chat_id):
                message = bot.sendMessage(
                    chat_id=chat_id,
                    text="*Progreso de la petición:* _enviando canción_ 📲",
                    parse_mode=telegram.ParseMode.MARKDOWN)
            mid = message.message_id
            if (os.path.getsize(complete_name_file) >=
                    50000000):  # Telegram limits bot sendable-file to 50MB
                flag = 1
                raise telegram.error.TelegramError(
                    'El archivo en formato MP3 es mayor de 50 MB - Se envía directamente'
                )
            else:
                bot.sendAudio(chat_id, song)
                print("Completado", "//",
                      threading.currentThread().getName(), "//")
                song.close()
                if 'es' in read_database(chat_id):
                    bot.editMessageText(chat_id=chat_id,
                                        message_id=mid,
                                        text="*Completado* ✅",
                                        parse_mode=telegram.ParseMode.MARKDOWN)
                    if read_os(chat_id, user) == None:
                        key_ios(bot, update, chat_id)
                    elif 'iOS' in read_os(
                            chat_id, user
                    ):  # If device is iOS, we provide a direct download link (because iOS devices cannot obtain downloaded data between apps)
                        bot.sendMessage(
                            chat_id,
                            text=
                            "Has establecido tu dispositivo como un *iOS*, por lo que procedemos a enviarle un enlace de descarga directa (para cambiar este valor, ejecute /preferences).\n\n_Por favor, espere_",
                            parse_mode=telegram.ParseMode.MARKDOWN)
                        url_file = descarga(complete_name_file)
                        bot.sendMessage(
                            chat_id,
                            text="Aquí tienes tu [enlace de descarga directa]("
                            + url_file + ").",
                            parse_mode=telegram.ParseMode.MARKDOWN)
                        try:
                            if path.exists(title_file):
                                os.remove(title_file)
                            if path.exists(video_file):
                                os.remove(video_file)
                            key_f(bot, update, chat_id)
                        except PermissionError:
                            key_f(bot, update, chat_id)
                    else:
                        try:
                            if path.exists(title_file):
                                os.remove(title_file)
                            if path.exists(video_file):
                                os.remove(video_file)
                            key_f(bot, update, chat_id)
                        except PermissionError:
                            key_f(bot, update, chat_id)
                elif 'en' in read_database(chat_id):
                    bot.editMessageText(chat_id=chat_id,
                                        message_id=mid,
                                        text="*Done* ✅",
                                        parse_mode=telegram.ParseMode.MARKDOWN)
                    if read_os(chat_id, user) == None:
                        key_iosen(bot, update, chat_id)
                    elif 'iOS' in read_os(chat_id, user):
                        bot.sendMessage(
                            chat_id,
                            text=
                            "You have setted your device as an *iOS*, so we are preparing a direct download link for you (for changing this value, use /preferences).\n\n_Please, wait_",
                            parse_mode=telegram.ParseMode.MARKDOWN)
                        url_file = descarga(complete_name_file)
                        bot.sendMessage(
                            chat_id,
                            text="Here you have [your direct download link](" +
                            url_file + ").",
                            parse_mode=telegram.ParseMode.MARKDOWN)
                        try:
                            if path.exists(title_file):
                                os.remove(title_file)
                            if path.exists(video_file):
                                os.remove(video_file)
                            key_fen(bot, update, chat_id)
                        except PermissionError:
                            key_fen(bot, update, chat_id)
                    else:
                        try:
                            if path.exists(title_file):
                                os.remove(title_file)
                            if path.exists(video_file):
                                os.remove(video_file)
                            key_fen(bot, update, chat_id)
                        except PermissionError:
                            key_fen(bot, update, chat_id)
                print("Canción enviada correctamente")
        else:
            print("NO SE HA ENCONTRADO LA CANCIÓN")
            titulo_2 = name.translate({ord(c): None for c in '()[]-'})
            titulo_3 = titulo_2.replace("feat", "")
            titulo_4 = titulo_3.replace("Lyrics" or "lyrics" or "LYRICS", "")
            titulo_5 = titulo_4.replace(
                "Audio Only" or "audio Only" or "audio only", "")
            titulo_6 = titulo_5.replace(
                "Official video" or "Official Video" or "Official"
                or "official" or "OFFICIAL", "")
            titulo_7 = titulo_6.replace("LIVE" or "Live" or "live", "")
            titulo_8 = titulo_7.replace("Cover" or "COVER" or "cover", "")
            titulo_9 = titulo_8.replace("short" or "Short" or "SHORT", "")
            titulo_10 = titulo_9.replace("HD", "")
            titulo_11 = titulo_10.replace("Version" or "version" or "VERSION",
                                          "")
            titulo_12 = titulo_11.replace("Video" or "video" or "VIDEO", "")
            titulo_13 = titulo_12.replace("long" or "Long" or "LONG", "")
            titulo_14 = titulo_13.replace("Lyric" or "lyric" or "LYRIC", "")
            titulo_15 = titulo_14.replace("Full", "")
            titulo_16 = titulo_15.replace("OST", "")
            titulo_17 = titulo_16.replace("HQ", "")
            titulo_18 = titulo_17.replace("Audio" or "audio" or "AUDIO", "")
            print("\n\tTítulo de búsqueda: ", titulo_18)
            idioma = read_database(chat_id)
            time.sleep(2)
            cov_name = "cover_{}.jpg".format(chat_id)
            if 'es' in idioma:
                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)
                message = bot.sendMessage(
                    chat_id,
                    text="*Progreso de la petición:* _obteniendo metadatos_ 🎧",
                    parse_mode=telegram.ParseMode.MARKDOWN)
            elif 'en' in idioma:
                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)
                message = bot.sendMessage(
                    chat_id,
                    text="*Request status:* _getting metadata_ 🎧",
                    parse_mode=telegram.ParseMode.MARKDOWN)
            mid = message.message_id
            api = ask_for_credentials()
            song = api.search(titulo_18, max_results=1)
            try:
                album = song['song_hits'][0]['track']['album']
                print("\n\tAlbum encontrado")
            except IndexError:
                print("Error al conseguir el álbum")
                album = "Unknown"
            try:
                artist = song['song_hits'][0]['track']['albumArtist']
                print("\tArtista encontrado")
            except IndexError:
                print("Error al conseguir el nombre del artista")
                artist = "Unknown"
            try:
                cover_url = song['song_hits'][0]['track']['albumArtRef'][0][
                    'url']
                urllib.request.urlretrieve(cover_url, cov_name)
                picture = cov_name
                print("\tCarátula encontrada")
            except IndexError:
                print("Error al conseguir la carátula del álbum")
                picture = "default.png"
            try:
                titulo_met = song['song_hits'][0]['track']['title']
                print("\tTítulo encontrado")
            except IndexError:
                print("Error al conseguir el título de la canción")
                titulo_met = name
            video = pafy.new(url)
            audio = video.getbestaudio(
            )  # 'webm' has always the best quality audio (on YouTube)
            print("\n\tEntrado dentro de la sección de descarga...", "//",
                  threading.currentThread().getName(), "//")
            print("\n\tFormato de audio: ", audio.extension)
            if 'es' in idioma:
                bot.editMessageText(
                    chat_id=chat_id,
                    message_id=mid,
                    text="*Progreso de la petición:* _descargando vídeo ..._ ⬇",
                    parse_mode=telegram.ParseMode.MARKDOWN)
            elif 'en' in idioma:
                bot.editMessageText(
                    chat_id=chat_id,
                    message_id=mid,
                    text="*Request status:* _downloading video ..._ ⬇",
                    parse_mode=telegram.ParseMode.MARKDOWN)
            audio.download(
                quiet=False, filepath=full_name +
                audio.extension)  # 'quiet=False' shows a progress bar
            full_name_w = "{}_{}_{}.{}".format(name, Id, ad_quality,
                                               audio.extension)
            print("\n\tConvirtiendo a mp3...")
            if (
                    os.path.getsize(full_name_w) >= 25000000
            ):  # For converting this huge files it's needed a bit more time than others
                if 'es' in read_database(chat_id):
                    bot.editMessageText(
                        chat_id=chat_id,
                        message_id=mid,
                        text=
                        "*Progreso de la petición:* _convirtiendo a mp3_ 🎶\n\nComo es un poco más grande de lo normal, tardará un poquito más en enviarse _(pero no hay que preocuparse por nada 😉)_",
                        parse_mode=telegram.ParseMode.MARKDOWN)
                elif 'en' in read_database(chat_id):
                    bot.editMessageText(
                        chat_id=chat_id,
                        message_id=mid,
                        text=
                        "*Request status:* _converting to mp3_ 🎶\n\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)
            elif 'es' in idioma:
                bot.editMessageText(
                    chat_id=chat_id,
                    message_id=mid,
                    text="*Progreso de la petición:* _convirtiendo a mp3_ 🎶",
                    parse_mode=telegram.ParseMode.MARKDOWN)
            elif 'en' in idioma:
                bot.editMessageText(
                    chat_id=chat_id,
                    message_id=mid,
                    text="*Request status:* _converting to mp3_ 🎶",
                    parse_mode=telegram.ParseMode.MARKDOWN)
            AudioSegment.from_file(full_name_w,
                                   audio.extension).export(mp3_name,
                                                           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):
                os.remove(cov_name)
            song = open(mp3_name, "rb")
            print("\n\tEnviando canción...")
            if 'es' in idioma:
                bot.editMessageText(
                    chat_id=chat_id,
                    message_id=mid,
                    text="*Progreso de la petición:* _enviando canción_ 📲",
                    parse_mode=telegram.ParseMode.MARKDOWN)
            elif 'en' in idioma:
                bot.editMessageText(chat_id=chat_id,
                                    message_id=mid,
                                    text="*Request status:* _sending song_ 📲",
                                    parse_mode=telegram.ParseMode.MARKDOWN)
            if (os.path.getsize(mp3_name) >=
                    50000000):  # Telegram limits bot sendable-file to 50MB
                flag = 0
                raise telegram.error.TelegramError(
                    'El archivo en formato MP3 es mayor de 50 MB - Se envía directamente'
                )
            else:
                bot.sendAudio(chat_id, song)
                print("Completado", "//",
                      threading.currentThread().getName(), "//")
                song.close()
                if 'es' in read_database(chat_id):
                    bot.editMessageText(chat_id=chat_id,
                                        message_id=mid,
                                        text="*Completado* ✅",
                                        parse_mode=telegram.ParseMode.MARKDOWN)
                    if read_os(chat_id, user) == None:
                        key_ios(bot, update, chat_id)
                    elif 'iOS' in read_os(
                            chat_id, user
                    ):  # If device is iOS, we provide a direct download link (because iOS devices cannot obtain downloaded data between apps)
                        bot.sendMessage(
                            chat_id,
                            text=
                            "Has establecido tu dispositivo como un *iOS*, por lo que procedemos a enviarle un enlace de descarga directa (para cambiar este valor, ejecute /preferences).\n\n_Por favor, espere_",
                            parse_mode=telegram.ParseMode.MARKDOWN)
                        url_file = descarga(mp3_name)
                        bot.sendMessage(
                            chat_id,
                            text="Aquí tienes tu [enlace de descarga directa]("
                            + url_file + ").",
                            parse_mode=telegram.ParseMode.MARKDOWN)
                        try:
                            if path.exists(title_file):
                                os.remove(title_file)
                            if path.exists(video_file):
                                os.remove(video_file)
                            if path.exists(mp3_name):
                                os.rename('ORIGINAL_PATH' + mp3_name,
                                          complete_name_file)
                            key_f(bot, update, chat_id)
                        except PermissionError:
                            key_f(bot, update, chat_id)
                    else:
                        try:
                            if path.exists(title_file):
                                os.remove(title_file)
                            if path.exists(video_file):
                                os.remove(video_file)
                            if path.exists(mp3_name):
                                os.rename('ORIGINAL_PATH' + mp3_name,
                                          complete_name_file)
                            key_f(bot, update, chat_id)
                        except PermissionError:
                            key_f(bot, update, chat_id)
                elif 'en' in read_database(chat_id):
                    bot.editMessageText(chat_id=chat_id,
                                        message_id=mid,
                                        text="*Done* ✅",
                                        parse_mode=telegram.ParseMode.MARKDOWN)
                    if read_os(chat_id, user) == None:
                        key_iosen(bot, update, chat_id)
                    elif 'iOS' in read_os(chat_id, user):
                        bot.sendMessage(
                            chat_id,
                            text=
                            "You have setted your device as an *iOS*, so we are preparing a direct download link for you (for changing this value, use /preferences).\n\n_Please, wait_",
                            parse_mode=telegram.ParseMode.MARKDOWN)
                        url_file = descarga(mp3_name)
                        bot.sendMessage(
                            chat_id,
                            text="Here you have [your direct download link](" +
                            url_file + ").",
                            parse_mode=telegram.ParseMode.MARKDOWN)
                        try:
                            if path.exists(title_file):
                                os.remove(title_file)
                            if path.exists(video_file):
                                os.remove(video_file)
                            if path.exists(mp3_name):
                                os.rename('ORIGINAL_PATH' + mp3_name,
                                          complete_name_file)
                            key_fen(bot, update, chat_id)
                        except PermissionError:
                            key_fen(bot, update, chat_id)
                    else:
                        try:
                            if path.exists(title_file):
                                os.remove(title_file)
                            if path.exists(video_file):
                                os.remove(video_file)
                            if path.exists(mp3_name):
                                os.rename('ORIGINAL_PATH' + mp3_name,
                                          complete_name_file)
                            key_fen(bot, update, chat_id)
                        except PermissionError:
                            key_fen(bot, update, chat_id)
                print("Canción enviada correctamente")
    except telegram.error.TelegramError:
        print("\n\"TelegramError\" - Mostrando mensaje...", "//",
              threading.currentThread().getName(), "//")
        if 'es' in read_database(chat_id):
            bot.sendMessage(
                chat_id,
                text=
                "*¡¡Ups!!* 😱\n\nDebido a que tu archivo es bastante grande _(>50 MB)_, no te lo *podemos enviar directamente por Telegram*, por lo que lo estamos subiendo a un servidor para que lo puedas *descargar directamente*.\n\nMantente a la espera y en nada tendrás tu descarga lista 👌",
                parse_mode=telegram.ParseMode.MARKDOWN)
            bot.editMessageText(
                chat_id=chat_id,
                message_id=mid,
                text="*Progreso de la petición:* _subiendo a_ file.io _..._ ⬆️",
                parse_mode=telegram.ParseMode.MARKDOWN)
        elif 'en' in read_database(chat_id):
            bot.sendMessage(
                chat_id,
                text=
                "*¡¡Wooha!!* 😱\n\nYour file is too big _(>50 MB)_, so we *can't send it by Telegram*, but don't worry because we're uploading it to a server in order to *let you download it directly*.\n\nWait for a time and you'll have your download ready 👌",
                parse_mode=telegram.ParseMode.MARKDOWN)
            bot.editMessageText(
                chat_id=chat_id,
                message_id=mid,
                text=
                "*Progreso de la petición:* _uploading to_ file.io _..._ ⬆️",
                parse_mode=telegram.ParseMode.MARKDOWN)
        if flag == 0:
            url_file = descarga(mp3_name)
        elif flag == 1:
            url_file = descarga(complete_name_file)
        time.sleep(1)
        if 'es' in read_database(chat_id):
            bot.sendMessage(
                chat_id,
                text="Aquí tienes tu [enlace de descarga directa](" +
                url_file +
                "). Tienes *una semana entera* para utilizar el enlace anterior, luego se eliminará.",
                parse_mode=telegram.ParseMode.MARKDOWN)
            bot.editMessageText(chat_id=chat_id,
                                message_id=mid,
                                text="*Completado* ✅",
                                parse_mode=telegram.ParseMode.MARKDOWN)
        elif 'en' in read_database(chat_id):
            bot.sendMessage(
                chat_id,
                text="Here you have [your direct download link](" + url_file +
                "). You have *a hole week* to use that link, then it will be deleted from server.",
                parse_mode=telegram.ParseMode.MARKDOWN)
            bot.editMessageText(chat_id=chat_id,
                                message_id=mid,
                                text="*Done* ✅",
                                parse_mode=telegram.ParseMode.MARKDOWN)
        try:
            if path.exists(title_file):
                os.remove(title_file)
            if path.exists(video_file):
                os.remove(video_file)
            if path.exists(mp3_name):
                song.close()
                os.rename('ORIGINAL_PATH' + mp3_name, complete_name_file)
        except PermissionError:
            print(
                "\n\tError en los permisos (el archivo/s están siendo utilizados)"
            )
            print("Limpiando búffer y cerrando", "//",
                  threading.currentThread().getName(), "//")
            sys.stdout.flush()
            sys.stdin.flush()
            print("//",
                  threading.currentThread().getName(), "//",
                  "cerrado correctamente")
    except (OSError, youtube_dl.utils.ExtractorError,
            youtube_dl.utils.DownloadError) as e:
        try:
            full_name_w = "{}_{}_{}.{}".format(name, Id, ad_quality,
                                               audio.extension)
            if 'es' in read_database(chat_id):
                bot.editMessageText(chat_id=chat_id,
                                    message_id=mid,
                                    text="*Error* 🚫",
                                    parse_mode=telegram.ParseMode.MARKDOWN)
                bot.sendMessage(
                    chat_id,
                    text=
                    "No hemos podido descargar tu vídeo por temas de *Copyright*. _Sentimos mucho las molestias_",
                    parse_mode=telegram.ParseMode.MARKDOWN)
                try:
                    if path.exists(title_file):
                        os.remove(title_file)
                    if path.exists(video_file):
                        os.remove(video_file)
                    if path.exists(mp3_name):
                        song.close()
                        os.rename('ORIGINAL_PATH' + mp3_name,
                                  complete_name_file)
                    if path.exists(full_name_w):
                        os.remove(full_name_w)
                except PermissionError:
                    print(
                        "\n\tError en los permisos (el archivo/s están siendo utilizados)"
                    )
                    print("Limpiando búffer y cerrando", "//",
                          threading.currentThread().getName(), "//")
                    sys.stdout.flush()
                    sys.stdin.flush()
                    print("//",
                          threading.currentThread().getName(), "//",
                          "cerrado correctamente")
            elif 'en' in read_database(chat_id):
                bot.editMessageText(chat_id=chat_id,
                                    message_id=mid,
                                    text="*Error* 🚫",
                                    parse_mode=telegram.ParseMode.MARKDOWN)
                bot.sendMessage(
                    chat_id,
                    text=
                    "We couldn't download your video because of *Copyright conditions*. _We're sorry for the inconvenience_",
                    parse_mode=telegram.ParseMode.MARKDOWN)
                try:
                    if path.exists(title_file):
                        os.remove(title_file)
                    if path.exists(video_file):
                        os.remove(video_file)
                    if path.exists(mp3_name):
                        song.close()
                        os.rename('ORIGINAL_PATH' + mp3_name,
                                  complete_name_file)
                    if path.exists(full_name_w):
                        os.remove(full_name_w)
                except PermissionError:
                    print(
                        "\n\tError en los permisos (el archivo/s están siendo utilizados)"
                    )
                    print("Limpiando búffer y cerrando", "//",
                          threading.currentThread().getName(), "//")
                    sys.stdout.flush()
                    sys.stdin.flush()
                    print("//",
                          threading.currentThread().getName(), "//",
                          "cerrado correctamente")
        except UnboundLocalError:
            if 'es' in read_database(chat_id):
                bot.editMessageText(chat_id=chat_id,
                                    message_id=mid,
                                    text="*Error* 🚫",
                                    parse_mode=telegram.ParseMode.MARKDOWN)
                bot.sendMessage(
                    chat_id,
                    text=
                    "No hemos podido descargar tu vídeo por temas de *Copyright*. _Sentimos mucho las molestias_",
                    parse_mode=telegram.ParseMode.MARKDOWN)
                try:
                    if path.exists(title_file):
                        os.remove(title_file)
                    if path.exists(video_file):
                        os.remove(video_file)
                except PermissionError:
                    print(
                        "\n\tError en los permisos (el archivo/s están siendo utilizados)"
                    )
                    print("Limpiando búffer y cerrando", "//",
                          threading.currentThread().getName(), "//")
                    sys.stdout.flush()
                    sys.stdin.flush()
                    print("//",
                          threading.currentThread().getName(), "//",
                          "cerrado correctamente")
            elif 'en' in read_database(chat_id):
                bot.editMessageText(chat_id=chat_id,
                                    message_id=mid,
                                    text="*Error* 🚫",
                                    parse_mode=telegram.ParseMode.MARKDOWN)
                bot.sendMessage(
                    chat_id,
                    text=
                    "We couldn't download your video because of *Copyright conditions*. _We're sorry for the inconvenience_",
                    parse_mode=telegram.ParseMode.MARKDOWN)
                try:
                    if path.exists(title_file):
                        os.remove(title_file)
                    if path.exists(video_file):
                        os.remove(video_file)
                except PermissionError:
                    print(
                        "\n\tError en los permisos (el archivo/s están siendo utilizados)"
                    )
                    print("Limpiando búffer y cerrando", "//",
                          threading.currentThread().getName(), "//")
                    sys.stdout.flush()
                    sys.stdin.flush()
                    print("//",
                          threading.currentThread().getName(), "//",
                          "cerrado correctamente")
Beispiel #28
0
import sys
import numpy as np

sys.path.append('/home/aksenov/Simulation_wrapper/siman'
                )  #provide your path to siman package
import header
from header import db  # database dictionary
from calc_manage import smart_structure_read, add_loop, res_loop
from geo import supercell
from database import read_database, write_database

read_database()  # read saved results
"""1. Read structure and create supercells with defects"""
if 1:
    st = smart_structure_read(input_geo_file='Li2/POSCAR')

    sc = supercell(
        st, [10, 10, 10])  # create 3x3x3 supercell, sizes close to 10 10 10 A

    sc_vac = sc.del_atom(25)  # create vacancy defect in supercell

    # sc_vac.write_poscar('Li_vac/POSCAR') # write POSCAR to check geometry

    sc_oct = sc.add_atom(
        [1 / 2 / 3, 1 / 2 / 3, 1 / 3],
        'Li')  # create interstitial defect in octahedral position
    sc_tet = sc.add_atom(
        [1 / 4 / 3, 1 / 2 / 3, 1 / 3],
        'Li')  # create interstitial defect in tetrahedral position

    # sc_oct.write_poscar('Li_oct/POSCAR')
def botones(
    bot, update, chat_id, message_id, value, user
):  # 'value' is obtained from "def buttons" in 'TeleBotSongDownloader.py'
    star = "https://goo.gl/12AADY"
    hour_spain = "http://24timezones.com/es_husohorario/madrid_hora_actual.php"
    hour_eng = "http://24timezones.com/world_directory/time_in_madrid.php"
    if value == "1":
        if 'es' in read_database(chat_id):
            bot.editMessageText(
                text=
                "Prueba a intentar la descarga de nuevo.\n\nPrueba a introducir la URL del vídeo directamente (suele funcionar en la mayoría de los casos).\n\nDisculpa las molestias. *Si necesitas más ayuda*, escribe  /errors",
                chat_id=chat_id,
                message_id=message_id,
                parse_mode=telegram.ParseMode.MARKDOWN)
        elif 'en' in read_database(chat_id):
            bot.editMessageText(
                text=
                "Retry the download.\n\nTry to put the video URL directly (it usually works in almos cases).\n\nSorry for the inconvenience. *If you need more help*, type  /errors",
                chat_id=chat_id,
                message_id=message_id,
                parse_mode=telegram.ParseMode.MARKDOWN)
    elif value == "2":
        if 'es' in read_database(chat_id):
            bot.editMessageText(
                text=
                "Muchas gracias por utilizarme 😄\n\n\nPara descargar otra canción, puedes: \n\nescribirme directamente el *título* 🎵,\nmandar la *URL* del vídeo 📎,\n*buscar* el vídeo con  @vid ▶,\n/help _para más ayuda_\n\n*¿Te gusta este bot?* 👍 No dudes en enviarme tus comentarios [haciendo clic aquí]("
                + star + ")",
                parse_mode=telegram.ParseMode.MARKDOWN,
                chat_id=chat_id,
                message_id=message_id)
        elif 'en' in read_database(chat_id):
            bot.editMessageText(
                text=
                "Thank you so much for using me 😄\n\n\nTo download another song, you can: \n\nsend me directly *the title of the video* 🎵,\nsend me *the URL of the video* 📎,\n*search the video* with @vid ▶,\n/help _for get assistance_\n\n*Do you like this bot?* 👍 Please send me your opinions [by clicking here]("
                + star + ")",
                parse_mode=telegram.ParseMode.MARKDOWN,
                chat_id=chat_id,
                message_id=message_id)

    elif value == "Ax":
        if 'es' in read_database(chat_id):
            bot.editMessageText(text="_Comenzando la descarga..._",
                                parse_mode=telegram.ParseMode.MARKDOWN,
                                chat_id=chat_id,
                                message_id=message_id)
        elif 'en' in read_database(chat_id):
            bot.editMessageText(text="_Starting download..._",
                                parse_mode=telegram.ParseMode.MARKDOWN,
                                chat_id=chat_id,
                                message_id=message_id)
        sender(bot, update, chat_id, user)
    elif value == "Ay":
        if 'es' in read_database(chat_id):
            bot.editMessageText(text="*Descarga cancelada*",
                                parse_mode=telegram.ParseMode.MARKDOWN,
                                chat_id=chat_id,
                                message_id=message_id)
        elif 'en' in read_database(chat_id):
            bot.editMessageText(text="*Download cancelled*",
                                parse_mode=telegram.ParseMode.MARKDOWN,
                                chat_id=chat_id,
                                message_id=message_id)
        if path.exists(title_file):
            os.remove(title_file)
        if path.exists(video_file):
            os.remove(video_file)
    elif value == "en":
        bot.editMessageText(
            text=
            "_Preferences updated correctly..._\n\nIf you want to *change your language*, just use the command /preferences\n\n_If you were trying to download a video, please start again._",
            parse_mode=telegram.ParseMode.MARKDOWN,
            chat_id=chat_id,
            message_id=message_id)
        data = None
        write_database(user, chat_id, value, data)
    elif value == "es":
        bot.editMessageText(
            text=
            "_Preferencias actualizadas correctamente..._\n\nPara *cambiar el idioma en cualquier momento*, ejecuta /preferences\n\n_Si estabas intentando descargar un vídeo, por favor comienza de nuevo._",
            parse_mode=telegram.ParseMode.MARKDOWN,
            chat_id=chat_id,
            message_id=message_id)
        data = None
        write_database(user, chat_id, value, data)
    elif value == "glish":
        bot.editMessageText(
            text=
            "_Preferences updated correctly..._\n\nIf you want to *change your language*, just use the command /preferences",
            parse_mode=telegram.ParseMode.MARKDOWN,
            chat_id=chat_id,
            message_id=message_id)
        value = "en"
        data = "Something"
        write_database(user, chat_id, value, data)
    elif value == "castell":
        bot.editMessageText(
            text=
            "_Preferencias actualizadas correctamente..._\n\nPara *cambiar el idioma en cualquier momento*, ejecuta /preferences",
            parse_mode=telegram.ParseMode.MARKDOWN,
            chat_id=chat_id,
            message_id=message_id)
        value = "es"
        data = "Something"
        write_database(user, chat_id, value, data)
    elif value == "Ed":
        key_ed(bot, update, chat_id)
    elif value == "O":
        key_o(bot, update, chat_id)
    elif value == "V":
        bot.sendMessage(
            chat_id,
            text=
            "Algunas veces, el servidor *sufre un colapso* 😫 y no se envían correctamente las canciones.\
        \n\nEsto se soluciona volviendo a pedirle al servidor que _descargue la canción_",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "U":
        bot.sendMessage(
            chat_id,
            text=
            "Cuando el vídeo no puede ser obtenido _directamente desde Telegram_ (a causa del servidor de descargas), \
se manda un *enlace* 📎 para descargarlo y luego ya se puede conseguir directamente desde Telegram",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "Z":
        bot.sendMessage(
            chat_id,
            text=
            "El bot puede no mostrar respuesta debido a un error ⚠ que no tenemos registrado. \
Todos los días revisamos los errores del bot, por lo que debería solucionarse en esta semana 😄",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "S":
        bot.sendMessage(
            chat_id,
            text=
            "Cuando se produce una descarga muy lenta, entran en juego varios factores fundamentales:\
        \n\nSi la canción 🎶 que quieres descargar es *muy larga*, se va a necesitar mayor tiempo 🕒 dependiendo de la _calidad de audio_ que tengas elegida (usa /preferences para cambiarlo)\
        \n\n*Tu ubicación* 🛰 es determinante, pues cuanto más lejos te encuentres del servidor más se tarda.\
        \n*Los usuarios activos* 👨‍👩‍👧‍👦 provocan una demora en los tiempos de descarga.\n*El servidor puede haberse bloqueado* 🌁.\
        \n*El servidor de descargas* ❌ no responde, siendo esta última la razón más usual para descargas lentas.\
        \n\nSin poder decir mucho más, *paciencia*: tarde o temprano la canción se acaba enviando y sino, pondremos medios para ello 😄",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "LK":
        bot.sendMessage(
            chat_id,
            text=
            "Es posible que seas el descubridor de *un fallo nuevo* (weeh 😱👏🎉‼),\
 por lo que si quieres comentarlo ve a [este enlace](" + star +
            "), puntúa el bot ⭐ y a continuación, *deja una reseña* 📝.\nLas leemos _todos los días_, por lo que agradeceremos mucho tu aportación.",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "fi":
        bot.sendMessage(
            chat_id,
            text=
            "Algunas veces, introduciendo *solo el nombre de la canción* 🎤 o *solo el artista* 💃 no es suficiente para el bot para encontrar *la canción que quieres*.\
        \n\nPara ello, te recomendamos que *ejecutes* /vid *para obtener una canción concreta* desde Telegram.",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "mn":
        bot.sendMessage(
            chat_id,
            text=
            "_A continuación se muestran todos los errores registrados más comunes:_\n\n\n \"El bot manda un mensaje diciendo que *no se puede descargar* pero me manda un link para hacerlo\"\n\nEsto se produce en la mayoría de los casos debido a que la *página de descargas todavía no tiene la información que necesita Telegram para poder descargar el vídeo directamente*.\nUna vez lo descargas desde la página web, se suele _poder descargar desde el bot_.\n\n \"El bot dice que *no se ha encontrado nada*\"\n\nEsto se suele producir porque o bien *solo has introducido el nombre del artista* o porque *el vídeo no existe*. Prueba a utilizar el Bot   @vid    para _mandar directamente la URL del vídeo que quieras obtener_. (escribe   /vid    para más información).\n\n\"El archivo de audio tiene una parte que pone un número del estilo: _\"1234567\"_\"\n\nEl archivo que se envía tiene una ID asociada a cada usuario pues así no se extravía por el camino o produce algún fallo en el servidor.\nEstamos trabajando en una solución posible.\n\n\"El bot *tarda mucho en descargar* algunas canciones\"\n\nCuando ocurre esto, puede ser o bien porque nuestro servidor está *colapsado con solicitudes* o porque la plataforma que utilizamos para descargar el vídeo *no responde o tiene que atender demasiadas peticiones*. No hay solución posible más que esperar a que se envíe la canción o, en su defecto, un enlace para descargarla.",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "Eden":
        key_eden(bot, update, chat_id)
    elif value == "Oen":
        key_oen(bot, update, chat_id)
    elif value == "Ven":
        bot.sendMessage(
            chat_id,
            text=
            "Sometimes the server *collapses* 😫 and the songs are not sent correctly.\
        \n\nThis is resolved by asking the server again to _download the song_",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "Uen":
        bot.sendMessage(
            chat_id,
            text=
            "When a video can't be obtained _directly from Telegram_ (because of the download server), \
we provide you *a link* 📎 for downloading and then you can get it directly from Telegram",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "Zen":
        bot.sendMessage(
            chat_id,
            text=
            "The bot can be not able to show response because of a non-registered error ⚠. \
We check everyday the information about happened errors and it should be solved in this week 😄",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "Sen":
        bot.sendMessage(
            chat_id,
            text=
            "When a very slow download is happening, some key factors are relevant:\
        \n\nIf the song 🎶 you were trying to download is *very long*, more time is needed 🕒 depending on chosen _audio quality_ (use /preferences for changing it)\
        \n\n*Your location* 🛰 is determinant, as when far away you are from the server and it takes longer to send you the song.\
        \n*Active users* 👨‍👩‍👧‍👦 can cause a delay in download-times.\n*Server can have got frozen* 🌁.\n*Download server* is not responding ❌, being this the most usual reason why downloads perform slowly.\
        \n\nI can only tell you *patience*: sooner or later your song will be availabe to download from Telegram by a way or other 😄",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "LKen":
        bot.sendMessage(
            chat_id,
            text=
            "It's possible that you are the discoverer of a *new error* (weeh 😱👏🎉‼), so if you would like us to get known about it go to [this link]("
            + star + "), \
rate the bot ⭐ an then *leave a review* 📝.\nWe read them _every day_, so we will appreciate so much your contribution.",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "fien":
        bot.sendMessage(
            chat_id,
            text=
            "Sometimes, giving the bot *only the name of the song* 🎤 or *only the artist* 💃 is not enough to find *the song you are looking for*.\
\n\nFor this, we recommend you *to execute* /vid *in order to get a specific song* directly from Telegram.",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "mnen":
        bot.sendMessage(
            chat_id,
            text=
            "_Now we are displaying all registered common-errors:_\n\n\n \"The bot sends a message telling that *is not possible to download the song* but sends me a link to do it\"\n\nThis happens because *the download page we use still not have the information needed by Telegram to download the video directly*.\nOnce you have downloaded it from the web page, you can usually _download it from the bot_.\n\n \"The bot says that *nothing was found*\"\n\nThis usually happens because or *you have only send the artist name* or because *the video doesn't exist*. Try to use the bot  @vid  to _send the video URL directly_ (type  /vid  to learn how to use this bot).\n\n\"The audio file has a numbered part like: _\"1234567\"_\"\n\nThe audio file the bot sends you has your ID attached in order to send it only to you.\nWe are working on a possible solution.\n\n\"It takes a long time for the bot to download songs\"\n\nWhen this occur, can be becauseour server is *collapsed* or most probably because the *download platform* we are using is down. There is no possible solution more than waiting for the video to be downloaded.",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "3":
        bot.editMessageText(text="Por favor, espere...",
                            chat_id=chat_id,
                            message_id=message_id)
        title_file = "title_{}.txt".format(chat_id)
        video_file = "url_{}.txt".format(chat_id)
        save_path = '/home/javialonso/BOT/Songs/'
        link = open(video_file, 'r')
        titulo = open(title_file, 'r')
        url = link.readline()
        name = titulo.readline()
        link.close()
        titulo.close()
        Id = get_yt_video_id(url)
        ad_quality = read_audio(chat_id)
        if ad_quality == None:
            ad_quality = "256k"
        mp3_name = "{}_{}_{}.mp3".format(name, Id, ad_quality)
        complete_name_file = save_path + mp3_name
        try:
            url_file = descarga(mp3_name)
        except FileNotFoundError:
            url_file = descarga(complete_name_file)
        bot.sendMessage(
            text=
            "Para los usuarios de dispositivos iOS 📱 (iPhone - iPad), aquí tenéis un enlace de [descarga directa]("
            + url_file +
            ") (_recomendamos utilizar un explorador alternativo a Safari pues sino no se podrán guardar las descargas_. Prueba con *Dolphin Browser*",
            chat_id=chat_id,
            parse_mode=telegram.ParseMode.MARKDOWN)
        value = "iOS"
        write_os(chat_id, user, value)
        try:
            if path.exists(video_file):
                os.remove(video_file)
            if path.exists(title_file):
                os.remove(title_file)
            if path.exists(mp3_name):
                os.rename('/home/javialonso/BOT/' + mp3_name,
                          complete_name_file)
            key_f(bot, update, chat_id)
        except PermissionError:
            key_f(bot, update, chat_id)
    elif value == "5":
        bot.editMessageText(text="Please, wait...",
                            chat_id=chat_id,
                            message_id=message_id)
        title_file = "title_{}.txt".format(chat_id)
        video_file = "url_{}.txt".format(chat_id)
        save_path = '/home/javialonso/BOT/Songs/'
        link = open(video_file, 'r')
        titulo = open(title_file, 'r')
        url = link.readline()
        name = titulo.readline()
        link.close()
        titulo.close()
        Id = get_yt_video_id(url)
        ad_quality = read_audio(chat_id)
        if ad_quality == None:
            ad_quality = "256k"
        mp3_name = "{}_{}_{}.mp3".format(name, Id, ad_quality)
        complete_name_file = save_path + mp3_name
        try:
            url_file = descarga(mp3_name)
        except FileNotFoundError:
            url_file = descarga(complete_name_file)
        bot.sendMessage(
            text=
            "For iOS users 📱 (iPhone - iPad), here you have [a direct download link]("
            + url_file +
            ") (_we recommend to use an alternative browser to Safari in order to save your song_. Try with *Dolphin Browser*",
            chat_id=chat_id,
            parse_mode=telegram.ParseMode.MARKDOWN)
        value = "iOS"
        write_os(chat_id, user, value)
        try:
            if path.exists(video_file):
                os.remove(video_file)
            if path.exists(title_file):
                os.remove(title_file)
            if path.exists(mp3_name):
                os.rename('/home/javialonso/BOT/' + mp3_name,
                          complete_name_file)
            key_fen(bot, update, chat_id)
        except PermissionError:
            key_fen(bot, update, chat_id)
    elif value == "4":
        bot.editMessageText(
            text=
            "Perfecto, muchas gracias por tu colaboración (era solo para ayudar a los usuarios de iOS con la descarga)",
            chat_id=chat_id,
            message_id=message_id,
            parse_mode=telegram.ParseMode.MARKDOWN)
        title_file = "title_{}.txt".format(chat_id)
        video_file = "url_{}.txt".format(chat_id)
        save_path = '/home/javialonso/BOT/Songs/'
        link = open(video_file, 'r')
        titulo = open(title_file, 'r')
        url = link.readline()
        name = titulo.readline()
        link.close()
        titulo.close()
        Id = get_yt_video_id(url)
        ad_quality = read_audio(chat_id)
        if ad_quality == None:
            ad_quality = "256k"
        mp3_name = "{}_{}_{}.mp3".format(name, Id, ad_quality)
        complete_name_file = save_path + mp3_name
        value = "Android"
        write_os(chat_id, user, value)
        try:
            if path.exists(video_file):
                os.remove(video_file)
            if path.exists(title_file):
                os.remove(title_file)
            if path.exists(mp3_name):
                os.rename('/home/javialonso/BOT/' + mp3_name,
                          complete_name_file)
            key_f(bot, update, chat_id)
        except PermissionError:
            key_f(bot, update, chat_id)
    elif value == "6":
        bot.editMessageText(
            text=
            "Perfect, thank you so much for your colaboration (that was only for helping iOS users with the download)",
            chat_id=chat_id,
            message_id=message_id,
            parse_mode=telegram.ParseMode.MARKDOWN)
        title_file = "title_{}.txt".format(chat_id)
        video_file = "url_{}.txt".format(chat_id)
        save_path = '/home/javialonso/BOT/Songs/'
        link = open(video_file, 'r')
        titulo = open(title_file, 'r')
        url = link.readline()
        name = titulo.readline()
        link.close()
        titulo.close()
        Id = get_yt_video_id(url)
        ad_quality = read_audio(chat_id)
        if ad_quality == None:
            ad_quality = "256k"
        mp3_name = "{}_{}_{}.mp3".format(name, Id, ad_quality)
        complete_name_file = save_path + mp3_name
        value = "Android"
        write_os(chat_id, user, value)
        try:
            if path.exists(video_file):
                os.remove(video_file)
            if path.exists(title_file):
                os.remove(title_file)
            if path.exists(mp3_name):
                os.rename('/home/javialonso/BOT/' + mp3_name,
                          complete_name_file)
            key_fen(bot, update, chat_id)
        except PermissionError:
            key_fen(bot, update, chat_id)
    elif value == "lang":
        bot.editMessageText(text="Actualizando preferencias de idioma...",
                            chat_id=chat_id,
                            message_id=message_id)
        key_l(bot, update, chat_id)
    elif value == "langen":
        bot.editMessageText(text="Updating language preferences...",
                            chat_id=chat_id,
                            message_id=message_id)
        key_l2(bot, update, chat_id)
    elif value == "os":
        bot.editMessageText(
            text="Actualizando preferencias de sistema operativo...",
            chat_id=chat_id,
            message_id=message_id)
        key_os(bot, update, chat_id)
    elif value == "osen":
        bot.editMessageText(text="Updating operative system preferences...",
                            chat_id=chat_id,
                            message_id=message_id)
        key_osen(bot, update, chat_id)
    elif value == "droid":
        bot.editMessageText(
            text=
            "Preferencias actualizadas correctamente...\n\nUsa /preferences para cambiarlas en cualquier momento",
            chat_id=chat_id,
            message_id=message_id)
        value = "Android"
        write_os(chat_id, user, value)
    elif value == "droiden":
        bot.editMessageText(
            text=
            "Preferences updated correctly...\n\nUse /preferences for changing them whenever you want",
            chat_id=chat_id,
            message_id=message_id)
        value = "Android"
        write_os(chat_id, user, value)
    elif value == "ios":
        bot.editMessageText(
            text=
            "Preferencias actualizadas correctamente...\n\nUsa /preferences para cambiarlas en cualquier momento",
            chat_id=chat_id,
            message_id=message_id)
        value = "iOS"
        write_os(chat_id, user, value)
    elif value == "iosen":
        bot.editMessageText(
            text=
            "Preferences updated correctly...\n\nUse /preferences for changing them whenever you want",
            chat_id=chat_id,
            message_id=message_id)
        value = "iOS"
        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 them 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 them 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 them whenever you want",
                chat_id=chat_id,
                message_id=message_id)
        value = "320k"
        set_audio(chat_id, value)
Beispiel #30
0
                        required=True)
    parser.add_argument('--input-db', help='Input process list', required=True)
    parser.add_argument('--input-dat',
                        help='Input ciphertext folder',
                        required=True)
    parser.add_argument('--output',
                        help='Output keys folder for individual files',
                        required=True)
    parser.add_argument('--output-db',
                        help='Output database file',
                        required=True)
    parser.add_argument('--cores', help='Number of cores to use', default=None)

    args = parser.parse_args()

    db = database.read_database(args.input_db)
    process_list = json.load(open(args.input_list))

    if not os.path.exists(args.output):
        os.makedirs(args.output)

    bucket = []
    for fileinfo in process_list:
        input_dat = os.path.join(args.input_dat,
                                 fileinfo['filename'].upper() + ".DAT")
        output_key = os.path.join(args.output, fileinfo['filename'] + ".json")

        if 'sha1' not in fileinfo:
            fileinfo['sha1'] = get_sha1(input_dat)

        sha1 = fileinfo['sha1']
Beispiel #31
0
def echo(bot, update):
    texto1 = update.message['text']
    chat_id = update.message.chat_id
    message_id = update.message.message_id
    name = update.message.from_user['first_name']
    user = unidecode(name)
    command = unidecode(texto1)
    print("\n\tTexto recibido: ", command)
    if read_database(chat_id) == None:
        bot.sendMessage(
            chat_id,
            text=
            "Antes de continuar, debes actualizar tus preferencias de idioma\n\nBefore you continue, you have to update your language preferences"
        )
        key_l(bot, update)
    elif command == 'Al descargar':  # This checks if the message was from keyboards in function 'errores.py' and assigns a value for redirecting them to 'botones.py'
        value = 'Ed'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Otro...":
        value = 'O'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Archivo vacio (0.00 Bytes)":
        value = 'V'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "El video no puede ser obtenido":
        value = 'U'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Descarga muy lenta":
        value = 'S'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Error al buscar la cancion":
        value = 'fi'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Mostrar todos los errores":
        value = 'mn'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Otro error no registrado":
        value = 'LK'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "El bot no hace nada":
        value = 'Z'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "While downloading":
        value = 'Eden'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Other...":
        value = 'Oen'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Empty file (0.00 Bytes)":
        value = 'Ven'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Video can't be downloaded":
        value = 'Uen'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Downloading very slowly":
        value = 'Sen'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Error while searching the song":
        value = 'fien'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Show all registered errors":
        value = 'mnen'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Another error not registered":
        value = 'LKen'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "The bot is not responding":
        value = 'Zen'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif 'es' in read_database(chat_id):
        print(
            "\n-----------------------------------------------------------------------------------------------------------------"
        )
        print("Debug [1]")
        print(
            "-----------------------------------------------------------------------------------------------------------------"
        )
        try:
            query0 = re.search("(?P<url>https?://[^\s]+)", command).group(
                "url"
            )  # It gets the first URL from message (if exists. Else, raises "AtributteError")
            Id = get_yt_video_id(query0)
            try:
                print("\tEjecutando descarga directa...")
                print("\tID: ", Id)
                if (Id == None):
                    raise IndexError(
                        'El enlace proporcionado no tiene un formato conocido, o no contiene el ID del vídeo, o no es un enlace de YouTube'
                    )
                else:
                    stndr_yt = "http://youtube.com/watch?v="
                    title1 = getVidTitle(Id, chat_id, bot, update)
                    title_file = "title_{}.txt".format(chat_id)
                    video_file = "url_{}.txt".format(chat_id)
                    url2 = "https://www.googleapis.com/youtube/v3/videos?id={}&part=contentDetails&key={}".format(
                        Id, API)
                    print("\tURL API (2): ", url2)
                    datas = urlopen(url2).read()
                    json_data2 = json.loads(datas)
                    length = json_data2["items"][0]['contentDetails'][
                        'duration']
                    print("\tDuración (ISO): ", length)
                    dur = isodate.parse_duration(length)
                    print("\tDuración: ", dur)
                    durS = dur.total_seconds()
                    print("\tDuración en segundos: ", durS)
                    file = open(video_file, 'w')
                    yt_url = "https://youtube.com/watch?v={}".format(Id)
                    file.write(yt_url)
                    file.close()
                    file = open(title_file, 'w')
                    file.write(title1)
                    file.close()
                    if (durS >= 5400):
                        bot.sendMessage(
                            chat_id,
                            "La duración de la canción/vídeo elegido es demasiado larga (más de una hora y media). La descarga se cancela"
                        )
                        if path.exists(video_file):
                            os.remove(video_file)
                        if path.exists(title_file):
                            os.remove(title_file)
                    else:
                        bot.sendMessage(chat_id,
                                        text="_Comenzando la descarga..._",
                                        parse_mode=telegram.ParseMode.MARKDOWN)
                        time.sleep(1)
                        sender(bot, update, chat_id, user)
            except IndexError:
                print(
                    "<<<<< IndexError al obtener información sobre el enlace (no existente) >>>>>"
                )
                bot.sendMessage(
                    chat_id,
                    text=
                    "El enlace que nos has proporcionado no se corresponde con ningún vídeo.\n\nRevisa que está escrito correctamente o utiliza el bot @vid para buscar el vídeo (escribe /vid para saber cómo utilizarlo)"
                )
        except AttributeError:  # The message is not containing an URL. So it's simple text message (query = command)
            query = command
            try:
                print("\tEjecutando búsqueda...")
                Id = getVidId(query, chat_id, bot, update)
                url2 = "https://www.googleapis.com/youtube/v3/videos?id={}&part=contentDetails&key={}".format(
                    Id, API)
                url_title = "https://www.googleapis.com/youtube/v3/videos?id={}&part=snippet&key={}".format(
                    Id, API)
                print("\tURL de la api: ", url2)
                datas = urlopen(url2).read()
                json_data2 = json.loads(datas)
                length = json_data2["items"][0]['contentDetails']['duration']
                data_t = urlopen(url_title).read()
                json_title = json.loads(data_t)
                title = json_title["items"][0]["snippet"]["title"]
                print("\tDuración (ISO): ", length)
                dur = isodate.parse_duration(length)
                print("\tDuración: ", dur)
                durS = dur.total_seconds()
                print("\tDuración en segundos: ", durS)
                if (durS >= 5400):
                    bot.sendMessage(
                        chat_id,
                        "Aquí tienes la URL del vídeo encontrado: http://youtube.com/watch?v="
                        + Id + "")
                    bot.sendMessage(
                        chat_id,
                        "La duración del vídeo es demasiado larga (más de una hora y media).\n\nLa descarga se cancela"
                    )
                else:
                    title_prev = title.translate(
                        {ord(c): None
                         for c in ':"/\!@#$'})
                    title_prev2 = title_prev.replace("." or ",", " ")
                    title1 = title_prev2.translate({
                        ord('á'): 'a',
                        ord('é'): 'e',
                        ord('í'): 'i',
                        ord('ó'): 'o',
                        ord('ú'): 'u',
                        ord('ñ'): 'n'
                    })
                    title_file = "title_{}.txt".format(chat_id)
                    video_file = "url_{}.txt".format(chat_id)
                    file = open(title_file, 'w')
                    file.write(title1)
                    file.close()
                    file = open(video_file, 'w')
                    yt_url = "https://youtube.com/watch?v={}".format(Id)
                    file.write(yt_url)
                    file.close()
                    bot.sendMessage(
                        chat_id,
                        "La canción encontrada es esta: http://youtube.com/watch?v="
                        + Id + " ")
                    key_a(bot, update)
            except ValueError:
                print(
                    "\n\t<<<<<< Error al buscar el vídeo (no encontrado) | ID: ",
                    chat_id, ">>>>>>\n")
                bot.sendMessage(
                    chat_id,
                    "No hemos encontrado ninguna canción en base a los términos de búsqueda especificados.\n\nPrueba a escribir sin tildes o busca tu vídeo con   @vid   directamente desde el teclado"
                )
            except IndexError:
                print(
                    "\n<<<<<<\"IndexError\" heredado de la función anterior (getVidId) | ID: ",
                    chat_id, ">>>>>>\n"
                )  # When IndexError is raised in 'getVidId', main function raises too. So as for this, we set it to "IndexError inherited from getVidId"
    elif 'en' in read_database(chat_id):
        print(
            "\n-----------------------------------------------------------------------------------------------------------------"
        )
        print("Debug [1]")
        print(
            "-----------------------------------------------------------------------------------------------------------------"
        )
        try:
            query0 = re.search("(?P<url>https?://[^\s]+)", command).group(
                "url"
            )  # As the bot is multi-langauge, two functions are needed
            Id = get_yt_video_id(query0)
            try:
                print("\tEjecutando descarga directa...")
                print("\tID: ", Id)
                if (Id == None):
                    raise IndexError(
                        'El enlace proporcionado no tiene un formato conocido, o no contiene el ID del vídeo, o no es un enlace de YouTube'
                    )
                else:
                    stndr_yt = "http://youtube.com/watch?v="
                    title1 = getVidTitle(Id, chat_id, bot, update)
                    url2 = "https://www.googleapis.com/youtube/v3/videos?id={}&part=contentDetails&key={}".format(
                        Id, API)
                    print("\tURL API (2): ", url2)
                    datas = urlopen(url2).read()
                    json_data2 = json.loads(datas)
                    length = json_data2["items"][0]['contentDetails'][
                        'duration']
                    print("\tDuración (ISO): ", length)
                    dur = isodate.parse_duration(length)
                    print("\tDuración: ", dur)
                    durS = dur.total_seconds()
                    print("\tDuración en segundos: ", durS)
                    title_file = "title_{}.txt".format(chat_id)
                    video_file = "url_{}.txt".format(chat_id)
                    file = open(title_file, 'w')
                    file.write(title1)
                    file.close()
                    file = open(video_file, 'w')
                    yt_url = "https://youtube.com/watch?v={}".format(Id)
                    file.write(yt_url)
                    file.close()
                    if (durS >= 5400):
                        bot.sendMessage(
                            chat_id,
                            "Video lenght is too long (more than 1 hour and a half). Download cancelled"
                        )
                        if path.exists(video_file):
                            os.remove(video_file)
                        if path.exists(title_file):
                            os.remove(title_file)
                    else:
                        bot.sendMessage(chat_id,
                                        text="_Starting download..._",
                                        parse_mode=telegram.ParseMode.MARKDOWN)
                        time.sleep(1)
                        sender(bot, update, chat_id, user)
            except IndexError:
                print(
                    "<<<<< IndexError al obtener información sobre el enlace (no existente) >>>>>"
                )
                bot.sendMessage(
                    chat_id,
                    text=
                    "The link you provided does not refer to any videos.\n\nCheck if it's writed correctly or use the bot @vid to search the video (type /vid to learn how to use it)"
                )
        except AttributeError:
            query = command
            try:
                print("\tEjecutando búsqueda...")
                Id = getVidId(query, chat_id, bot, update)
                url2 = "https://www.googleapis.com/youtube/v3/videos?id={}&part=contentDetails&key={}".format(
                    Id, API)
                url_title = "https://www.googleapis.com/youtube/v3/videos?id={}&part=snippet&key={}".format(
                    Id, API)
                print("\tURL de la api: ", url2)
                datas = urlopen(url2).read()
                json_data2 = json.loads(datas)
                length = json_data2["items"][0]['contentDetails']['duration']
                data_t = urlopen(url_title).read()
                json_title = json.loads(data_t)
                title = json_title["items"][0]["snippet"]["title"]
                print("\tDuración (ISO): ", length)
                dur = isodate.parse_duration(length)
                print("\tDuración: ", dur)
                durS = dur.total_seconds()
                print("\tDuración en segundos: ", durS)
                if (durS >= 5400):
                    bot.sendMessage(
                        chat_id,
                        "Here is the URL of the video found: http://youtube.com/watch?v="
                        + Id + "")
                    bot.sendMessage(
                        chat_id,
                        "Video lenght is too long (more than 1 hour and a half). Download cancelled"
                    )
                else:
                    title_prev = title.translate(
                        {ord(c): None
                         for c in ':"/\!@#$'})
                    title_prev2 = title_prev.replace("." or ",", " ")
                    title1 = title_prev2.translate({
                        ord('á'): 'a',
                        ord('é'): 'e',
                        ord('í'): 'i',
                        ord('ó'): 'o',
                        ord('ú'): 'u',
                        ord('ñ'): 'n'
                    })
                    title_def = unidecode(title1)
                    title_file = "title_{}.txt".format(chat_id)
                    video_file = "url_{}.txt".format(chat_id)
                    file = open(title_file, 'w')
                    file.write(title_def)
                    file.close()
                    file = open(video_file, 'w')
                    yt_url = "https://youtube.com/watch?v={}".format(Id)
                    file.write(yt_url)
                    file.close()
                    bot.sendMessage(
                        chat_id,
                        "The found song is this: http://youtube.com/watch?v=" +
                        Id + " ")
                    key_aen(bot, update)
            except ValueError:
                print(
                    "\n\t<<<<<< Error al buscar el vídeo (no encontrado) | ID: ",
                    chat_id, ">>>>>>\n")
                bot.sendMessage(
                    chat_id,
                    "We did not find any songs based on the specified search terms.\n\nTry typing without titles or searching your video with  @vid  directly from the keyboard"
                )
            except IndexError:
                print(
                    "\n<<<<<<\"IndexError\" heredado de la función anterior (getVidId) | ID: ",
                    chat_id, ">>>>>>\n")