Exemple #1
0
def send_stations_status(chat_id, stations):
    """
    Gets status of given stations in parallel and sends it to the user

    :param chat_id: Telegram chat id
    :param stations: list of stations identifiers
    """
    stations_status = Manager().dict()
    processes = []
    for station_index, station_id in enumerate(stations):
        # Start a process per station and add it to processes list
        process = Process(target=get_station_multiproc,
                          args=(station_id, chat_id, stations_status,
                                station_index))
        process.start()
        processes.append(process)
    # Wait until all processes have stopped
    for process in processes:
        process.join()
    if stations_status:
        # Get stations status sorted by index
        stations_status = [
            stations_status[key] for key in sorted(stations_status.keys())
        ]
        get_bot().send_message(chat_id=chat_id,
                               text=prepare_stations_status_response(
                                   chat_id, stations_status))
Exemple #2
0
def remove_group_command(chat_id, text):
    """
    Sends a keyboard to the user with the name of all her groups to choose the one to remove

    :param chat_id: Telegram chat id
    :param text: remove group command
    """
    db_connection = DatabaseConnection()
    logger.info('COMMAND {}: chat_id={}'.format(text, chat_id))
    groups = grouper(db_connection.get_groups_names(chat_id))
    buttons_lines = []
    for groups_line in groups:
        buttons_lines.append([
            InlineKeyboardButton(group_name,
                                 callback_data='{}_{}'.format(
                                     REMOVE_GROUP_CALLBACK, group_name))
            for group_name in groups_line if group_name
        ])
    buttons_lines.append([
        InlineKeyboardButton(
            tr('removegroup_cancel', chat_id),
            callback_data='{}_unused'.format(REMOVE_CANCEL_CALLBACK))
    ])
    keyboard = InlineKeyboardMarkup(buttons_lines)
    get_bot().send_message(chat_id=chat_id,
                           text=tr('removegroup_name', chat_id),
                           reply_markup=keyboard)
    db_connection.close()
Exemple #3
0
def bicingbot_commands(chat_id, text):
    """
    Handles bicingbot specific commands and sends the corresponding messages to the user

    :param chat_id: Telegram chat id
    :param text: command to be executed
    """
    text = normalize_command_name(text)
    command_method = get_command_method(text)
    if get_group_status(chat_id) > GROUP_STATUS_INIT:
        newgroup_command(chat_id, text)
    elif command_method:
        command_method(chat_id, text)
    elif is_integer(text):
        logger.info('COMMAND /station {}: chat_id={}'.format(text, chat_id))
        send_stations_status(chat_id, [int(text)])
    else:
        db_connection = DatabaseConnection()
        if text in db_connection.get_groups_names(chat_id):
            logger.info('COMMAND /group {}: chat_id={}'.format(text, chat_id))
            group = db_connection.get_group(chat_id, text)
            send_stations_status(chat_id, group['stations'])
        else:
            logger.info('UNKNOWN COMMAND {}: chat_id={}'.format(text, chat_id))
            get_bot().send_message(chat_id=chat_id,
                                   text=tr('unknown_command', chat_id))
        db_connection.close()
Exemple #4
0
def help_command(chat_id, text):
    """
    Sends help message to the user

    :param chat_id: Telegram chat id
    :param text: command name
    """
    logger.info('COMMAND {}: chat_id={}'.format(text, chat_id))
    get_bot().send_message(chat_id=chat_id,
                           text='\n'.join(tr('help', chat_id)))
Exemple #5
0
def remove_group_cancel(chat_id, callback_query):
    """
    Cancels the removing of the group and sends a confirmation notification

    :param chat_id: Telegram chat id
    :param callback_query: callback query
    """
    message = tr('removegroup_canceled', chat_id)
    get_bot().answer_callback_query(callback_query.id, text=message)
    get_bot().edit_message_text(chat_id=chat_id,
                                text=message,
                                message_id=callback_query.message.message_id)
Exemple #6
0
def language_command(chat_id, text):
    """
    Sends language options

    :param chat_id: Telegram chat id
    :param text: command name
    """
    logger.info('COMMAND {}: chat_id={}'.format(text, chat_id))
    keyboard = InlineKeyboardMarkup([
        [InlineKeyboardButton(lang_value, callback_data='{}_{}'.format(LANGUAGE_CALLBACK, lang_key)) for
         lang_key, lang_value in get_languages().items()]])
    get_bot().send_message(chat_id=chat_id, text=tr('language_choose', chat_id), reply_markup=keyboard)
Exemple #7
0
def update_language(chat_id, language, callback_query):
    """
    Updates user language and sends a confirmation notification

    :param chat_id: Telegram chat id
    :param language: selected language
    :param callback_query: callback query
    """
    languages = get_languages()
    if language in languages.keys():
        db_connection = DatabaseConnection()
        db_connection.add_setting(chat_id=chat_id, setting=LANGUAGE_SETTING, value=language)
        db_connection.close()

        message = tr('language_updated', chat_id).format(languages[language])
        get_bot().answer_callback_query(callback_query.id, text=message)
        get_bot().send_message(chat_id=chat_id, text=message)
Exemple #8
0
def groups_command(chat_id, text):
    """
    Sends a message to the user with the name of all her groups

    :param chat_id: Telegram chat id
    :param text: command name
    """
    logger.info('COMMAND {}: chat_id={}'.format(text, chat_id))
    db_connection = DatabaseConnection()
    groups = db_connection.get_groups_names(chat_id)
    db_connection.close()
    if groups:
        get_bot().send_message(chat_id=chat_id,
                               text=', '.join(
                                   ['/' + group for group in groups]))
    else:
        get_bot().send_message(chat_id=chat_id,
                               text=tr('groups_empty', chat_id))
def set_webhook():
    """
    Sets the BicingBot webhook in its Telegram Bot

    :return: HTTP_RESPONSE with 200 OK status and a status message.
    """
    response = 'Webhook configured'
    if request.url_root.startswith('https'):
        bot_response = get_bot().setWebhook('{}/bicingbot'.format(request.url_root))
        logger.debug(bot_response)
    else:
        response = 'Bad webhook: https url must be provided for webhook'
        logger.warn(response)
    return response
Exemple #10
0
def remove_group(chat_id, group_name, callback_query):
    """
    Removes the group and sends a confirmation notification

    :param chat_id: Telegram chat id
    :param group_name: group name to be removed
    :param callback_query: callback query
    """
    db_connection = DatabaseConnection()
    if group_name not in db_connection.get_groups_names(chat_id):
        get_bot().send_message(chat_id=chat_id,
                               text=tr('removegroup_not_found', chat_id))
    else:
        stations = db_connection.get_group(chat_id, group_name)['stations']
        db_connection.delete_group(chat_id=chat_id, name=group_name)
        message = tr('removegroup_removed', chat_id).format(
            group_name, ', '.join(str(station) for station in stations))
        get_bot().answer_callback_query(callback_query.id, text=message)
        get_bot().edit_message_text(
            chat_id=chat_id,
            text=message,
            message_id=callback_query.message.message_id)
    db_connection.close()
Exemple #11
0
def newgroup_command(chat_id, text):
    """
    Manages the workflow to create a new group.

    :param chat_id: Telegram chat id
    :param text: group command
    """
    group_status = get_group_status(chat_id)
    from bicingbot.commands import send_stations_status, COMMANDS
    db_connection = DatabaseConnection()
    if group_status == GROUP_STATUS_INIT:
        logger.info('COMMAND {}: chat_id={}'.format(text, chat_id))
        if len(db_connection.get_groups_names(chat_id)) < MAX_NUMBER_GROUPS:
            get_bot().send_message(chat_id=chat_id,
                                   text=tr('newgroup_name', chat_id))
            set_group_status(chat_id, GROUP_STATUS_NEWGROUP_NAME)
        else:
            get_bot().send_message(chat_id=chat_id,
                                   text=tr('newgroup_number_groups_limit',
                                           chat_id).format(MAX_NUMBER_GROUPS))
            del_group_status(chat_id)
    elif group_status == GROUP_STATUS_NEWGROUP_NAME:
        if text in COMMANDS['end']['alias']:
            get_bot().send_message(chat_id=chat_id,
                                   text=tr('newgroup_not_created', chat_id))
            del_group_status(chat_id)
        elif not is_valid_group_name(text):
            get_bot().send_message(chat_id=chat_id,
                                   text=tr('newgroup_name_format_error',
                                           chat_id))
        else:
            message = tr('newgroup_stations', chat_id)
            if text in db_connection.get_groups_names(chat_id):
                message = tr('newgroup_name_already_existing',
                             chat_id).format(message.lower())
            GROUPS_CACHE[chat_id]['name'] = text
            get_bot().send_message(chat_id=chat_id, text=message)
            set_group_status(chat_id, GROUP_STATUS_NEWGROUP_STATIONS)
    elif group_status == GROUP_STATUS_NEWGROUP_STATIONS:
        if text in COMMANDS['end']['alias']:
            if GROUPS_CACHE[chat_id]['stations']:
                db_connection.delete_group(chat_id=chat_id,
                                           name=GROUPS_CACHE[chat_id]['name'])
                db_connection.create_group(
                    chat_id=chat_id,
                    name=GROUPS_CACHE[chat_id]['name'],
                    stations=GROUPS_CACHE[chat_id]['stations'])
                get_bot().send_message(
                    chat_id=chat_id,
                    text=tr('newgroup_created',
                            chat_id).format(GROUPS_CACHE[chat_id]['name']))
                send_stations_status(chat_id,
                                     GROUPS_CACHE[chat_id]['stations'])
            else:
                if GROUPS_CACHE[chat_id][
                        'name'] in db_connection.get_groups_names(chat_id):
                    get_bot().send_message(
                        chat_id=chat_id,
                        text=tr('newgroup_not_overwrite',
                                chat_id).format(GROUPS_CACHE[chat_id]['name']))
                else:
                    get_bot().send_message(chat_id=chat_id,
                                           text=tr('newgroup_not_created',
                                                   chat_id))
            del_group_status(chat_id)
        elif is_integer(text):
            if len(GROUPS_CACHE[chat_id]['stations']) < MAX_NUMBER_STATIONS:
                GROUPS_CACHE[chat_id]['stations'].append(int(text))
            else:
                get_bot().send_message(
                    chat_id=chat_id,
                    text=tr('newgroup_number_stations_limit',
                            chat_id).format(MAX_NUMBER_STATIONS))
        else:
            get_bot().send_message(chat_id=chat_id,
                                   text=tr('newgroup_unknown_command',
                                           chat_id))

    db_connection.close()