Exemple #1
0
def menu(update, context):
    """
    Process the message and reply with the menu or error messages.

    Todo:
        Reduce complexity!
    """
    frontend_logger.debug('menu called')
    if update.message.text:
        message = update.message.text.lower().replace(
            '@%s' % context.bot.username.lower(), '')
        requested_canteen, requested_date = get_canteen_and_date(message)
        frontend_logger.info('Requested Canteen: %s (%s)' %
                             (requested_canteen, requested_date))
        if requested_date:
            reply = cache.hget(requested_date, requested_canteen)
            if not reply or reply.strip() == '':
                possible_canteens = []
                for canteen, canteen_menu in cache.hscan_iter(
                        requested_date, '*%s*' % requested_canteen):
                    possible_canteens.append((canteen, canteen_menu))
                if len(possible_canteens) == 1:
                    reply = possible_canteens.pop()[1]
                    update.message.reply_text(text=reply,
                                              parse_mode=ParseMode.MARKDOWN,
                                              disable_web_page_preview=True)
                    message_logger.debug('Out: %s' % reply)
                elif len(possible_canteens) > 1:
                    reply = 'Meintest du vielleicht:\n'
                    for canteen in possible_canteens:
                        reply += '\n /%s' % canteen[0]
                    update.message.reply_text(text=reply)
                    message_logger.debug('Out: %s' % reply)
                else:
                    error_message = "\n*Chat*\n```\n%s\n```\n*Message*\n```\n%s\n```\n*User*\n```\n%s\n```" % \
                                    (update.effective_chat, update.effective_message, update.effective_user)
                    send_message_to_admin.delay(error_message)
                    reply = 'Leider kenne ich keinen passenden Speiseplan. ' \
                            'Wenn das ein Fehler ist, wende dich an @ekeih.'
                    update.message.reply_text(text=reply,
                                              parse_mode=ParseMode.MARKDOWN)
                    message_logger.debug('Out: %s' % reply)
            else:
                update.message.reply_text(text=reply,
                                          parse_mode=ParseMode.MARKDOWN,
                                          disable_web_page_preview=True)
                message_logger.debug('Out: %s' % reply)
        else:
            reply = 'Sorry, leider habe ich das Datum nicht verstanden. Probier es doch einmal mit `/%s morgen`, ' \
                    '`/%s dienstag`, `/%s yesterday` oder `/%s next friday`.' % (requested_canteen, requested_canteen,
                                                                                 requested_canteen, requested_canteen)
            update.message.reply_text(text=reply,
                                      parse_mode=ParseMode.MARKDOWN,
                                      disable_web_page_preview=True)
            message_logger.debug('Out: %s' % reply)
Exemple #2
0
def error_handler(_, update, error):
    """
    Handle errors in the dispatcher and decide which errors are just logged and which errors are important enough to
    trigger a message to the admin.
    """
    # noinspection PyBroadException
    try:
        raise error
    except telegram.error.BadRequest:
        frontend_logger.error(error)
        log_error.delay(str(error), 'frontend', 'badrequest')
    except telegram.error.TimedOut:
        frontend_logger.error(error)
        log_error.delay(str(error), 'frontend', 'timeout')
    except:
        error_message = '*Some Frontend Error*\n\n*Update*\n```\n%s\n```\n*Error*\n```\n%s\n```' % (update, error)
        send_message_to_admin.delay(error_message)
        frontend_logger.error(error)
Exemple #3
0
def main():
    """
    The entrypoint for omnbot-frontend. The main function adds all handlers to the telegram dispatcher, informs the
    admin about the startup and runs the dispatcher forever.
    """
    global frontend_fh
    global message_fh
    global cache

    frontend_fh = logging.handlers.TimedRotatingFileHandler('logs/frontend.log', when='midnight', backupCount=60)
    frontend_fh.setLevel(logging.DEBUG)
    frontend_fh.setFormatter(formatter)
    frontend_logger.addHandler(frontend_fh)

    message_fh = logging.handlers.TimedRotatingFileHandler('logs/messages.log', when='midnight', backupCount=60)
    message_fh.setLevel(logging.DEBUG)
    message_fh.setFormatter(formatter)
    message_logger.addHandler(message_fh)

    redis_host = os.environ.get('OMNOMNOM_REDIS_HOST') or 'localhost'
    frontend_logger.debug('Redis host: %s' % redis_host)

    cache = redis.Redis(host=redis_host, decode_responses=True)

    token = os.environ.get('OMNOMNOM_AUTH_TOKEN')
    if not token:
        frontend_logger.error('You have to set your auth token as environment variable in OMNOMNOM_AUTH_TOKEN')
        sys.exit()

    admin = os.environ.get('OMNOMNOM_ADMIN')
    if not admin:
        frontend_logger.error('You have to specify an Admin account.')
        sys.exit()
    frontend_logger.debug('Admin ID: %s' % admin)

    updater = Updater(token=token)
    dispatcher = updater.dispatcher

    # Add an error handler to log and report errors
    dispatcher.add_error_handler(error_handler)

    # React to /start, /about and /help messages
    dispatcher.add_handler(CommandHandler('start', help_message), 2)
    dispatcher.add_handler(CommandHandler('about', about), 2)
    dispatcher.add_handler(CommandHandler('help', help_message), 2)

    # Send typing action and log incoming messages
    dispatcher.add_handler(RegexHandler('.*', send_typing_action), 0)
    dispatcher.add_handler(RegexHandler('.*', log_incoming_messages), 1)

    # Handle all messages beginning with a '/'
    dispatcher.add_handler(RegexHandler('/.*', menu), 2)

    # Handle normal text messages that are no reply and answer with a help_message
    dispatcher.add_handler(MessageHandler(Filters.text & (~ Filters.reply), help_message), 2)

    # Handle group member changes
    dispatcher.add_handler(MessageHandler(Filters.group & (~ Filters.reply), group_message_handler), 3)

    send_message_to_admin.delay('*Bot Started*\n\nID: %s\nFirstname: %s\nLastname: %s\nUsername: %s\nName: %s' %
                                (updater.bot.id, updater.bot.first_name, updater.bot.last_name,
                                 updater.bot.username, updater.bot.name))

    frontend_logger.info('Start polling')
    updater.start_polling()
    updater.idle()