예제 #1
0
 async def on_ready(self):
     """
     Event handler. Triggered when the bot logs in.
     @return:
     """
     print(f"Logged in as {self.user}")
     await self.change_presence(activity=discord.Activity(
         type=discord.ActivityType.listening, name=f"{PREFIX}help"))
     if RELEASE:
         execute_query(
             "DELETE FROM messages;"
         )  # Delete all remaining messages from a previous session.
예제 #2
0
    def request_server_conf(
            self) -> Tuple[Optional[TextChannel], Set[TextChannel], Set[Role]]:
        """
        Request the server configuration from the database
        @return: archive_id: Optional[int], queue_ids: List[int], role_ids: Set[int]
        """
        result = execute_query(
            "SELECT archiveid, queues, roles FROM servers WHERE serverid = %s;",
            (str(self.server_id), ),
            return_result=True)
        try:
            archive_id, queue_ids, role_ids = result[0]

            if archive_id is not None:  # Archive channel is set
                archive_id = int(archive_id)
                archive = self.server.get_channel(archive_id)
            else:
                archive = None
            if queue_ids is not None:  # At least one queue channel is set
                queue_ids = queue_ids.split()
                queue_ids = set(map(int, queue_ids))
                queues = set(map(self.server.get_channel, queue_ids))
            else:
                queues = set()
            if role_ids is not None:  # At least one role is designated queue manager
                role_ids = role_ids.split()
                role_ids = set(map(int, role_ids))
                roles = set(map(self.server.get_role, role_ids))
            else:
                roles = set()

            return archive, queues, roles
        except IndexError:  # Server has no configuration (no entry in database)
            return None, set(), set()
예제 #3
0
 async def clear_configuration(self, context: Context):
     """
     Delete the configurations for this server.
     @param context: discord.ext.commands.Context: The context of the command
     @return:
     """
     execute_query("DELETE FROM servers WHERE serverid = %s",
                   (str(context.guild.id), ))
     try:
         del self.client.server_confs[
             context.guild]  # Delete server configuration
     except KeyError:
         pass
     embed = Embed(title="Server configuration reset", colour=0xffe400)
     embed.add_field(
         name="Reset succesful",
         value="All configurations for this server are removed.")
     await context.send(embed=embed)
예제 #4
0
def get_dimentions():
    con = dbc.db_connection()
    cursor = dbc.execute_query(con, 'desc restaurant_features')
    rows = cursor.fetchall()
    dimentions = []
    for row in rows:
        if row != 'restaurant_business_id':
            dimentions.append(row[0])
    dbc.lose_connection(con)
    return dimentions
예제 #5
0
 async def set_archive_channel(self, context: Context):
     """
     Set the channel in which this command is used as the archive channel for this server.
     @param context: discord.ext.commands.Context: The context of the command
     @return:
     """
     channel_id = str(context.channel.id)
     server_id = str(context.guild.id)
     execute_query(
         "INSERT INTO servers "
         "(serverid, archiveid) VALUES (%s, %s) "
         "ON DUPLICATE KEY UPDATE  archiveid = VALUES(archiveid)",
         (server_id, channel_id))
     self.client.get_server_conf(context.guild).set_archive(context.channel)
     embed = Embed(title="Archive channel", colour=0xffe400)
     embed.add_field(
         name="Success!",
         value=
         f"{context.channel.mention} is now set as the archive channel.")
     await context.send(embed=embed)
예제 #6
0
 async def on_reaction_add(self, reaction: Reaction, member: Union[Member,
                                                                   User]):
     """
     Event handler. Triggers when a reaction is added to the message
     @param reaction: discord.Reaction: Reaction object
     @param member: discord.Member or discord.User: Member that added the reaction (Or User if in a DM)
     @return:
     """
     if not isinstance(member, Member) or member == reaction.message.guild.me or \
             reaction.message.channel not in self.get_queue_channels(reaction.message.guild):
         return  # Reaction is in a DM, or the bot added the reaction, or the reaction is not in a queue channel.
     if not self.is_manager(
             member) and reaction.emoji != '📤':  # Not a manager
         await reaction.remove(member)
         return
     if reaction.emoji == '❌':
         await reaction.message.delete()
         execute_query("DELETE FROM messages WHERE messageid = %s",
                       (str(reaction.message.id), ))
         return
     if reaction.emoji == '📥':  # Manager clicked to claim this message.
         if len(c := reaction.message.content) < 60 and \
                 re.search(r'(voice|vc|channel|chat|v|inactivacti)\s*\d+', c.lower()) is not None:
             await reaction.message.clear_reactions()
             await reaction.message.add_reaction('👍')
             await asyncio.sleep(6)
             await reaction.message.delete()  # Not worthy of the archive
             return
         await reaction.message.clear_reactions()
         await reaction.message.add_reaction('📤')
         await reaction.message.add_reaction('❌')
         result = execute_query("INSERT IGNORE INTO messages "
                                "(messageid, ownerid) VALUES (%s, %s)",
                                (str(reaction.message.id), str(member.id)),
                                return_cursor_count=True
                                )  # Set manager as owner of this question.
         if result > 0:  # Rows changed: message wasn't yet claimed; could happen in a split second.
             reply = await reaction.message.reply(
                 f"{member.mention} will answer your question.")
             await asyncio.sleep(5)
             await reply.delete()
예제 #7
0
 async def set_manager_roles(self, context: Context):
     """
     Declare the roles given in the arguments of this command as queue managers.
     @param context: discord.ext.commands.Context: The context of the command
     @return:
     """
     content = context.message.content
     if len(content.split()[1:]) == 0:  # No arguments
         await context.send(
             f"Tag the roles to be allowed to manage queues in the command's arguments: "
             f"`{PREFIX}roles @Role1 @Role2`.")
         return
     role_ids: List[str] = re.findall(
         r'<@&(\d+)>', content)  # Clear the tagging syntax around roles IDs
     roles: Set[Role] = set()
     for r_id in role_ids:
         role: Role = context.guild.get_role(int(r_id))
         if role is not None:
             roles.add(role)
     if len(roles) == 0:
         await context.send(
             f"Tag the roles to be allowed to manage queues in the command's arguments: "
             f"`{PREFIX}roles @Role1 @Role2`.")
         return
     role_ids_string = " ".join(
         stream(list(roles)).map(lambda r: r.id).map(str).to_list())
     server_id = str(context.guild.id)
     execute_query(
         "INSERT INTO servers "
         "(serverid, roles) VALUES (%s, %s) "
         "ON DUPLICATE KEY UPDATE  roles = VALUES(roles)",
         (server_id, role_ids_string))
     self.client.get_server_conf(context.guild).set_roles(roles)
     embed = Embed(title="Queue manager roles", colour=0xffe400)
     embed.add_field(name="Success!",
                     value=f"The role(s) that can manage queues are: "
                     f"{', '.join(list(map(lambda r: r.mention, roles)))}")
     await context.send(embed=embed)
예제 #8
0
 async def set_queue_channels(self, context: Context):
     """
     Declare the channels given in the arguments of this command as queues.
     @param context: discord.ext.commands.Context: The context of the command
     @return:
     """
     content = context.message.content
     if len(content.split()[1:]) == 0:
         await context.send(
             f"Tag the channels to enable as queue channel the in command's arguments: "
             f"`{PREFIX}questions #questions1 #questions2`.")
         return
     channel_ids: List[str] = re.findall(
         r'<#(\d+)>', content)  # Find all channel IDs in the message
     queues: Set[TextChannel] = set()
     for c_id in channel_ids:
         queue: TextChannel = context.guild.get_channel(int(c_id))
         if queue is not None:
             queues.add(queue)
     if len(queues) == 0:
         await context.send(
             f"Tag the channels to enable as queue channel the in command's arguments: "
             f"`{PREFIX}questions #questions1 #questions2`.")
         return
     queue_ids_string = " ".join(
         stream(list(queues)).map(lambda c: c.id).map(str).to_list())
     server_id = str(context.guild.id)
     execute_query(
         "INSERT INTO servers "
         "(serverid, queues) VALUES (%s, %s) "
         "ON DUPLICATE KEY UPDATE  queues = VALUES(queues)",
         (server_id, queue_ids_string))
     self.client.get_server_conf(context.guild).set_queues(queues)
     embed = Embed(title="Queue channels", colour=0xffe400)
     embed.add_field(name="Success!",
                     value=f"The channel(s) used as queues are: "
                     f"{', '.join(list(map(lambda q: q.mention, queues)))}")
     await context.send(embed=embed)
예제 #9
0
def get_yelp_data():
    # print 'got request'
    con = dbc.db_connection()
    cursor = dbc.execute_query(con, restaurant_features_query)
    rows = cursor.fetchall()
    test_x_data = []
    test_y_data = []
    # print rows
    for row in rows:
        # print row
        test_touple = []
        index = 0
        for field in row:
            if index < 27:
                if index == 1:
                    if field is None or field not in alcohol_mapping:
                        test_touple.append(0)
                    else:
                        test_touple.append(alcohol_mapping[field])
                        # print type(alcohol_mapping[field])
                elif index == 11:
                    if field is None or field not in attire_mapping:
                        test_touple.append(0)
                    else:
                        test_touple.append(attire_mapping[field])

                elif index == 16:
                    if field is None or field not in noise_mapping:
                        test_touple.append(0)
                    else:
                        test_touple.append(noise_mapping[field])
                elif index == 23:
                    test_touple.append(int(field))
                else:
                    test_touple.append(field)
            else:
                test_y_data.append(float(field))
            index = index + 1
        test_x_data.append(test_touple)
    dbc.close_connection(con)
    # print test_data
    test_data = {'data': test_x_data, 'target': test_y_data}
    # print test_data
    # print len(test_data['data'])
    # print len(test_data['target'])

    # print test_data['data'][0]
    return test_data
예제 #10
0
                    embed.add_field(name=f"{m.author.display_name} replied:",
                                    value=m.content,
                                    inline=False)
                    await m.delete()
            elif author in m.mentions:
                # Add messages that mention the author of the question
                embed.add_field(name=f"{m.author.display_name}:",
                                value=m.content,
                                inline=False)
                await m.delete()

        await message.delete()
        await channel.send(embed=embed)

        # Delete message from database
        execute_query("DELETE FROM messages WHERE messageid = %s",
                      (str(message.id), ))

    # Bot event handlers:

    async def on_ready(self):
        """
        Event handler. Triggered when the bot logs in.
        @return:
        """
        print(f"Logged in as {self.user}")
        await self.change_presence(activity=discord.Activity(
            type=discord.ActivityType.listening, name=f"{PREFIX}help"))
        if RELEASE:
            execute_query(
                "DELETE FROM messages;"
            )  # Delete all remaining messages from a previous session.