def JoinOrder(order_name, user):
    """ Adds a user to an order if they are not already in it"""
    db = staticsDb()

    msg = db.AddUserToStatic(str(user), order_name)

    if msg != "":
        raise Exception(msg)
Esempio n. 2
0
 def Update(self):
     """ Requests to update table entry for static """
     db = staticsDb()
     setStr = (f'static_name = \'{self.static_name}\','
               f'lead_name = \'{self.static_lead}\','
               f'colead_name = \'{self.static_colead}\','
               f'static_role_id = \'{self.discord_id}\','
               f'static_size = {self.static_size}')
     db.UpdateStaticRow(setStr, self.id)
Esempio n. 3
0
    def static_exists(self):
        """ Checks if the current static exists in the database """
        db = staticsDb()

        data = db.GetStaticDataByName(self.static_name)
        if (data):
            return True
        else:
            return False
async def PromoteCoLead(static_data, discord_name, adding_user,
                        adding_user_is_officer, discData, role_manager):
    """ Promotes a user to co_lead for a given order 
        static_data: Data for the static that is being modified 
        discord_name: Name of the co_lead in discord
        adding_user: user that is attempting the prompotion, should be from the same order unless it is a discord officier
        adding_user_is_officer: boolean to siginify if the user sending the message is an officer
        discData: Discord channel data
        role_manager: Initialized role manager
    """
    db = staticsDb()

    properFormat = re.match(r".*#\d{4}$", discord_name)
    staticData = None

    if properFormat:
        colead_staticData = db.GetUserStaticData(discord_name,
                                                 static_data.static_name)
        adding_userData = None

        if not colead_staticData:  # No data for the specified static was found
            raise Exception(
                f'User: {discord_name} is not in order {static_data.static_name} and cannot be promoted to co-lead'
            )

        if not adding_user_is_officer:  #The user making the change is not an officer in the discord
            adding_userData = db.GetUserStaticData(adding_user,
                                                   static_data.static_name)
            if not adding_userData:  # No data for the specific static was found...
                raise Exception(
                    f'Cannot promote User: {discord_name} because you are not in the specified Order'
                )

            #Check if adding user is the leader of the order and
            if staticData.static_lead != adding_user:
                raise Exception(
                    f'Cannot promote User:{discord_name} because you are not the order\'s leader'
                )

        static_data.static_colead = discord_name
        staticObj = Static(static_data)
        staticObj.Update()

        role_manager.AddAddColeadRole(discord_name)

        previous_colead = static_data.static_colead
        if previous_colead != 'None':
            splitname = previous_colead.static_colead.split('#')
            discord.utils.get(discData.members,
                              name=splitname[0],
                              discriminator=splitname[1])

            if not db.CheckIsCoLead:  # User is no longer a co_lead of any static, remove their role
                role_manager.RemoveColeadRole(previous_colead)
    else:
        raise NameError("Invalid format, should be like !addcolead Seyon#1392")
Esempio n. 5
0
async def on_message(message):
    chanId = message.channel.id
    if chanId == chanIds["roster"] and message.author.id != 735708593294147674:
        await DeleteMessageFromChannel(message.channel, message)

    elif chanId == chanIds["events"]:

        if message.content.startswith('!create'):
            event = Event()
            err = event.from_message(message)

            if err != "":
                await message.channel.send(err)

            elif not event.isValid():
                await message.channel.send(
                    "Passed data was unable to be parsed please revise your input \n"
                    f'Format: {eventFormatMessage} \n Example: {createEventEx}'
                )
            else:
                # Add the event to the database (and spreadsheet?)
                # eventsWorksheet = sheet.add_worksheet(title=eventName, rows=500, cols=7)
                # eventsWorksheet.update('A1:F1', ['DiscordTag', 'Attended', 'Date', dateOfEvent, 'Time', eventTimeAsInt])
                await message.channel.send(
                    f'An event called <{event.event_name}> has been scheduled')

        elif message.content.startswith('!events'):
            return
        elif message.content.startswith('!startevent'):
            return

    elif chanId == chanIds["staticCreation"]:
        msgUser = message.author
        userStr = str(msgUser)
        manager = StaticsManagement()

        if message.content.startswith('!help'):  #display commands and
            await message.channel.send(
                "Here is a list of valid commands: \n"
                f'Create: {createStaticEx} \n'
                f'Join: {joinStaticEx} \n'
                f'------------------------------ \n'
                f'Disband [Order leader only]: {disbandEx}\n'
                f'Promote Lead [Order leader only]: {promoteLeaderEx} \n'
                f'Add Colead [Order leader only]: {promoteColeadEx} \n')

        elif message.content.startswith('!startorder'):

            db = staticsDb()
            static = Static()
            static.from_creation_request(message.content, str(message.author))

            try:
                (static, role) = await StartOrder(static, discordG)

                manager.setStaticInfo(static)
                manager.initRoles(discordIds, discordG, role,
                                  static.static_name)
                await manager.AddLeaderRole(message.author)
                await manager.AddStaticRole(message.author)
                await manager.AddDiscordRole(message.author)
                await manager.RemoveBasicTag(message.author)

                JoinOrder(static.static_name, msgUser)
                await message.channel.send(
                    f'The order {static.static_name}. The role <@&{static.discord_id}>, text channel, and voice channel were created for the Orders use'
                )

            except (Exception, DatabaseError) as error:
                await message.channel.send(str(error))
                return

        elif message.content.startswith('!joinorder'):

            db = staticsDb()
            staticName = [x.strip() for x in message.content.split(' ', 1)][1]
            data = db.GetStaticDataByName(staticName)

            if not data:
                await message.channel.send(
                    f'Order, {staticName}, does not exist')
                return

            staticRole = discord.utils.get(discordG.roles,
                                           id=int(data.discord_id))

            try:
                JoinOrder(data.static_name, msgUser)
                manager.setStaticInfo(Static(data))
                manager.initRoles(discordIds, discordG, staticRole,
                                  data.static_name)
                await manager.RemoveBasicTag(msgUser
                                             )  # Not everyone needs this
                await manager.AddDiscordRole(
                    msgUser)  # Not everyone needs this every time
                await manager.AddStaticRole(
                    msgUser)  # Unique to the order they are joining

                await message.channel.send(
                    f'You have successfully joined {data.static_name}.')

            except (Exception, DatabaseError) as error:
                await message.channel.send(str(error))
                return

        elif message.content.startswith('!addcolead'):
            db = staticsDb()
            # split on space, get the 2nd item (everything after the command) split on the first comma
            splitString = [
                x.strip()
                for x in message.content.split(' ', 1)[1].split(',', 1)
            ]
            new_colead = splitString[0]
            order_name = splitString[1]

            try:
                data = db.GetStaticDataByName(order_name)
                if not data:
                    await message.channel.send(
                        f'Order, {order_name}, does not exist')

                staticRole = discord.utils.get(discordG.roles,
                                               id=int(data.discord_id))
                manager.setStaticInfo(Static(data))
                manager.initRoles(discordIds, discordG, staticRole,
                                  data.static_name)

                await PromoteCoLead(data, new_colead, userStr, False, discordG,
                                    manager)
            except (Exception) as error:
                await message.channel.send(str(error))
                return

        elif message.content.startswith('!disbandorder'):
            return True
            db = staticsDb()
            staticName = [x.strip() for x in message.content.split(' ', 1)][1]

            # Get the game that the static is for before deleting
            games = db.GetGames()
            game = None

            if games == []:
                await message.channel.send(
                    "Error when fetching games. Contact Seyon")
                return

            await message.channel.send(f'What game is this order for? \n' +
                                       "\n".join(games))

            def check(m):
                return m.content in games and m.channel == message.channel

            try:
                msg = await client.wait_for('message',
                                            timeout=30.0,
                                            check=check)
                if msg.content in games:
                    game = msg.content
                    await message.channel.send('Processing....')
                else:
                    await message.channel.send(
                        'Game is not in the list. If this is an error contact Seyon or Tockz.'
                    )
                    return
            except asyncio.TimeoutError:
                await message.channel.send(
                    'Operation has timed out. You will need to start the creation process.'
                )
                return

            try:
                static_data = db.GetStaticDataByName(staticName, game)

                if static_data is not None:
                    manager.setStaticInfo(Static(static_data))
                    staticRole = discord.utils.get(discordG.roles,
                                                   id=static_data.discord_id)

                    manager.initRoles(discordIds, discordG, staticRole,
                                      static_data.static_name)
                else:
                    await message.channel.send(
                        f'Unable to delete static, {staticName}, does not exist for game, {game}'
                    )
                    return

                if userStr == static_data.static_lead:
                    static_users = db.GetAllUsersInStatic(
                        staticName, static_data.game_id)

                    if static_users:
                        for user in static_users:
                            db.DropUserFromStatic(staticName, user)
                            splitname = user.split('#')
                            discUser = discord.utils.get(
                                discordG.members,
                                name=splitname[0],
                                discriminator=splitname[1])

                            try:
                                inAnyStatic = db.GetUsersStatics(str(discUser))
                                if not inAnyStatic:  # No order, add basic discord tag
                                    manager.AddBasicTag(discUser)

                            except Exception as Error:
                                await (
                                    "There was an error when checking static data"
                                )
                                return

                        db.dropStatic(staticName)
                    else:
                        await message.channel.send(
                            f'Order: {staticName}, has no users')

                else:
                    await message.channel.send(
                        f'You need to be the leader of the order to disband.')

            except (Exception, DatabaseError) as error:
                await message.channel.send(
                    "There was an error when disbanding Order by. Contact Seyon"
                )
                return

        elif message.content.startswith('!promotelead'):
            db = staticsDb()
            new_lead = [x.strip() for x in message.content.split(' ', 1)][1]

            leadHasProperFormat = re.match(r".*#\d{4}$", new_lead)

            if leadHasProperFormat:
                try:
                    new_leadData = db.GetUserStaticData(new_lead)
                    userData = db.GetUserStaticData(msgUser)

                    if userData[1] == new_leadData[1]:  # Same static

                        data = db.GetStaticDataByName(new_leadData[1])
                        manager.setStaticInfo(Static(data))
                        manager.initRoles(discordIds, discordG)

                        data.static_lead = new_lead
                        splitname = new_lead.split('#')
                        discUser = discord.utils.get(
                            discordG.members,
                            name=splitname[0],
                            discriminator=splitname[1])

                        staticObj = Static(data)
                        staticObj.Update(
                        )  # Make sure update is successful before updating roles
                        manager.AddLeaderRole(discUser)
                        manager.RemoveLeaderRole(msgUser)
                    else:
                        await message.channel.send(
                            f'User: {new_lead} is not in Order: {userData[1]}')

                except (Exception, DatabaseError) as error:
                    await message.channel.send(
                        "There was an error when promoting a new lead. Contact Seyon"
                    )
                    return
            else:
                await message.channel.send(
                    f'User {new_lead}, is not formatted properly. Proper Format: {promoteLeaderEx}'
                )

    elif chanId == chanIds["orderDisplay"]:
        if message.content.startswith('!report'):

            message_hist = await message.channel.history().flatten()
            to_delete = []
            for msg in message_hist:
                if str(
                        msg.author
                ) != 'Tockz#0001':  #Put in limited time exception to deleting tockz old messages
                    to_delete.append(msg)

            await DeleteMessageFromChannel(message.channel, to_delete)

            db = staticsDb()
            orders_list = db.FetchAllMembersList()
            for order in orders_list:
                members = None
                if order[3] is not None:
                    members = order[3].split(",")

                co_lead = "No Colead"
                if order[2] is not None:
                    co_lead = order[2]

                out_message = (f'** {order[0].capitalize()} ** \n'
                               f'```asciidoc\n'
                               f'[Captain]\n'
                               f'{order[1]}\n\n'
                               f'[Knight]\n'
                               f'{co_lead}\n\n'
                               f'[Members]\n')

                if members is not None:
                    for member in members:
                        out_message += f'{member} \n'
                else:
                    out_message += "No Members \n"

                out_message += '\n``` \n'
                await message.channel.send(out_message)
        return
Esempio n. 6
0
 def create(self):
     """ Creates a static db entry """
     db = staticsDb()
     self.id = db.createNewStatic(self)
async def StartOrder(order, guild):
    """ 
        Checks order information and creates it 
        Cannot create an order if one of the same name exists

        Returns a tuple containing the updated order and the newly created discord role object
    """
    db = staticsDb()
    text_chat = Chat('text')
    voice_chat = Chat('voice')

    errorMsg = "There was an exception while checking your Order status"
    try:
        if order.static_exists():
            raise NameError('Order already exists')
        else:
            errorMsg = 'Error when creating Order'
            order.create()

            errorMsg = 'Error when fetching discord category'

            text_chat.static_name = order.static_name
            voice_chat.static_name = order.static_name

            category = discord.utils.get(guild.categories,
                                         name='◇──◇Orders◇──◇')

            role_name = f'{order.static_name}'
            new_chan_name = f'{order.static_name}'

            errorMsg = 'Error while creating discord role'

            role = await guild.create_role(name=role_name)
            order.discord_id = role.id

            errorMsg = 'Error while creating text chat'

            await text_chat.CreateChat(guild, new_chan_name, category, role)

            errorMsg = 'Error while creating voice chat'

            await voice_chat.CreateChat(guild, new_chan_name, category, role)

            # Create entries in Chat table
            text_chat.static_name = order.static_name
            voice_chat.static_name = order.static_name

            errorMsg = 'Error while creating voice/text channel'

            db.Create_chat_channel(text_chat)
            db.Create_chat_channel(voice_chat)

            errorMsg = 'Error while updating static info'

            order.Update()
            return (order, role)

    except (Exception, DatabaseError) as error:
        raise Exception(errorMsg)

    return