Exemple #1
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 #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 database_connection():
    config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'conf')
    os.remove(os.path.join(config_path, 'bicingbot_test.db'))
    DatabaseMigration(database='bicingbot_test.db').create_schema()
    conn = DatabaseConnection(database='bicingbot_test.db')
    yield conn
    conn.close()
Exemple #4
0
def get_language(chat_id):
    """
    Retrieves the language configured by the user, if exists. Otherwise, None is returned.
    :param chat_id: Telegram chat id
    :return: chat language
    """
    db_connection = DatabaseConnection()
    language = db_connection.get_setting(chat_id=chat_id, setting=LANGUAGE_SETTING)
    db_connection.close()

    return language
Exemple #5
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 #6
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))
class DatabaseMigration(object):
    """
    Updates a database schema
    """
    def __init__(self, database='bicingbot.db'):
        self.connection = DatabaseConnection(database).connection

    def create_schema(self):
        """
        Creates a complete schema of the database
        """
        self.create_initial_schema()
        self.update_schema_table_settings()
        self.connection.close()

    def create_initial_schema(self):
        """
        Creates the first schema of the database
        """
        cursor = self.connection.cursor()

        # Create groups table
        cursor.execute('''CREATE TABLE groups (chat_id INTEGER NOT NULL,
                                               name TEXT NOT NULL,
                                               station_id INTEGER NOT NULL,
                                               created_date DATETIME DEFAULT CURRENT_TIMESTAMP,
                                               PRIMARY KEY (chat_id, name, station_id))'''
                       )
        self.connection.commit()

    def update_schema_table_settings(self):
        """
        Update the schema of the database adding settings table.
        """
        cursor = self.connection.cursor()

        # Create groups table
        cursor.execute('''CREATE TABLE settings (chat_id INTEGER NOT NULL,
                                                 setting TEXT NOT NULL,
                                                 value INTEGER NOT NULL,
                                                 created_date DATETIME DEFAULT CURRENT_TIMESTAMP,
                                                 PRIMARY KEY (chat_id, setting))'''
                       )
        self.connection.commit()
Exemple #8
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 #9
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()
Exemple #10
0
def check_connection():
    conn = DatabaseConnection(database='bicingbot_test.db')
    yield conn
    conn.close()