Exemple #1
0
def command_setup(bot: commands.bot):
    """Configures command coroutines."""
    from routines.commands import CommandRoutine
    for cmd in CommandRoutine.__subclasses__():
        LOGGER.debug(f'Registering command: {cmd.__name__}')
        setup = cmd(bot)
        setup.actions()
Exemple #2
0
def on_ready_setup(bot: commands.bot):
    """Configures on_ready coroutines."""
    from routines.on_ready import OnReadyEvent
    for event in OnReadyEvent.__subclasses__():
        LOGGER.debug(f'Registering event: {event.__name__}')
        setup = event(bot)
        setup.actions()
 def on_welcome(self, c, e):
     """This is called when we are welcomed by the IRC server."""
     LOGGER.debug("Welcome page of the server was reached successfully.")
     if self.args.channel:
         self.requested = False
         self.connection.join(self.args.channel)
     else:
         self.request_file_to_bot()
Exemple #4
0
def setup_coroutines(bot: commands.bot):
    """Main entrypoint to dynamically configure bot routines."""
    LOGGER.debug('Registering co-routines.')
    database_creation(bot)
    on_ready_setup(bot)
    slash_command_setup(bot)
    command_setup(bot)
    cog_setup(bot)
Exemple #5
0
    async def rsmod(self, ctx):
        right_channel = False
        channel = ""
        for club_channel in self.rs_channel:
            if club_channel == str(ctx.message.channel):
                right_channel = True
                channel = club_channel
        if right_channel:
            extras = {
                'croid': discord.utils.get(self.bot.emojis, name='croid'),
                'influence': discord.utils.get(self.bot.emojis, name='influence'),
                'nosanc': discord.utils.get(self.bot.emojis, name='nosanc'),
                'notele': discord.utils.get(self.bot.emojis, name='notele'),
                'rse': discord.utils.get(self.bot.emojis, name='rse'),
                'suppress': discord.utils.get(self.bot.emojis, name='suppress'),
                'unity': discord.utils.get(self.bot.emojis, name='unity'),
                'veng': discord.utils.get(self.bot.emojis, name='veng'),
                'barrage': discord.utils.get(self.bot.emojis, name='barrage'),
                'laser': discord.utils.get(self.bot.emojis, name='laser'),
                'dart': discord.utils.get(self.bot.emojis, name='dart'),
                'battery': discord.utils.get(self.bot.emojis, name='battery'),
                'solo': discord.utils.get(self.bot.emojis, name='solo'),
                'solo2': discord.utils.get(self.bot.emojis, name='solo2')
            }
            # LOGGER.debug(self.extras)
            LOGGER.debug(str(extras['croid']))
            # await ctx.send(str(croid) + str(influence) + str(nosanc) + str(notele) + str(rse) + str(suppress) + str(unity) + str(veng) + str(barrage))
            extra_embed = discord.Embed(
                color=discord.Color.blue(),
                description="Current Mods"
            )
            extra_embed.add_field(name=str(extras['croid']), value=f"Croid: Would like help getting croid.", inline=False)
            extra_embed.add_field(name=str(extras['influence']), value=f"Influence: would like a full system clear.",inline=False)
            extra_embed.add_field(name=str(extras['nosanc']), value=f"Nosanc: No Sanctuary on Battleships.", inline=False)
            extra_embed.add_field(name=str(extras['rse']), value=f"RSE: Will provide RSE.", inline=False)
            extra_embed.add_field(name=str(extras['veng']), value=f"Veng: Vengeance present on Battleship(s).",inline=False)
            extra_embed.add_field(name=str(extras['notele']),value=f"Notele: No Teleport on either Battleship or Transport.", inline=False)
            extra_embed.add_field(name=str(extras['barrage']),value=f"Barrage: Barrage, best left alone, and if you help only take out capital ships.",inline=False)
            extra_embed.add_field(name=str(extras['suppress']), value=f"Suppress: Suppress present on Battleship(s).",inline=False)
            extra_embed.add_field(name=str(extras['unity']), value=f"Unity: Unity present on Battleship(s).", inline=False)
            extra_embed.add_field(name=str(extras['laser']), value=f"Laser: Laser present on Battleship(s).", inline=False)
            extra_embed.add_field(name=str(extras['battery']), value=f"Battery: Battery present on Battleship(s).",inline=False)
            extra_embed.add_field(name=str(extras['dart']), value=f"Dart: Dart launcher present on Battleship(s).",inline=False)
            extra_embed.add_field(name=str(extras['solo']),value=f"solo: Can solo one planet without any help from others.", inline=False)
            extra_embed.add_field(name=str(extras['solo2']), value=f"solo2: Can solo two planets without any help.",inline=False)

            await ctx.send(embed=extra_embed)
            await ctx.send(
                "If you'd like any of these to show up when you enter a queue, type `!rsmod on ModName`, and it will be added. If you'd like to remove it, type `!rsmod off ModName`")
            # for emoji in self.extras.keys():
            #    await message.add_reaction(discord.utils.get(self.bot.emojis, name=emoji))
        else:
            msg = await ctx.send(f"{ctx.author.mention}, this command can only be run in #bot-spam")
            await asyncio.sleep(15)
            await ctx.message.delete()
            await msg.delete()
Exemple #6
0
 async def corp(self, ctx, *corp):
     member = await ctx.guild.fetch_member(ctx.author.id)
     LOGGER.debug(member.display_name)
     if member.display_name.startswith("["):
         name = member.display_name[member.display_name.find("]") + 2:]
     else:
         name = member.display_name
     nick = f"[{' '.join(corp)}] " + name
     await member.edit(nick=nick)
     await ctx.send(
         f"{ctx.author.display_name}, Your corp has been set to {corp}")
    def on_dcc_disconnect(self, connection, event):
        """This is called when the bot disconnect the DCC comunication."""
        LOGGER.debug("DCC connection closed by remote peer!")
        self.file.close()

        if self.args.action == "send":
            try:
                self.request_file_to_bot()
            except StopIteration:
                self.connection.quit()
        else:  # list
            self.connection.quit()
Exemple #8
0
 def queue_time(self, user_id, level):
     LOGGER.debug(
         f"Running the time command. User ID: {user_id}, level: {level}")
     db = sqlite3.connect("rsqueue.sqlite")
     cursor = db.cursor()
     sql = "SELECT time FROM main WHERE user_id=? AND level=?"
     val = (user_id, level)
     cursor.execute(sql, val)
     person = cursor.fetchone()
     db.commit()
     cursor.close()
     db.close()
     LOGGER.debug("Results from the database: ", person)
     for p in person:
         return int((time.time() - int(p)) / 60)
Exemple #9
0
 async def on_guild_join(self, guild):
     LOGGER.debug(f"Here is the guild: {guild.name}")
     for channel in guild.text_channels:
         LOGGER.debug(f"Channel: {channel}")
         if channel.permissions_for(guild.me).send_messages:
             await channel.send(
                 f"Hello {guild.name}! I'm the bot from The Clubs discord server. You've added me to your server, which means you'll be able to queue for Red Stars without even leaving the comfort of your discord server!"
             )
             await channel.send(
                 f"In order to be connected to The Clubs, I'll need a text channel to show the current queues. Once you have a text channel that I can use, simply run `!connect # %` in the channel you want where # is the minimum rs level of your server and % is the maximum (i.e. `!connect 5 9`) and just like that you'll be connected to The Clubs!"
             )
             await channel.send(
                 f"NOTE: The `!connect # %` command can ONLY be run by an administrator of this server."
             )
             break
Exemple #10
0
 async def check_people(self):
     # This command will run every minute, and check if someone has been in a queue for over n minutes
     LOGGER.debug("Checking the time")
     db = sqlite3.connect('rsqueue.sqlite')
     cursor = db.cursor()
     # TODO: This *should* deal with the conflicts until PostgreSQL is used
     cursor.execute(
         "SELECT time, length, user_id, level, channel_id FROM main")
     times = cursor.fetchall()
     for queue_time in times:
         # LOGGER.debug(queue_time)
         # LOGGER.debug(int(time.time()), queue_time[0], int(time.time())-queue_time[0], int((time.time()-queue_time[0])/60))
         minutes = int((time.time() - queue_time[0]) / 60)
         if minutes == queue_time[1]:
             # Ping the user
             user = await self.bot.fetch_user(queue_time[2])
             channel = await self.bot.fetch_channel(queue_time[4])
             message = await channel.send(
                 f"{user.mention}, still in for a RS{queue_time[3]}? React ✅ to stay in the queue, and ❌ to leave the queue"
             )
             await message.add_reaction('✅')
             await message.add_reaction('❌')
             # Add their user_id and message_id to database
             sql = "INSERT INTO temp(user_id, message_id, level) VALUES(?,?,?)"
             val = (user.id, message.id, queue_time[3])
             cursor.execute(sql, val)
             pass
         elif minutes >= queue_time[1] + 5:
             self.sql_command(
                 "DELETE FROM main WHERE user_id=? AND level=?",
                 (queue_time[2], queue_time[3]))
             user = await self.bot.fetch_user(queue_time[2])
             channel = await self.bot.fetch_channel(queue_time[4])
             await channel.send(
                 f"{user.display_name} has left RS{queue_time[3]} ({self.amount(queue_time[3])}/4)"
             )
             id = self.sql_command(
                 "SELECT message_id FROM temp WHERE user_id=? AND level=?",
                 (queue_time[2], queue_time[3]))
             message = await channel.fetch_message(id[0][0])
             await message.delete()
             self.sql_command(
                 "DELETE FROM temp WHERE user_id=? AND level=?",
                 (queue_time[2], queue_time[3]))
             pass
     db.commit()
     cursor.close()
     db.close()
    def request_file_to_bot(self):
        """Sends a ctcp message to the bot requesting the pack number specified
        on the command-line arguments.

        When the send action was chosen, this method raise StopIteration when there is
        no more pack to be downloaded.
        """
        LOGGER.debug("Sending command to the bot...")
        if self.args.action == "list":
            self.connection.ctcp("xdcc", self.args.bot, "send list")
        elif self.args.action == "send":
            next_pack = next(self.packs_iter)
            self.connection.ctcp(
                "xdcc", self.args.bot, "send %d" % next_pack
            )
            self.last_pack = next_pack
            self.__current_pack += 1
Exemple #12
0
 async def out(self, ctx):
     # First check if they are in any RS Queues
     db = sqlite3.connect('rsqueue.sqlite')
     cursor = db.cursor()
     sql = "SELECT user_id FROM main WHERE user_id=?"
     cursor.execute(sql, [ctx.author.id])
     results = cursor.fetchall()
     if len(results) != 0:  # They were found in an RS Queue
         # remove only one (and delete if they only have one in queue)
         current_queues = self.sql_command(
             "SELECT level, amount FROM main WHERE user_id=?",
             [(ctx.author.id)])
         # would return [(11, 2), (10, 3)] for example
         adding_queue = (self.rs_channel[str(ctx.message.channel)], -1)
         current_queues.append(adding_queue)
         updated_queues = {}
         for (x, y) in current_queues:
             if x not in updated_queues.keys():
                 updated_queues[x] = y
             else:
                 updated_queues[x] += y
         final_queues = [(x, updated_queues[x])
                         for x in updated_queues.keys()]
         for updated_queues in final_queues:
             # Remove only count from the queue they sent the message in
             if updated_queues[0] == self.rs_channel[str(
                     ctx.message.channel)]:
                 LOGGER.debug(updated_queues)
                 if updated_queues[1] <= 0:
                     self.sql_command(
                         "DELETE FROM main WHERE user_id=? AND level=?",
                         (ctx.author.id, int(updated_queues[0])))
                     LOGGER.debug("Removed them from the queue")
                 else:
                     self.sql_command(
                         "UPDATE main SET amount=? WHERE user_id=? AND level=?",
                         (int(updated_queues[1]), ctx.author.id,
                          self.rs_channel[str(ctx.message.channel)]))
                     LOGGER.debug("updated the queue they were in")
         # Print out the new queue
         await self.print_queue(ctx,
                                self.rs_channel[str(ctx.message.channel)],
                                False)
         await ctx.send(
             f"{ctx.author.display_name} has left the RS{self.rs_channel[str(ctx.message.channel)]} Queue ({self.amount(self.rs_channel[str(ctx.message.channel)])}/4)"
         )
     else:
         await ctx.send(f"{ctx.author.mention}, You aren't in an RS Queues")
     db.commit()
     cursor.close()
     db.close()
Exemple #13
0
def setup(bot):
    bot.add_cog(RSEvent(bot))
    LOGGER.debug('RS Event Loaded')
Exemple #14
0
 async def everything(self, ctx, prefix, count, length, channel_id):
     LOGGER.debug(f"Running the everything command")
     LOGGER.debug(
         f"Values: Prefix: {prefix}, Count: {count}, length: {length}, channel_id: {channel_id}"
     )
     count = int(count)
     if prefix == "+":
         right_channel = False
         channel = ""
         for club_channel in self.rs_channel:
             if club_channel == str(ctx.message.channel):
                 right_channel = True
                 channel = club_channel
         if right_channel:
             has_right_role = False
             for role in ctx.author.roles:
                 if str(role)[2:].isnumeric():  # Checks main role (rs#)
                     if int(str(role)[2:]) >= int(self.rs_channel[channel]):
                         has_right_role = True
                         break
                 elif str(role)[2:-12].isnumeric(
                 ):  # Checks 3/4 role (rs# 3/4 1more)
                     if int(str(role)[2:-12]) >= int(
                             self.rs_channel[channel]):
                         has_right_role = True
                         break
                 elif str(role)[2:-2].isnumeric(
                 ):  # Checks silent role (rs# s)
                     if int(str(role)[2:-2]) >= int(
                             self.rs_channel[channel]):
                         has_right_role = True
                         break
             if has_right_role:
                 # check if adding amount would overfill the queue
                 queue_status = self.amount(self.rs_channel[channel])
                 if int(queue_status) + count > 4:
                     await ctx.send(
                         f"{ctx.author.mention}, adding {count} people to the queue would overfill the queue"
                     )
                 else:
                     # check if they are in any other queues
                     database_check = self.sql_command(
                         "SELECT user_id FROM main WHERE user_id=?",
                         [(ctx.author.id)])
                     LOGGER.debug(database_check)
                     if len(
                             database_check
                     ) == 0:  # They weren't found in the database, add them
                         LOGGER.debug("Adding them to the queue")
                         self.sql_command(
                             "INSERT INTO main(user_id, amount, level, time, length, channel_id) VALUES(?,?,?,?,?,?)",
                             (ctx.author.id, count,
                              self.rs_channel[channel], int(
                                  time.time()), length, channel_id))
                         # Check if queue is 4/4
                         if self.amount(self.rs_channel[channel]) == 4:
                             LOGGER.debug("Queue is 4/4, remove everyone")
                             # Print out the queue
                             people = self.sql_command(
                                 "SELECT user_id FROM main WHERE level=?",
                                 [(self.rs_channel[str(
                                     ctx.message.channel)])])
                             string_people = ""
                             print_people = []
                             LOGGER.debug(people)
                             for person in people:
                                 string_people += (
                                     await self.bot.fetch_user(
                                         person[0])).mention + " "
                                 print_people.append(
                                     (await ctx.guild.fetch_member(
                                         person[0])).display_name)
                             await self.print_queue(
                                 ctx,
                                 self.rs_channel[str(ctx.message.channel)])
                             await ctx.send(
                                 f"RS{self.rs_channel[str(ctx.message.channel)]} Ready! {string_people}"
                             )
                             await ctx.send("Meet where?")
                             # Remove everyone from the queue
                             self.sql_command(
                                 "DELETE FROM main WHERE level=?",
                                 [(self.rs_channel[str(
                                     ctx.message.channel)])])
                             #
                             rs_log_channel = await self.bot.fetch_channel(
                                 805228742678806599)
                             formated_date = datetime.now().strftime(
                                 "%m/%d/%Y, %H:%M:%S")
                             await rs_log_channel.send(
                                 f"RS{self.rs_channel[str(ctx.message.channel)]} Started at {formated_date} PST \nUsers: {', '.join(print_people)}"
                             )
                         else:
                             LOGGER.debug(
                                 "Queue ain't 4/4, print out el queue")
                             await self.print_queue(
                                 ctx,
                                 self.rs_channel[str(ctx.message.channel)])
                             count = self.amount(self.rs_channel[channel])
                             if count == 3:
                                 await ctx.send(
                                     f"{ctx.author.mention} joined {self.rs_ping_1more[f'RS{self.rs_channel[channel]}']} ({count}/4)"
                                 )
                             else:
                                 await ctx.send(
                                     f"{ctx.author.mention} joined {self.rs_ping[f'RS{self.rs_channel[channel]}']} ({count}/4)"
                                 )
                     else:
                         LOGGER.debug(
                             "They were found on multiple queues, find all queues"
                         )
                         # see what queue they are on, and either update their current position or new position
                         current_queues = self.sql_command(
                             "SELECT level, amount FROM main WHERE user_id=?",
                             [(ctx.author.id)])
                         current_queues.append(
                             (self.rs_channel[str(ctx.message.channel)],
                              count))
                         LOGGER.debug(f'Current Queues: {current_queues}')
                         D = {}
                         for (x, y) in current_queues:
                             if x not in D.keys():
                                 D[x] = y
                             else:
                                 D[x] += y
                         final_queues = [(x, D[x]) for x in D.keys()]
                         LOGGER.debug(final_queues)
                         LOGGER.debug(
                             "Above is what should be the final queue status"
                         )
                         # append the queue they wanna join to
                         for queue in final_queues:
                             if queue[0] == self.rs_channel[channel]:
                                 # Check if adding amount to the queue would make it 4/4
                                 if self.amount(self.rs_channel[channel]
                                                ) + count > 4:
                                     pass
                                 else:
                                     # check to see if we need to update their position or add another position
                                     if (len(
                                             self.sql_command(
                                                 "SELECT amount FROM main WHERE user_id=? AND level=?",
                                                 (ctx.author.id,
                                                  self.rs_channel[channel]
                                                  ))) == 0):
                                         # They weren't found elsewhere, add them to the new queue
                                         self.sql_command(
                                             "INSERT INTO main(user_id, amount, level, time, length, channel_id) VALUES(?,?,?,?,?,?)",
                                             (ctx.author.id, int(queue[1]),
                                              self.rs_channel[channel],
                                              int(time.time()), length,
                                              channel_id))
                                     else:
                                         # They were found on another queue, so update their position
                                         self.sql_command(
                                             f"UPDATE main SET amount=?, time=?, length=? WHERE user_id=? AND level=?",
                                             (int(queue[1]), int(
                                                 time.time()), length,
                                              ctx.author.id,
                                              self.rs_channel[channel]))
                                     if self.amount(queue[0]) == 4:
                                         people = self.sql_command(
                                             "SELECT user_id FROM main WHERE level=?",
                                             [(self.rs_channel[str(
                                                 ctx.message.channel)])])
                                         string_people = ""
                                         print_people = []
                                         for person in people:
                                             string_people += (
                                                 await self.bot.fetch_user(
                                                     person[0]
                                                 )).mention + " "
                                             print_people.append(
                                                 (await
                                                  ctx.guild.fetch_member(
                                                      person[0]
                                                  )).display_name)
                                         await self.print_queue(
                                             ctx, self.rs_channel[str(
                                                 ctx.message.channel)])
                                         await ctx.send(
                                             f"RS{self.rs_channel[str(ctx.message.channel)]} Ready! {string_people}"
                                         )
                                         await ctx.send("Meet where?")
                                         # Remove everyone from the queue
                                         self.sql_command(
                                             "DELETE FROM main WHERE level=?",
                                             [(self.rs_channel[str(
                                                 ctx.message.channel)])])
                                         # Print out the rs log
                                         rs_log_channel = await self.bot.fetch_channel(
                                             805228742678806599)
                                         formated_date = datetime.now(
                                         ).strftime("%m/%d/%Y, %H:%M:%S")
                                         await rs_log_channel.send(
                                             f"RS{self.rs_channel[str(ctx.message.channel)]} Started at {formated_date} PST \nUsers: {', '.join(print_people)}"
                                         )
                                     else:
                                         await self.print_queue(
                                             ctx, self.rs_channel[str(
                                                 ctx.message.channel)])
                                         count = self.amount(
                                             self.rs_channel[channel])
                                         if count == 3:
                                             await ctx.send(
                                                 f"{ctx.author.mention} joined {self.rs_ping_1more[f'RS{self.rs_channel[channel]}']} ({count}/4)"
                                             )
                                         else:
                                             await ctx.send(
                                                 f"{ctx.author.mention} joined {self.rs_ping[f'RS{self.rs_channel[channel]}']} ({count}/4)"
                                             )
             else:
                 await ctx.send(
                     f"{ctx.author.mention}, you aren't RS{self.rs_channel[channel]}"
                 )
         else:
             msg = await ctx.send("Command not run in an RS Channel")
             await asyncio.sleep(10)
             await ctx.message.delete()
             await msg.delete()
     elif prefix == "-":
         LOGGER.debug("- command run, attempting to remove them from queue")
         result = self.sql_command(
             "SELECT amount FROM main WHERE user_id=? AND level=?",
             (ctx.author.id, self.rs_channel[str(ctx.message.channel)]))
         LOGGER.debug(result)
         if len(result) == 0:  # Didn't find them in any queues
             await ctx.send(
                 f"{ctx.author.mention}, You aren't in an RS Queues at the moment"
             )
         else:  # Remove count of them from the queue
             # Get the level and amount data
             # Check if removing count would remove more than they are in
             current_queues = self.sql_command(
                 "SELECT level, amount FROM main WHERE user_id=?",
                 [(ctx.author.id)])
             # would return [(11, 2), (10, 3)] for example
             adding_queue = (self.rs_channel[str(ctx.message.channel)],
                             -count)
             current_queues.append(adding_queue)
             D = {}
             for (x, y) in current_queues:
                 if x not in D.keys():
                     D[x] = y
                 else:
                     D[x] += y
             final_queues = [(x, D[x]) for x in D.keys()]
             LOGGER.debug(final_queues)
             LOGGER.debug("above is the final queues of that person")
             for queue in final_queues:
                 # Remove only count from the queue they sent the message in
                 if queue[0] == self.rs_channel[str(ctx.message.channel)]:
                     LOGGER.debug(queue)
                     if queue[1] <= 0:
                         self.sql_command(
                             "DELETE FROM main WHERE user_id=? AND level=?",
                             (ctx.author.id, int(queue[0])))
                         LOGGER.debug("Removed them from the queue")
                     else:
                         self.sql_command(
                             "UPDATE main SET amount=? WHERE user_id=? AND level=?",
                             (int(queue[1]), ctx.author.id,
                              self.rs_channel[str(ctx.message.channel)]))
                         LOGGER.debug("updated the queue they were in")
             people = self.sql_command(
                 "SELECT amount FROM main WHERE level=?",
                 [(self.rs_channel[str(ctx.message.channel)])])
             count = 0
             counting = []
             for person in people:
                 counting.append(person[0])
                 count += int(person[0])
             await self.print_queue(
                 ctx, self.rs_channel[str(ctx.message.channel)], False)
             await ctx.send(
                 f"{ctx.author.display_name} has left the RS{self.rs_channel[str(ctx.message.channel)]} Queue ({count}/4)"
             )
Exemple #15
0
def cog_setup(bot):
    """Configures cogs."""
    from routines.cogs import __all__
    for cog in __all__:
        LOGGER.debug(f'Registering cog: {cog}')
        bot.load_extension(f'routines.cogs.{cog}')
Exemple #16
0
 async def connect(self, ctx, min_rs=None, max_rs=None):
     await ctx.send("This feature has currently been disabled")
     if (False):
         if max_rs is None or min_rs is None:
             await ctx.send(
                 "Please specify this server's min and max rs level in the `!connect` command, i.e. `!connect 5 9`"
             )
         if int(max_rs) < int(min_rs):
             await ctx.send(
                 "Your server's maximum rs level should be higher than your minimum."
             )
         elif int(min_rs) > 4 and int(max_rs) < 12:
             async with sessionmaker(
             ) as session:  # check to see if the server is already in the database
                 data = (await session.execute(
                     select(ExternalServer).where(
                         ExternalServer.server_id == ctx.guild.id)
                 )).scalars().all()
             if len(data
                    ) == 0:  # Add the server to the ExternalServer Database
                 async with sessionmaker() as session:
                     LOGGER.debug("Adding server to database")
                     webhook = await ctx.channel.create_webhook(
                         name="Global Chat Webhook (The Clubs)")
                     Server_enter = ExternalServer(
                         server_id=ctx.guild.id,
                         server_name=ctx.guild.name,
                         channel_id=ctx.channel.id,
                         webhook=str(webhook.url),
                         min_rs=int(min_rs),
                         max_rs=int(max_rs),
                         global_chat=False,
                         show=True)
                     session.add(Server_enter)
                     await session.commit()
                     print_str = "This server has been connected to The Clubs!\n"
                     print_str += f"The min/max rs of this server has been set to: rs{min_rs}-rs{max_rs}\n"
                     print_str += "If you messed up the max rs level of this server while running the `!connect` command, just run the command again with the correct rs level(s) and it will update the rs level of the server.\n"
                     print_str += "Now comes the fun part, setting up the rs level of users on this server!\n"
                     print_str += "Below is everything you'll need to know about setting this up, and if you need to see this again, run `!help external`, or to see all functions of this bot, `!help`\n"
                     await ctx.send(print_str)
                     external_embed = discord.Embed(
                         title='External', color=discord.Color.green())
                     if TESTING:
                         external_embed.add_field(
                             name="Connecting your server to the clubs",
                             value=
                             f"If you want to connect your corporation's discord server to The Clubs so you can run Red Stars from the comfort of your discord server, simply add the bot to your discord server with [this link](https://discord.com/api/oauth2/authorize?client_id=805960284543385650&permissions=537193536&scope=bot) and follow the steps"
                         )
                     else:
                         # Fix this
                         external_embed.add_field(
                             name="Connecting your server to the clubs",
                             value=
                             f"If you want to connect your corporation's discord server to The Clubs so you can run Red Stars from the comfort of your discord server, simply add the bot to your discord server with [this link]() and follow the steps"
                         )
                     external_embed.add_field(
                         name="First Time Setup",
                         value=
                         f"Run `!connect # %` (where `#` is the minimum rs level of your server and `%` is the maximum), and your server will be connected to The Clubs."
                     )
                     external_embed.add_field(
                         name="Setting up max RS levels",
                         value=
                         f"To change the min/max RS level of your server, run `!connect # %` where `#` is the minimum rs level of your server and `%` is the maximum."
                     )
                     external_embed.add_field(
                         name="Users and Queues",
                         value=
                         f"To allow users to join queues, they'll need to have a role specifying their rs level. In order to do this, use the `!level # type @<>` command, where `#` is the rs level, and `type` is either `all`, `3/4`, or `silent`. This allows users to decide if how they want to get notified (everytime, when the queue is 3/4, or not at all) `@<>` is the role that players in that rs level have. If you want to change the role, simply run the command again."
                     )
                     external_embed.add_field(
                         name="Seeing Roles",
                         value=
                         f"Use the `!current` command to show what roles are currently connected to the bot. If you want to add more, use the `!level # type @<>` command."
                     )
                     external_embed.add_field(
                         name="Disconnecting",
                         value=
                         f"If you want this server to be disconnected from The Clubs, have an admin run the `!disconnect` command."
                     )
                     external_embed.add_field(
                         name="Joining/Leaving/Showing Queues",
                         value=
                         f"Go to the queue section of the `!help` command to get information on the queueing system (`!help q`)."
                     )
                     await ctx.send(embed=external_embed)
             else:  # They were found in the database, update their max rs level
                 async with sessionmaker() as session:
                     server = (await session.get(ExternalServer,
                                                 ctx.guild.id))
                     server.max_rs = int(max_rs)
                     await session.commit()
                     await ctx.send(
                         f"This server has already been connected to The Clubs, but now the max rs level of this server is {max_rs}"
                     )
         else:
             await ctx.send(
                 f"The Clubs only support RS 5-11, {max_rs} is outside that range."
             )
Exemple #17
0
    async def rs(self, ctx, length=60):
        right_channel = False
        channel = ""
        add_level = self.rs_channel[str(ctx.message.channel)]
        for club_channel in self.rs_channel:
            if club_channel == str(ctx.message.channel):
                right_channel = True
                channel = club_channel
        if right_channel:
            has_right_role = False
            for role in ctx.author.roles:
                if str(role)[2:].isnumeric():  # Check main rs role
                    if int(str(role)[2:]) >= int(self.rs_channel[channel]):
                        has_right_role = True
                        break
                elif str(role)[2:-12].isnumeric():  # Check 3/4 role
                    if int(str(role)[2:-12]) >= int(self.rs_channel[channel]):
                        has_right_role = True
                        break
                elif str(role)[2:-2].isnumeric():  # Checks silent role (rs# s)
                    if int(str(role)[2:-2]) >= int(self.rs_channel[channel]):
                        has_right_role = True
                        break
                # if(str(role) == f'RS{self.rs_channel[channel]}' or int(str(role)[2:]) > self.rs_channel[channel]):
                #    has_right_role = True
            if has_right_role:
                # This is where the fun begins
                db = sqlite3.connect('rsqueue.sqlite')
                cursor = db.cursor()
                # check if they are in any other queues
                sql = "SELECT user_id FROM main WHERE user_id=?"
                cursor.execute(sql, [ctx.author.id])
                if len(cursor.fetchall()
                       ) == 0:  # They weren't found in the database, add them
                    self.sql_command(
                        "INSERT INTO main(user_id, amount, level, time, length, channel_id) VALUES(?,?,?,?,?,?)",
                        (ctx.author.id, 1, add_level, int(
                            time.time()), length, ctx.channel.id))
                    # Print out the queue
                    # Check if queue is 4/4
                    people = self.sql_command(
                        "SELECT amount FROM main WHERE level=?", [(add_level)])
                    count = 0
                    counting = []
                    for person in people:
                        counting.append(person[0])
                        count += int(person[0])
                    if count == 4:
                        # Print out the queue
                        sql = "SELECT user_id FROM main WHERE level=?"
                        cursor.execute(sql, [add_level])
                        people = cursor.fetchall()
                        string_people = ""
                        print_people = []
                        for person in people:
                            string_people += (await self.bot.fetch_user(
                                person[0])).mention + " "
                            print_people.append(
                                (await ctx.guild.fetch_member(person[0]
                                                              )).display_name)
                        await self.print_queue(
                            ctx, self.rs_channel[str(ctx.message.channel)])
                        await ctx.send(
                            f"RS{self.rs_channel[str(ctx.message.channel)]} Ready! {string_people}"
                        )
                        await ctx.send("Meet where?")
                        # Remove everyone from the queue
                        sql = "DELETE FROM main WHERE level=?"
                        cursor.execute(sql, [add_level])
                        # Print logs to rs-log
                        rs_log_channel = await self.bot.fetch_channel(
                            805228742678806599)
                        formated_date = datetime.now().strftime(
                            "%m/%d/%Y, %H:%M:%S")
                        await rs_log_channel.send(
                            f"RS{self.rs_channel[str(ctx.message.channel)]} Started at {formated_date} PST \nUsers: {', '.join(print_people)}"
                        )
                    else:
                        await self.print_queue(
                            ctx, self.rs_channel[str(ctx.message.channel)])
                        count = self.amount(self.rs_channel[channel])
                        if count == 3:
                            await ctx.send(
                                f"{ctx.author.mention} joined {self.rs_ping_1more[f'RS{self.rs_channel[channel]}']} ({count}/4)"
                            )
                        else:
                            await ctx.send(
                                f"{ctx.author.mention} joined {self.rs_ping[f'RS{self.rs_channel[channel]}']} ({count}/4)"
                            )
                    db.commit()
                    cursor.close()
                    db.close()
                else:
                    # see what queue they are on, and either update their current position or new position
                    current_queues = self.sql_command(
                        "SELECT level, amount FROM main WHERE user_id=?",
                        [(ctx.author.id)])
                    # Check to see if they are trying to update the position of a queue they are in
                    valid = True
                    for (x, y) in current_queues:
                        if x == self.rs_channel[str(ctx.message.channel)]:
                            valid = False
                    if valid:
                        current_queues.append(
                            (self.rs_channel[str(ctx.message.channel)], 1))
                        LOGGER.debug(current_queues)
                        D = {}
                        for (x, y) in current_queues:
                            if x not in D.keys():
                                D[x] = y
                            else:
                                D[x] += y
                        final_queues = [(x, D[x]) for x in D.keys()]
                        LOGGER.debug(final_queues)
                        # append the queue they wanna join to the
                        for queue in final_queues:
                            if queue[0] == self.rs_channel[channel]:
                                # Check if adding amount to the queue would make it 4/4
                                if self.amount(
                                        self.rs_channel[channel]) + 1 > 4:
                                    pass
                                else:
                                    # check to see if we need to update their position or add another position
                                    if len(
                                            self.sql_command(
                                                "SELECT amount FROM main WHERE user_id=? AND level=?",
                                                (ctx.author.id,
                                                 self.rs_channel[channel]
                                                 ))) == 0:
                                        # They weren't found elsewhere, add them to the new queue
                                        self.sql_command(
                                            "INSERT INTO main(user_id, amount, level, time, length, channel_id) VALUES(?,?,?,?,?,?)",
                                            (ctx.author.id, int(queue[1]),
                                             self.rs_channel[channel],
                                             int(time.time()), length,
                                             ctx.channel.id))
                                    else:
                                        # They were found on another queue, so update their position
                                        self.sql_command(
                                            f"UPDATE main SET amount=?, time=?, length=? WHERE user_id=? AND level=?",
                                            (int(queue[1]), int(time.time()),
                                             length, ctx.author.id,
                                             self.rs_channel[channel]))
                                    if self.amount(queue[0]) == 4:
                                        people = self.sql_command(
                                            "SELECT user_id FROM main WHERE level=?",
                                            [(self.rs_channel[str(
                                                ctx.message.channel)])])
                                        string_people = ""
                                        print_people = []
                                        for person in people:
                                            string_people += (
                                                await self.bot.fetch_user(
                                                    person[0])).mention + " "
                                            print_people.append(
                                                (await ctx.guild.fetch_member(
                                                    person[0])).display_name)

                                        await ctx.send(
                                            f"RS{self.rs_channel[str(ctx.message.channel)]} Ready! {string_people}"
                                        )
                                        await ctx.send("Meet where?")
                                        rs_log_channel = await self.bot.fetch_channel(
                                            805228742678806599)
                                        formated_date = datetime.now(
                                        ).strftime("%m/%d/%Y, %H:%M:%S")
                                        await rs_log_channel.send(
                                            f"RS{self.rs_channel[str(ctx.message.channel)]} Started at {formated_date} PST \nUsers: {', '.join(print_people)}"
                                        )
                                        # Remove everyone from the queue
                                        self.sql_command(
                                            "DELETE FROM main WHERE level=?",
                                            [(self.rs_channel[str(
                                                ctx.message.channel)])])
                                        # Print the logs to rs-log
                                        rs_log_channel = await self.bot.fetch_channel(
                                            805228742678806599)
                                        formated_date = datetime.now(
                                        ).strftime("%m/%d/%Y, %H:%M:%S")
                                        await rs_log_channel.send(
                                            f"RS{self.rs_channel[str(ctx.message.channel)]} Started at {formated_date} PST \nUsers: {', '.join(print_people)}"
                                        )
                                    else:
                                        await self.print_queue(
                                            ctx, self.rs_channel[str(
                                                ctx.message.channel)])
                                        count = self.amount(
                                            self.rs_channel[channel])
                                        if count == 3:
                                            await ctx.send(
                                                f"{ctx.author.mention} joined {self.rs_ping_1more[f'RS{self.rs_channel[channel]}']} ({count}/4)"
                                            )
                                        else:
                                            await ctx.send(
                                                f"{ctx.author.mention} joined {self.rs_ping[f'RS{self.rs_channel[channel]}']} ({count}/4)"
                                            )
                    else:
                        await ctx.send(
                            f"{ctx.author.mention}, you are already queued for a RS{self.rs_channel[channel]}, if you want to add another player to the queue, type +1"
                        )
            else:
                await ctx.send(
                    f"{ctx.author.mention}, you aren't RS{self.rs_channel[channel]}"
                )
Exemple #18
0
 async def print_queue(self, ctx, level, display=True):
     extras = {
         'croid': discord.utils.get(self.bot.emojis, name='croid'),
         'influence': discord.utils.get(self.bot.emojis, name='influence'),
         'nosanc': discord.utils.get(self.bot.emojis, name='nosanc'),
         'notele': discord.utils.get(self.bot.emojis, name='notele'),
         'rse': discord.utils.get(self.bot.emojis, name='rse'),
         'suppress': discord.utils.get(self.bot.emojis, name='suppress'),
         'unity': discord.utils.get(self.bot.emojis, name='unity'),
         'veng': discord.utils.get(self.bot.emojis, name='veng'),
         'barrage': discord.utils.get(self.bot.emojis, name='barrage'),
         'laser': discord.utils.get(self.bot.emojis, name='laser'),
         'dart': discord.utils.get(self.bot.emojis, name='dart'),
         'battery': discord.utils.get(self.bot.emojis, name='battery'),
         'solo': discord.utils.get(self.bot.emojis, name='solo'),
         'solo2': discord.utils.get(self.bot.emojis, name='solo2')
     }
     queue_embed = discord.Embed(color=discord.Color.red())
     db = sqlite3.connect('rsqueue.sqlite')
     cursor = db.cursor()
     sql = "SELECT amount FROM main WHERE level=?"
     cursor.execute(sql, [level])
     people = cursor.fetchall()
     count = 0
     counting = []
     for person in people:
         counting.append(person[0])
         count += int(person[0])
     if count > 0:
         sql = "SELECT user_id FROM main WHERE level=?"
         cursor.execute(sql, [level])
         people_printing = cursor.fetchall()
         list_people = []
         user_ids = []
         rsmods = []
         for people in people_printing:
             list_people.append(
                 (await ctx.guild.fetch_member(people[0])).display_name)
             user_ids.append((await ctx.guild.fetch_member(people[0])).id)
             result = self.sql_command(
                 "SELECT * FROM data WHERE user_id=?",
                 [(await ctx.guild.fetch_member(people[0])).id])
             stuff = cursor.execute('select * from data')
             names = [description[0] for description in stuff.description]
             LOGGER.debug(names)
             names = names[1:]
             temp = ""
             if len(result) != 0:
                 for i in range(1, len(result[0])):
                     if result[0][i] == 1:
                         temp += " " + (str(extras[names[i - 1]]))
             rsmods.append(temp)
         str_people = ""
         emoji_count = 0
         for i in range(len(people_printing)):
             for j in range(counting[i]):
                 str_people += str(list(self.emojis)[emoji_count])
                 emoji_count += 1
             str_people += " " + list_people[i] + rsmods[i] + " 🕒 " + str(
                 self.queue_time(user_ids[i], self.rs_channel[str(
                     ctx.message.channel)])) + "m"
             str_people += "\n"
         queue_embed.add_field(
             name=
             f"The Current RS{self.rs_channel[str(ctx.message.channel)]} Queue ({self.amount(self.rs_channel[str(ctx.message.channel)])}/4)",
             value=str_people,
             inline=False)
         await ctx.send(embed=queue_embed)
     else:
         if display:
             await ctx.send(
                 f"No RS{self.rs_channel[str(ctx.message.channel)]} Queues found, you can start one by typing +1"
             )
     db.commit()
     cursor.close()
     db.close()
Exemple #19
0
def database_creation(bot: commands.bot):
    from routines.create_database import CreateDatabaseEvent
    for event in CreateDatabaseEvent.__subclasses__():
        LOGGER.debug(f'Registering event: {event.__name__}')
        setup = event(bot)
        setup.actions()
Exemple #20
0
def setup(bot):
    bot.add_cog(RSQueue(bot))
    LOGGER.debug('RS Queueing loaded')
 def on_disconnect(self, connection, event):
     """Called when disconnecting from the server."""
     LOGGER.debug("Disconnected!")
     self.end_loop = True
Exemple #22
0
            "RS11": "<@&806261078295183400>"
        },
        'rs_ping_1more': {
            "RS5": "<@&806018333517938688>",
            "RS6": "<@&806018337804910592>",
            "RS7": "<@&806018340203397140>",
            "RS8": "<@&806018343696990208>",
            "RS9": "<@&806018346269016084>",
            "RS10": "<@&806018349183139890>",
            "RS11": "<@&806261118158372936>"
        }
    },
}

if TESTING:
    LOGGER.debug('Loading testing settings.')
    RS_GROUPS = RS_GROUPS.get('testing')
else:
    LOGGER.info('Loading PRODUCTION settings.')
    RS_GROUPS = RS_GROUPS.get('prod')


class RSQueue(commands.Cog, name='Queue'):
    def __init__(self, bot):
        self.bot = bot
        self.index = 0
        self.check_people.start()
        self.current_mods = [
            "croid", "influence", "nosanc", "notele", "rse", "suppress",
            "unity", "veng", "barrage"
        ]