Example #1
0
def register(bot, update):
    """A user that wants to access private commands must first register"""
    user = update.message.from_user
    user_data_string = _user_to_string(user)
    send_message_to_admin(
        bot,
        f'{user.name} wants to start using AmbroBot\n\n'
        f'User details:\n{user_data_string}',
    )
    update.message.reply_text('✅ Your registration request has been sent.\nPlease wait for approval.. ⏳', quote=False)
Example #2
0
def _add_reminder_job(bot, update, job_queue, job_context, when):
    logger.info(f"Adding job to db..")
    added = add_job_to_db(job_context)
    update.callback_query.answer(text='')
    if added:
        job_queue.run_once(send_notification, when, context=job_context)
        logger.info(f"Job added to job queue and db.")
    else:
        logger.error('Could not save reminder job')
        send_message_to_admin(
            bot, f"Error saving reminder.\n CONTEXT:\n{job_context}\n")

    return added
Example #3
0
def subte_updates_cron(bot, job):
    try:
        status_updates = check_update()
    except Exception:
        logger.exception('An unexpected error ocurred when fetching updates.')
        send_message_to_admin(
            bot,
            'An unexpected error ocurred when requesting subte updates. Please see the logs.'
        )
        return
    if status_updates is None:
        logger.error("The api did not respond with status ok.")
        send_message_to_admin(
            bot,
            'Metrovias api did not respond with status 200. Check it please')
        return

    context = job.context
    logger.info(
        'Checking if subte status has changed..\nSTATUS_UPDATE: %s\nCONTEXT: %s',
        status_updates, context)
    if status_updates != context:
        logger.info('Updating subte status...')
        if not status_updates:
            # There are no incidents to report.
            pretty_update = SUBWAY_STATUS_OK
        else:
            pretty_update = prettify_updates(status_updates)

        bot.send_message(chat_id='@subtescaba', text=pretty_update)
        logger.info('Update message sent to channel')
        try:
            notify_suscribers(bot, status_updates, context)
            logger.info('Suscribers notified of line changes')
        except Exception:
            logger.error("Could not notify suscribers", exc_info=True)

        # Now the context must reflect the new status_updates. Update context with new incidents.
        job.context = status_updates
        logger.info('Context updated with new status updates')

    else:
        logger.info("Subte status has not changed. Not posting new reply.")
Example #4
0
def _send_feedback(bot, update, suggestion):
    user = update.effective_message.from_user.name
    send_message_to_admin(bot, f'💬 Feedback!\n\n{suggestion}\n\nby {user}')
    update.effective_message.reply_text('✅ Feedback sent 🗳', quote=False)
Example #5
0
def youtube_to_mp3(bot, update, args):
    video_url = args[0]

    def ext(f):
        return f'bestaudio[ext={f}]'

    def format_extensions(extens):
        return '/'.join(map(ext, extens))

    try:
        extensions = ('mp3', '3gp', 'aac', 'wav', 'flac', 'm4a')
        ydl_opts = {
            'format': format_extensions(extensions),
            'outtmpl': f'{FILENAME}.%(ext)s',
        }
        logger.info(f'Starting download of {video_url}..')
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.download([video_url])
        logger.info(f'Video downloaded.')

    except Exception:
        logger.error('Audio not downloaded.', exc_info=True)
        update.message.reply_text(f'No audio found for {video_url}')
        return

    # Download was successful, now we must open the audio file
    try:
        logger.info('Reading audio file from local storage')
        file, filename = get_audio_file(extensions)
        update.message.reply_text(f'✅ Archivo descargado. Enviando...')
        bot.send_chat_action(chat_id=update.message.chat_id,
                             action=ChatAction.UPLOAD_AUDIO)
        logger.info(f'Filename: {filename}')
        if file:
            logger.info('Sending file to user')
            update.message.reply_document(document=file)
            update.message.reply_text(
                f'💬 Tip: Podés usar [VLC]({VLC_LINK}) para reproducir el audio 🎶',
                parse_mode='markdown',
                disable_web_page_preview=True)
            file.close()
            logger.info('File sent successfully')
    except NetworkError:
        logger.error('A network error occurred.', exc_info=True)
        update.message.reply_text(
            text=
            '🚀 Hay problemas de conexión en estos momentos. Intentá mas tarde..'
        )
        send_message_to_admin(bot, f'Error mandando {video_url}, {filename}')

    except Exception:
        msg = 'Error uploading file to telegram servers'
        logger.exception(msg), send_message_to_admin(bot, msg)
        update.message.reply_text(text=msg)

    else:
        if filename:
            try:
                # Remove the file we just sent, as the name is hardcoded.
                logger.info(f"Removing file '{filename}'")
                os.remove(filename)
                logger.info('File removed')
            except FileNotFoundError:
                msg = f'Error removing audio file. File not found {filename}'
                logger.error(msg), send_message_to_admin(bot, msg)
            except Exception:
                msg = f"UnknownError removing audio file. '{filename}'"
                logger.error(msg), send_message_to_admin(bot, msg)
Example #6
0
def main():
    # Setup bot
    updater = Updater(os.environ['PYTEL'], user_sig_handler=signal_handler)
    dispatcher = updater.dispatcher

    start_handler = CommandHandler('start', start)

    # Add repeating jobs
    cron_tasks = updater.job_queue
    cron_tasks.run_repeating(subte_updates_cron,
                             interval=5 * MINUTE,
                             first=50 * MINUTE,
                             context={},
                             name=SUBTE_UPDATES_CRON)

    # Load reminders that were lost on bot restart (job_queue is not persistent)
    loaded_reminders = load_reminders(updater.bot, cron_tasks)
    logger.info(f"Recovered {loaded_reminders} reminders")

    #  Associate commands with action.
    dispatcher.add_handler(feedback_receiver)
    dispatcher.add_handler(inline_snippets)
    dispatcher.add_handler(start_handler)
    dispatcher.add_handler(register_user)
    dispatcher.add_handler(show_users_handler)
    dispatcher.add_handler(authorize_handler)
    dispatcher.add_handler(partido_handler)
    dispatcher.add_handler(dolar_handler)
    dispatcher.add_handler(subte_suscriptions)
    dispatcher.add_handler(modify_subte_freq)
    dispatcher.add_handler(subte_desuscriptions)
    dispatcher.add_handler(subte_show_suscribers)
    dispatcher.add_handler(dolar_futuro_handler)
    dispatcher.add_handler(posiciones_handler)
    dispatcher.add_handler(subte_handler)
    dispatcher.add_handler(cartelera_handler)
    dispatcher.add_handler(add_retro_item)
    dispatcher.add_handler(show_retro_details)
    dispatcher.add_handler(expire_retro_command)
    dispatcher.add_handler(pelis)
    dispatcher.add_handler(pelis_alt)
    dispatcher.add_handler(yts_handler)
    dispatcher.add_handler(hoypido_handler)
    dispatcher.add_handler(feriados_handler)
    dispatcher.add_handler(serie_handler)
    dispatcher.add_handler(yt_handler)
    dispatcher.add_handler(yt_handler_alt)
    dispatcher.add_handler(code_handler)
    dispatcher.add_handler(save_snippet_handler)
    dispatcher.add_handler(get_snippet_handler)
    dispatcher.add_handler(snippet_get_command)
    dispatcher.add_handler(show_snippets_handler)
    dispatcher.add_handler(delete_snippet_handler)
    dispatcher.add_handler(remind_me_handler)
    dispatcher.add_handler(tag_all)
    dispatcher.add_handler(show_meetings_handler)
    dispatcher.add_handler(delete_meeting_handler)
    dispatcher.add_handler(hastebin_handler)
    dispatcher.add_handler(tickets_handler)
    dispatcher.add_handler(edit_tag_all)

    # Add callback handlers
    dispatcher.add_handler(serie_callback)
    dispatcher.add_handler(yts_callback_handler)
    dispatcher.add_handler(reminders_callback_handler)
    dispatcher.add_handler(peliculas_callback)

    # Add Conversation handler
    dispatcher.add_handler(msup_conversation)
    dispatcher.add_handler(meeting_conversation)

    # Add generics
    dispatcher.add_handler(callback_handler)
    dispatcher.add_handler(generic_handler)

    # Add error handler
    dispatcher.add_error_handler(error_handler)

    updater.start_polling()
    logger.info('Listening humans as %s..' % updater.bot.username)
    send_message_to_admin(updater.bot, "⚡️ I'm up and running ⚡️️")
    updater.idle()
    logger.info('Bot stopped gracefully')