Example #1
0
def end_of_settings(update, context, settings_type):
    query = QueryBuffer().get_query(update.callback_query.message.message_id)
    # query looks like: settings_private,username,notify_participation/notify_vote/
    # or: settings_group,title,notify_not_admin/notify_unauthorized
    if "settings" in ps.parse_csv_to_array(query)[0]:
        to_set = ps.parse_csv_to_array(query)[-1].split('/')[:-1]
        to_unset = []
        if ps.parse_csv_to_array(query)[0] == "settings_private":
            possible_settings = ['notify_participation', 'notify_vote']
            table = "settings"
        else:  # ps.parse_csv_to_array(query)[0] == "settings_group":
            possible_settings = ['notify_not_admin', 'notify_unauthorized']
            table = "group_settings"
        for _ in possible_settings:
            if _ not in to_set:
                to_unset.append(_)
        who = ps.parse_csv_to_array(query)[1]
        dbf.update_settings(table, who, to_set, to_unset)
        context.bot.send_message(
            chat_id=update.callback_query.message.chat_id,
            text="Okay, ich habe mir die Einstellungen vermerkt.",
            reply_markup=ReplyKeyboardRemove())
        shrink_keyboard(update, context, "Einstellungen angepasst.")
    else:
        pass
    QueryBuffer().clear_query(update.callback_query.message.message_id)
Example #2
0
def handle_category(update, context):
    update.callback_query.answer()
    category = update.callback_query.data.split(";")[1]
    if category == "none":
        end_of_categories(update, context, no_category=True)
    elif category == "stop":
        QueryBuffer().clear_query(update.callback_query.message.message_id)
        context.bot.send_message(chat_id=update.callback_query.message.chat_id,
                                 text='Okay, hier ist nichts passiert.',
                                 reply_markup=ReplyKeyboardRemove())
        shrink_keyboard(update, context, "Abbruch.")
    elif category == "done":
        end_of_categories(update, context)
    elif category == "IGNORE":
        pass
    else:  # we actually got a category, now register it
        if update.callback_query.data.split(";")[2] == "SET":
            query = QueryBuffer().get_query(
                update.callback_query.message.message_id) + category + "/"
            categories_so_far = ps.parse_csv_to_array(query)[-1].split(
                '/')[:-1]  # last one is empty since set ends on /
            QueryBuffer().edit_query(update.callback_query.message.message_id,
                                     query)
            # change keyboard layout
            try:
                context.bot.edit_message_text(
                    text=update.callback_query.message.text,
                    chat_id=update.callback_query.message.chat_id,
                    message_id=update.callback_query.message.message_id,
                    reply_markup=generate_categories(
                        pressed=categories_so_far))
            except BadRequest:
                pass
        elif update.callback_query.data.split(";")[2] == "UNSET":
            query = QueryBuffer().get_query(
                update.callback_query.message.message_id)
            query_csv = ps.parse_csv_to_array(query)
            categories_so_far = query_csv[-1].split('/')[:-1]
            categories_so_far.remove(category)
            categories_string = '/'.join(categories_so_far)
            if len(categories_string) > 0:
                categories_string += '/'
            new_query = ps.parse_array_to_csv(
                query_csv[:-1]) + ',' + categories_string
            QueryBuffer().edit_query(update.callback_query.message.message_id,
                                     new_query)
            # change keyboard layout
            try:
                context.bot.edit_message_text(
                    text=update.callback_query.message.text,
                    chat_id=update.callback_query.message.chat_id,
                    message_id=update.callback_query.message.message_id,
                    reply_markup=generate_categories(
                        pressed=categories_so_far))
            except BadRequest:
                pass
Example #3
0
def end_of_categories(update, context, no_category=False):
    query = QueryBuffer().get_query(update.callback_query.message.message_id)
    query_csv = ps.parse_csv_to_array(query)
    categories = query_csv[-1].split('/')[:-1]
    # remove categories from query buffer now
    uuid = ps.generate_uuid_32()
    query = ps.parse_array_to_csv(query_csv[:-1]) + "," + uuid

    if query_csv[0] == "new_game":
        if no_category:
            try:
                dbf.add_game_into_db(
                    ps.parse_csv_to_array(ps.remove_first_string(query)))
                # dbf.add_game_into_db(ps.parse_values_from_query(
                #                         ps.remove_first_string(query)))
            except IntegrityError:
                context.bot.send_message(
                    chat_id=update.callback_query.message.chat_id,
                    text="Wusste ich doch: Das Spiel hast du schon "
                    "einmal eingetragen. Viel Spaß noch damit!",
                    reply_markup=ReplyKeyboardRemove())
                inline_text = "Du wolltest das Spiel " + query_csv[
                    2] + " hinzufügen."
                shrink_keyboard(update, context, inline_text)
                return
        else:
            try:
                dbf.add_game_into_db(ps.parse_csv_to_array(
                    ps.remove_first_string(query)),
                                     cats=categories,
                                     uuid=uuid)
                # dbf.add_game_into_db(ps.parse_values_from_query(
                #                     ps.remove_first_string(query)),
                #                     cats=categories,
                #                     uuid=uuid)
            except IntegrityError:
                context.bot.send_message(
                    chat_id=update.callback_query.message.chat_id,
                    text="Wusste ich doch: Das Spiel hast du schon "
                    "einmal eingetragen. Viel Spaß noch damit!",
                    reply_markup=ReplyKeyboardRemove())
                inline_text = "Du wolltest das Spiel " + query_csv[
                    2] + " hinzufügen."
                shrink_keyboard(update, context, inline_text)
                return
        context.bot.send_message(chat_id=update.callback_query.message.chat_id,
                                 text="Okay, das Spiel wurde hinzugefügt \\o/",
                                 reply_markup=ReplyKeyboardRemove())
        inline_text = "Du hast das Spiel " + query_csv[2] + " hinzugefügt."
        shrink_keyboard(update, context, inline_text)
    else:
        pass
    QueryBuffer().clear_query(update.callback_query.message.message_id)
Example #4
0
 def add_with_query(self, reply_to_id, reply_type, query):
     where = self.types_to_indices[reply_type]
     if len(self.message_IDs[where]
            ) >= 100:  # maybe a 100x100 matrix is too big? no idea...
         self.message_IDs[where] = self.message_IDs[where][50:]
     self.message_IDs[where].append(reply_to_id)
     QueryBuffer().add(reply_to_id, query)
Example #5
0
def end_of_household(update, context):
    query = QueryBuffer().get_query(update.callback_query.message.message_id)
    # query looks like: household,username,member1/member2
    query_csv = ps.parse_csv_to_array(query)
    members = query_csv[-1].split('/')[:-1]
    if "household" in query_csv[0]:
        household = [query_csv[1]] + members
        dbf.add_household(household)
        context.bot.send_message(chat_id=update.callback_query.message.chat_id,
                                 text="Okay, ich weiß Bescheid.",
                                 reply_markup=ReplyKeyboardRemove())
        shrink_label = " ".join(household)
        shrink_keyboard(update, context, shrink_label)
        if LogToMessageFilter().ask_chat_type == "private":
            update.message.bot.send_message(
                chat_id=update.callback_query.message.chat_id,
                text=
                'Hey, soll ich meine Debug-Nachrichten hier rein schicken?',
                reply_markup=generate_debug())
    else:
        pass
    QueryBuffer().clear_query(update.callback_query.message.message_id)
Example #6
0
def einstellungen(update, context):
    if check_user(update.message.chat_id):
        if "group" in update.message.chat.type:
            init_settings = []
            msg = context.bot.send_message(update.message.chat_id,
                                           'Ändert hier die Gruppeneinstellungen. '
                                           'Bei welchen Problemen soll ich euch '
                                           'eine Warnung senden?',
                                           reply_markup=generate_settings(
                                                "settings_group",
                                                first=True,
                                                who=update.message.chat_id,
                                                init_array=init_settings))
            query = "settings_group," + str(update.message.chat_id) + ","
            # init_settings was initialised in generate_settings
            for init_val in init_settings:
                query = query + init_val + "/"
            QueryBuffer().add(msg.message_id, query)
        elif "private" in update.message.chat.type:
            init_settings = []
            msg = context.bot.send_message(update.message.chat_id,
                                           'Ändere hier deine Einstellungen. '
                                           'Bei welchen Ereignissen soll ich '
                                           'dich benachrichtigen?',
                                           reply_markup=generate_settings(
                                                "settings_private",
                                                first=True,
                                                who=update.message.from_user.username,
                                                init_array=init_settings))
            query = "settings_private," + update.message.from_user.username + ","
            # init_settings was initialised in generate_settings
            for init_val in init_settings:
                query = query + init_val + "/"
            QueryBuffer().add(msg.message_id, query)
    else:
        update.message.reply_text('Bitte authentifiziere dich zunächst '
                                  'mit /key.')
Example #7
0
def game_players(update):
    if "/stop" in update.message.text:
        ForceReplyJobs().clear_query(
            update.message.reply_to_message.message_id)
        update.message.reply_text('Okay, hier ist nichts passiert.',
                                  reply_markup=ReplyKeyboardRemove())
    else:
        query = ForceReplyJobs().get_query(
            update.message.reply_to_message.message_id
        ) + "," + update.message.text + ","
        msg = update.message.reply_text(
            'In welche Kategorien passt ' + ps.parse_csv_to_array(query)[2] +
            ' am besten?\n'
            'Wähle so viele, wie du willst, und drücke dann '
            'auf \'Fertig\'.\n'
            'Wenn du keine Kategorie angeben möchtest, drücke '
            'auf \'Keine Angabe\'.',
            reply_markup=generate_categories(first=True))
        ForceReplyJobs().clear_query(
            update.message.reply_to_message.message_id)
        # not adding a new ForceReply because this happens inline
        QueryBuffer().add(msg.message_id, query)
def bulk_insert(graph, host, port, password, nodes, nodes_with_label,
                relations, relations_with_type, separator, enforce_schema,
                skip_invalid_nodes, skip_invalid_edges, quote, max_token_count,
                max_buffer_size, max_token_size):
    if sys.version_info[0] < 3:
        raise Exception("Python 3 is required for the RedisGraph bulk loader.")

    if not (any(nodes) or any(nodes_with_label)):
        raise Exception("At least one node file must be specified.")

    start_time = timer()

    # If relations are being built, we must store unique node identifiers to later resolve endpoints.
    store_node_identifiers = any(relations) or any(relations_with_type)

    # Initialize configurations with command-line arguments
    config = Config(max_token_count, max_buffer_size, max_token_size,
                    enforce_schema, skip_invalid_nodes, skip_invalid_edges,
                    separator, int(quote), store_node_identifiers)

    # Attempt to connect to Redis server
    try:
        client = redis.StrictRedis(host=host, port=port, password=password)
    except redis.exceptions.ConnectionError as e:
        print("Could not connect to Redis server.")
        raise e

    # Attempt to verify that RedisGraph module is loaded
    try:
        module_list = client.execute_command("MODULE LIST")
        if not any(b'graph' in module_description
                   for module_description in module_list):
            print("RedisGraph module not loaded on connected server.")
            sys.exit(1)
    except redis.exceptions.ResponseError:
        # Ignore check if the connected server does not support the "MODULE LIST" command
        pass

    # Verify that the graph name is not already used in the Redis database
    key_exists = client.execute_command("EXISTS", graph)
    if key_exists:
        print(
            "Graph with name '%s', could not be created, as Redis key '%s' already exists."
            % (graph, graph))
        sys.exit(1)

    query_buf = QueryBuffer(graph, client, config)

    # Read the header rows of each input CSV and save its schema.
    labels = parse_schemas(Label, query_buf, nodes, nodes_with_label, config)
    reltypes = parse_schemas(RelationType, query_buf, relations,
                             relations_with_type, config)

    process_entities(labels)
    process_entities(reltypes)

    # Send all remaining tokens to Redis
    query_buf.send_buffer()

    end_time = timer()
    query_buf.report_completion(end_time - start_time)
Example #9
0
 def edit_query(self, reply_to_id, query):
     QueryBuffer().edit_query(reply_to_id, query)
Example #10
0
 def clear_query(self, reply_to_id):
     QueryBuffer().clear_query(reply_to_id)
Example #11
0
 def get_query(self, reply_to_id):
     return QueryBuffer().get_query(reply_to_id)
Example #12
0
def auth(update):
    config = configparser.ConfigParser()
    config_path = os.path.dirname(os.path.realpath(__file__))
    config.read(os.path.join(config_path, "config.ini"))
    passphrase = config['Authentication']['password']

    if update.message.text == passphrase:
        try:
            update.message.bot.delete_message(update.message.chat_id,
                                              update.message.message_id)
        except BadRequest:
            handle_bot_not_admin(update.message.bot, update.message.chat_id)
        if not dbf.check_user(update.message.chat_id):
            if update.message.chat_id > 0:
                dbf.add_user_auth(update.message.chat_id,
                                  name=update.message.from_user.username)
                try:
                    msg = update.message.bot.send_message(
                        chat_id=update.message.chat_id,
                        text='Super! Wir dürfen jetzt miteinander reden. '
                        'Noch eine Frage: Wohnst du vielleicht mit einem '
                        '(oder mehreren) '
                        'der Gruppenmitglieder zusammen? '
                        'Wenn ja, wähle unten den (die) '
                        'entsprechenden Alias(e)! '
                        'Wenn nicht, wähle Nein.',
                        reply_markup=generate_household(
                            update.message.from_user.username, first=True))
                    query = "household," + update.message.from_user.username + ","
                    QueryBuffer().add(msg.message_id, query)
                except IndexError:  # first user
                    update.message.bot.send_message(
                        chat_id=update.message.chat_id,
                        text='Super! Wir dürfen jetzt miteinander reden.',
                        reply_markup=ReplyKeyboardRemove())
                    if LogToMessageFilter().ask_chat_type == "private":
                        update.message.bot.send_message(
                            chat_id=update.message.chat_id,
                            text=
                            'Hey, soll ich meine Debug-Nachrichten hier rein schicken?',
                            reply_markup=generate_debug())
            else:
                dbf.add_user_auth(update.message.chat_id)
                update.message.bot.send_message(
                    chat_id=update.message.chat_id,
                    text='Super! Wir dürfen jetzt '
                    'miteinander reden.',
                    reply_markup=ReplyKeyboardRemove())
                if LogToMessageFilter().ask_chat_type == "group":
                    update.message.bot.send_message(
                        chat_id=update.message.chat_id,
                        text=
                        'Hey, soll ich meine Debug-Nachrichten hier rein schicken?',
                        reply_markup=generate_debug())
        else:
            update.message.reply_text(
                "Du musst das Passwort nicht nochmal "
                "eingeben... Rede einfach mit mir!",
                reply_markup=ReplyKeyboardRemove())
    else:
        update.message.reply_text(
            "Schade, das hat leider nicht funktioniert. "
            "Mach es gut!",
            reply_markup=ReplyKeyboardRemove())
        update.message.chat.leave()
Example #13
0
def bulk_insert(graph, host, port, password, nodes, nodes_with_label,
                relations, relations_with_type, separator, enforce_schema,
                skip_invalid_nodes, skip_invalid_edges, quote, max_token_count,
                max_buffer_size, max_token_size, index, full_text_index):
    if sys.version_info[0] < 3:
        raise Exception("Python 3 is required for the RedisGraph bulk loader.")

    if not (any(nodes) or any(nodes_with_label)):
        raise Exception("At least one node file must be specified.")

    start_time = timer()

    # If relations are being built, we must store unique node identifiers to later resolve endpoints.
    store_node_identifiers = any(relations) or any(relations_with_type)

    # Initialize configurations with command-line arguments
    config = Config(max_token_count, max_buffer_size, max_token_size,
                    enforce_schema, skip_invalid_nodes, skip_invalid_edges,
                    separator, int(quote), store_node_identifiers)

    # Attempt to connect to Redis server
    try:
        client = redis.StrictRedis(host=host, port=port, password=password)
    except redis.exceptions.ConnectionError as e:
        print("Could not connect to Redis server.")
        raise e

    # Attempt to verify that RedisGraph module is loaded
    try:
        module_list = client.execute_command("MODULE LIST")
        if not any(b'graph' in module_description
                   for module_description in module_list):
            print("RedisGraph module not loaded on connected server.")
            sys.exit(1)
    except redis.exceptions.ResponseError:
        # Ignore check if the connected server does not support the "MODULE LIST" command
        pass

    # Verify that the graph name is not already used in the Redis database
    key_exists = client.execute_command("EXISTS", graph)
    if key_exists:
        print(
            "Graph with name '%s', could not be created, as Redis key '%s' already exists."
            % (graph, graph))
        sys.exit(1)

    query_buf = QueryBuffer(graph, client, config)

    # Read the header rows of each input CSV and save its schema.
    labels = parse_schemas(Label, query_buf, nodes, nodes_with_label, config)
    reltypes = parse_schemas(RelationType, query_buf, relations,
                             relations_with_type, config)

    process_entities(labels)
    process_entities(reltypes)

    # Send all remaining tokens to Redis
    query_buf.send_buffer()

    end_time = timer()
    query_buf.report_completion(end_time - start_time)

    # Add in Graph Indices after graph creation
    for i in index:
        l, p = i.split(":")
        print("Creating Index on Label: %s, Property: %s" % (l, p))
        try:
            index_create = client.execute_command(
                "GRAPH.QUERY", graph, "CREATE INDEX ON :%s(%s)" % (l, p))
            for z in index_create:
                print(z[0].decode("utf-8"))
        except redis.exceptions.ResponseError as e:
            print("Unable to create Index on Label: %s, Property %s" % (l, p))
            print(e)

    # Add in Full Text Search Indices after graph creation
    for i in full_text_index:
        l, p = i.split(":")
        print("Creating Full Text Search Index on Label: %s, Property: %s" %
              (l, p))
        try:
            index_create = client.execute_command(
                "GRAPH.QUERY", graph,
                "CALL db.idx.fulltext.createNodeIndex('%s', '%s')" % (l, p))
            print(index_create[-1][0].decode("utf-8"))
        except redis.exceptions.ResponseError as e:
            print(
                "Unable to create Full Text Search Index on Label: %s, Property %s"
                % (l, p))
            print(e)
        except:
            print(
                "Unknown Error: Unable to create Full Text Search Index on Label: %s, Property %s"
                % (l, p))
Example #14
0
def handle_household(update, context):
    update.callback_query.answer()
    member = update.callback_query.data.split(";")[1]
    if member == "stop":
        QueryBuffer().clear_query(update.callback_query.message.message_id)
        context.bot.send_message(chat_id=update.callback_query.message.chat_id,
                                 text='Okay, hier ist nichts passiert.',
                                 reply_markup=ReplyKeyboardRemove())
        shrink_keyboard(update, context, "Nein.")
        if LogToMessageFilter().ask_chat_type == "private":
            context.bot.send_message(
                chat_id=update.callback_query.message.chat_id,
                text=
                'Hey, soll ich meine Debug-Nachrichten hier rein schicken?',
                reply_markup=generate_debug())
    elif member == "done":
        end_of_household(update, context)
    else:  # got a household member
        if update.callback_query.data.split(";")[2] == "SET":
            query = QueryBuffer().get_query(
                update.callback_query.message.message_id) + member + "/"
            members_so_far = ps.parse_csv_to_array(query)[-1].split(
                '/')[:-1]  # last one is empty since set ends on /
            remove = ps.parse_csv_to_array(query)[
                1]  # don't let user select himself...
            QueryBuffer().edit_query(update.callback_query.message.message_id,
                                     query)
            # change keyboard layout
            try:
                context.bot.edit_message_text(
                    text=update.callback_query.message.text,
                    chat_id=update.callback_query.message.chat_id,
                    message_id=update.callback_query.message.message_id,
                    reply_markup=generate_household(remove,
                                                    to_set=members_so_far))
            except BadRequest:
                pass
        elif update.callback_query.data.split(";")[2] == "UNSET":
            query = QueryBuffer().get_query(
                update.callback_query.message.message_id)
            query_csv = ps.parse_csv_to_array(query)
            remove = query_csv[1]
            members_so_far = query_csv[-1].split('/')[:-1]
            members_so_far.remove(member)
            members_string = '/'.join(members_so_far)
            if len(members_string) > 0:
                members_string += '/'
            new_query = ps.parse_array_to_csv(
                query_csv[:-1]) + ',' + members_string
            QueryBuffer().edit_query(update.callback_query.message.message_id,
                                     new_query)
            # change keyboard layout
            try:
                context.bot.edit_message_text(
                    text=update.callback_query.message.text,
                    chat_id=update.callback_query.message.chat_id,
                    message_id=update.callback_query.message.message_id,
                    reply_markup=generate_household(remove,
                                                    to_set=members_so_far))
            except BadRequest:
                pass