示例#1
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()
示例#2
0
def start_command(chat_id, text):
    """
    Sends welcome 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('welcome', chat_id) + tr('help', chat_id)))
示例#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()
示例#4
0
def get_station_multiproc(station_id, chat_id, stations_status, station_key):
    """
    Gets station status and returns it in stations_status variable

    :param station_id: id of the station
    :param chat_id: Telegram chat id
    :param stations_status: output dict to put station status
    :param station_key: output dict key
    """
    try:
        stations_status[station_key] = Bicing().get_station(station_id)
    except StationNotFoundError:
        stations_status[station_key] = {
            'error': tr('station_not_found', chat_id).format(station_id)
        }
    except Exception:
        stations_status[station_key] = {
            'error': tr('wrong_station', chat_id).format(station_id)
        }
示例#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)
示例#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)
示例#7
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()
示例#8
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)
示例#9
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))
示例#10
0
def prepare_stations_status_response(chat_id, stations):
    """
    Beautifies stations status output to be rendered in Telegram

    :param chat_id: Telegram chat id
    :param stations: list of stations read from Bicing API
    :return: a str with the complete message
    """
    messages = [Emoji.BICYCLE + ' - ' + Emoji.NO_ENTRY_SIGN]
    for station in stations:
        if 'error' in station:
            messages.append(station['error'])
        else:
            if station['status'] == 1:
                bikes = '{} - {}'.format(pad_number(station['bikes']),
                                         pad_number(station['slots']))
            else:
                bikes = tr('disabled_station', chat_id=chat_id)
            messages.append('{} [{}] {}'.format(
                bikes, station['id'], compact_address(station['streetName'])))
    return '\n'.join(messages)
示例#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()
示例#12
0
def test_translate_default_language():
    assert tr('wrong_station', 1) == STRINGS['es']['wrong_station']
示例#13
0
def test_translate_language(DatabaseConnection):
    DatabaseConnection.return_value = mock.MagicMock()
    DatabaseConnection().get_setting.return_value = 'en'

    assert tr('wrong_station', 1) == STRINGS['en']['wrong_station']