Esempio n. 1
0
def loadXML():
    filename = 'legislation.xml'
    logging.debug('Loading XML with local storage file ' + filename)
    try:
        f = open(filename, 'r')
        text = f.read()
        f.close()
        logging.debug('Loaded from local storage')
        return text
    except IOError:
        logging.error('Local storage file not found')
        return None
    async def cog_command_error(self, ctx, error):

        # Missing Role #
        if isinstance(error, commands.MissingRole):
            await ctx.send(
                ':no_entry: You must have a team role! For example role: team1'
            )

        # No Private Message #
        if isinstance(error, commands.NoPrivateMessage):
            await ctx.author.send(
                ':no_entry: Please use all commands in a Server (Not Direct Messages)!'
            )

        # Any other error #
        else:
            logging.error(f'Unexpected error: {error}')
            await ctx.send(
                f':satellite: (Main)An unexpected error occurred! ```The error is: {error}``` '
            )
    async def cog_command_error(self, ctx, error):

        # Missing Role #
        if isinstance(error, commands.MissingRole):
            await ctx.send(':no_entry: You must have a team role! For example role: team1')

        # Channel Not Found #
        elif isinstance(error, commands.ChannelNotFound):
            await ctx.send(':no_entry: You must use this command in you team channel e.g. team1!')

        # Missing Required Argument #
        elif isinstance(error, commands.MissingRequiredArgument):
            if ctx.command.name == 'answer':
                await ctx.send(f':no_entry: You need to specify a answer! ```mr {ctx.command.name} hello world```')
            else:
                await ctx.send(f':no_entry: You need to specify the property! e.g. ```mr {ctx.command.name} brown1```')

        # No Private Message #
        elif isinstance(error, commands.NoPrivateMessage):
            await ctx.author.send(':no_entry: Please use all commands in a Server (Not Direct Messages)!')

        # Invalid Property Name #
        elif isinstance(error, MonopolyRunError.InvalidPropertyName):
            await ctx.send(f':no_entry: Please enter a valid property! e.g. ```mr {ctx.command.name} brown1``` For a list of properties see the properties channel!')

        # Not In Team Channel #
        elif isinstance(error, MonopolyRunError.NotInTeamChannel):
            await ctx.send(':no_entry: Please make sure you have the correct role for the correct team channel! e.g.```role team1 for channel team1```')

        # Already visited #
        elif isinstance(error, MonopolyRunError.AlreadyVisted):
            await ctx.send(':no_entry: You have already answered the question for that property correctly!')

        # Database Table Not Found #
        elif isinstance(error, MonopolyRunError.DatabaseTableNotFound):
            await ctx.send(':no_entry: No table was found in the database for this Server! Have you run setup?')

        # Any other error #
        else:
            logging.error(f'Unexpected error: {error}')
            await ctx.send(f':satellite: (Main)An unexpected error occurred! ```The error is: {error}``` ')
Esempio n. 4
0
    async def cog_command_error(self, ctx, error):
        # Missing Required Argument #
        if isinstance(error, commands.MissingRequiredArgument):
            if ctx.command.name == 'setup':
                await ctx.send(
                    f':no_entry: Please specify both the number of teams to create and the question set! ```e.g. mr {ctx.command} 4 test```'
                )
            elif ctx.command.name == 'remove':
                await ctx.send(
                    f':no_entry: Please enter true to confirm removal! ```e.g. mr {ctx.command} true```'
                )

        # Missing Permissions #
        elif isinstance(error, commands.MissingPermissions):
            await ctx.send(
                ':no_entry: You do not have permission to use that command!')

        # Bad Argument #
        elif isinstance(error, commands.BadArgument):
            if ctx.command.name == 'setup':
                await ctx.send(
                    f':no_entry: Please enter a valid number of teams to create! ```e.g. mr {ctx.command} 4 test```'
                )
            elif ctx.command.name == 'remove':
                await ctx.send(
                    f':no_entry: Please enter true to confirm removal! ```e.g. mr {ctx.command} true```'
                )

        # Missing Role #
        elif isinstance(error, commands.MissingRole):
            await ctx.send(
                ':no_entry: You need the Monopoly Run Administrator role to use that command!'
            )
        # Database records not found #
        elif isinstance(error, MonopolyRunError.DatabaseRecordNotFound):
            await ctx.send(
                ':no_entry: No database records were found for this sever! Have you run setup?'
            )

        # Too many teams #
        elif isinstance(error, MonopolyRunError.TooManyTeams):
            if ctx.command.name == 'add':
                await ctx.send(
                    ':no_entry: You can not create any teams as you will be over the maximum allowed amount of teams!'
                )
            else:
                await ctx.send(':no_entry: Maximum amount of teams is 46!')

        # Not enough teams #
        elif isinstance(error, MonopolyRunError.NotEnoughTeams):
            await ctx.send(':no_entry: Minimum amount of teams is 2!')

        # No Private Message #
        elif isinstance(error, commands.NoPrivateMessage):
            await ctx.author.send(
                ':no_entry: Please use all commands in a Server (Not Direct Messages)!'
            )

        # Any other error #
        else:
            logging.error(f'Unexpected error: {error}')
            await ctx.send(
                f':satellite: An unexpected error occurred! ```The error is: {error}``` '
            )
    async def answer(self, ctx, *, strAnswer):

        # Declare some key variables #
        strGuildID = str(ctx.guild.id)
        strTeamName = str(self.funTeamRole(ctx))

        # Get teams current location #
        dbcursor.execute(f"SELECT current_location FROM tbl_{strGuildID} WHERE id = ?", (strTeamName, ))
        lisCurrentLocation = dbcursor.fetchall()
        tupCurrentLocation = lisCurrentLocation[0]
        strCurrentLocation = tupCurrentLocation[0]

        # Check if team has said they are going to visit the property #
        if strCurrentLocation not in self.lisProperties:
            if strCurrentLocation == '':
                await ctx.send(':tophat: You need to use goto first to tell the game where your going! ```mr goto brown1```')
                return None

        # Set property to location #
        strProperty = strCurrentLocation

        # Get teams money and if they have visited this property from the database #
        dbcursor.execute(f"SELECT money, {strProperty}_visited FROM tbl_{strGuildID} WHERE id = ?", (strTeamName, ))
        lisMoneyVisted = dbcursor.fetchall()
        for item in lisMoneyVisted:
            intTeamsMoney = item[0]
            strVisted = item[1]

        # Check if the team has already visited that property #
        if strVisted == 'Y':
            raise MonopolyRunError.AlreadyVisted(strProperty)

        # Check if a team owns the property #
        dbcursor.execute(f"SELECT id FROM tbl_{strGuildID} WHERE {strProperty}_owner = 'Y'")
        lisOwner = dbcursor.fetchall()
        if not lisOwner:
            strOwner = None
        else:
            tupOwner = lisOwner[0]
            strOwner = tupOwner[0]

            # Get how much money the owner has #
            dbcursor.execute(f"SELECT money FROM tbl_{strGuildID} WHERE id = ?", (strOwner, ))
            lisOwnersMoney = dbcursor.fetchall()
            tupOwnersMoney = lisOwnersMoney[0]
            intOwnersMoney = tupOwnersMoney[0]

        # Get which set of Questions the guild is using #
        dbcursor.execute("SELECT questions FROM tbl_guilds WHERE id = ?", (strGuildID, ))
        lisQuestions = dbcursor.fetchall()
        tupQuestions = lisQuestions[0]
        strQuestions = tupQuestions[0]

        # Get answer and value from database #
        dbcursor.execute(f"SELECT answer, value FROM tbl_{strQuestions} WHERE id = ?", (strProperty, ))
        lisOwnerAnswer = dbcursor.fetchall()
        for item in lisOwnerAnswer:
            strCorrectAnswers = item[0]
            intValue = item[1]

        # Check if a set of properties is owned by one team #
        lisPropertiesToSelect = [i for i in self.lisProperties if i.startswith(re.sub('[0-9]+', '', strProperty))]
        intNumberofPropertiesToSelect = len(lisPropertiesToSelect)
        if intNumberofPropertiesToSelect == 2:
            dbcursor.execute(f"SELECT id FROM tbl_{strGuildID} WHERE {lisPropertiesToSelect[0]}_owner = 'Y' and {lisPropertiesToSelect[1]}_owner = 'Y'")
            lisPropertiesInSet = dbcursor.fetchall()
            if not lisPropertiesInSet:
                blnDoubleRent = False
            else:
                blnDoubleRent = True

        elif intNumberofPropertiesToSelect == 3:
            dbcursor.execute(f"SELECT id FROM tbl_{strGuildID} WHERE {lisPropertiesToSelect[0]}_owner = 'Y' and {lisPropertiesToSelect[1]}_owner = 'Y' and {lisPropertiesToSelect[2]}_owner = 'Y'")
            lisPropertiesInSet = dbcursor.fetchall()
            if not lisPropertiesInSet:
                blnDoubleRent = False
            else:
                blnDoubleRent = True

        elif intNumberofPropertiesToSelect == 4:
            dbcursor.execute(f"SELECT id FROM tbl_{strGuildID} WHERE {lisPropertiesToSelect[0]}_owner = 'Y' and {lisPropertiesToSelect[1]}_owner = 'Y' and {lisPropertiesToSelect[2]}_owner = 'Y' and {lisPropertiesToSelect[3]}_owner = 'Y'", ())
            lisPropertiesInSet = dbcursor.fetchall()
            if not lisPropertiesInSet:
                blnDoubleRent = False
            else:
                blnDoubleRent = True
  
        else:
            blnDoubleRent = False

        # Check if answer is correct #
        lisCorrectAnswers = strCorrectAnswers.split('-')
        for item in lisCorrectAnswers:

            # Convert to lowercase and remove spaces #
            strCorrectAnswer = item.lower()
            strCorrectAnswer = re.sub("\s+", '', strCorrectAnswer)

            strAnswer = strAnswer.lower()
            strAnswer = re.sub("\s+", '', strAnswer)
            # Use fuzzy-wuzzy to compare the users answer with the correct answer #
            intPartialRatio = fuzz.partial_ratio(strCorrectAnswer, strAnswer)
            intTokenSetRatio = fuzz.token_set_ratio(strCorrectAnswer, strAnswer)

            if intPartialRatio >= 80 or intTokenSetRatio >= 80:
                blnAnswerCorrect = True
                break
            else:
                blnAnswerCorrect = False

        # Checks #
        # Answer is correct AND the property is NOT owned #
        if blnAnswerCorrect is True and strOwner is None and blnDoubleRent is False:

            # Update property visited in database #
            dbcursor.execute(f"UPDATE tbl_{strGuildID} SET {strProperty}_visited = 'Y' WHERE id = ?", (strTeamName, ))

            # Update teams money and set owner #
            intUpdatedMoney = intTeamsMoney + intValue
            dbcursor.execute(f"UPDATE tbl_{strGuildID} SET money = '{intUpdatedMoney}', {strProperty}_owner = 'Y' WHERE id = '{strTeamName}'")

            # Notify announcements of the Owner #
            catMonopolyRun = utils.get(ctx.guild.categories, name="Monopoly Run")
            chaAnnouncementChannel = utils.get(ctx.guild.channels, name="announcements", category_id=catMonopolyRun.id)
            await chaAnnouncementChannel.send(f':house: {strTeamName} now owns {strProperty}!')

            await ctx.send(f':white_check_mark: You now own {strProperty}!')

            # Set current_location to empty #
            dbcursor.execute(f"UPDATE tbl_{strGuildID} SET current_location = ? WHERE id = ?", ("", strTeamName))

        # Answer is correct AND the property is owned #
        elif blnAnswerCorrect is True and strOwner is not None and blnDoubleRent is False:

            # Update property visited in database #
            dbcursor.execute(f"UPDATE tbl_{strGuildID} SET {strProperty}_visited = 'Y' WHERE id = ?", (strTeamName, ))

            # Update teams money #
            intUpdatedMoney = intTeamsMoney + intValue
            dbcursor.execute(f"UPDATE tbl_{strGuildID} SET money = ? WHERE id = ?", (intUpdatedMoney, strTeamName))

            # Update owners money #
            chaOwner = utils.get(ctx.guild.channels, name=strOwner)
            await chaOwner.send(f':dollar: {strTeamName} just paid £{intValue} on {strProperty}!')
            intUpdatedMoney = intOwnersMoney + intValue
            dbcursor.execute(f"UPDATE tbl_{strGuildID} SET money = ? WHERE id = ?", (intUpdatedMoney, strOwner))
            await ctx.send(f':white_check_mark: However since: {strOwner} already owns that property you paid: £{intValue} in rent!')

            # Set current_location to empty #
            dbcursor.execute(f"UPDATE tbl_{strGuildID} SET current_location = ? WHERE id = ?", ("", strTeamName))

        # Answer is correct AND the property is owned  AND double rent #
        elif blnAnswerCorrect is True and strOwner is not None and blnDoubleRent is True:

            # Update property visited in database #
            dbcursor.execute(f"UPDATE tbl_{strGuildID} SET {strProperty}_visited = 'Y' WHERE id = ?", (strTeamName, ))

            # Update teams money #
            intUpdatedMoney = intTeamsMoney + intValue
            dbcursor.execute(f"UPDATE tbl_{strGuildID} SET money = ? WHERE id = ?", (intUpdatedMoney, strTeamName))

            # Update owners money #
            chaOwner = utils.get(ctx.guild.channels, name=strOwner)
            await chaOwner.send(f':dollar: {strTeamName} just paid £{intValue * 2} on {strProperty}!')
            intUpdatedMoney = intOwnersMoney + (intValue * 2)
            dbcursor.execute(f"UPDATE tbl_{strGuildID} SET money = ? WHERE id = ?", (intUpdatedMoney, strOwner))
            await ctx.send(f':white_check_mark: However since: {strOwner} already owns that property and the other properties in the same group you paid: £{intValue*2} in rent!')

            # Set current_location to empty #
            dbcursor.execute(f"UPDATE tbl_{strGuildID} SET current_location = ? WHERE id = ?", ("", strTeamName))

        # Answer is incorrect AND the property is NOT owned #
        elif blnAnswerCorrect is False and strOwner is None and blnDoubleRent is False:
            await ctx.send(':negative_squared_cross_mark: Try again!')

        # Answer is incorrect AND the property is owned  #
        elif blnAnswerCorrect is False and strOwner is not None and blnDoubleRent is False:

            await ctx.send(f':negative_squared_cross_mark: Try again! However since: {strOwner} already owns that property you paid: £{intValue} in rent!')

            # Update owners money #
            chaOwner = utils.get(ctx.guild.channels, name=strOwner)
            await chaOwner.send(f':dollar: {strTeamName} just paid £{intValue} on {strProperty}, even though they got the answer incorrect!')
            intUpdatedMoney = intOwnersMoney + intValue
            dbcursor.execute(f"UPDATE tbl_{strGuildID} SET money = ? WHERE id = ?", (intUpdatedMoney, strOwner))

        # Answer is incorrect AND the property is owned AND double rent  #
        elif blnAnswerCorrect is False and strOwner is not None and blnDoubleRent is True:

            await ctx.send(f':negative_squared_cross_mark: Try again! However since: {strOwner} already owns that property and the other properties in the same group you paid: £{intValue*2} in rent!')

            # Update owners money #
            chaOwner = utils.get(ctx.guild.channels, name=strOwner)
            await chaOwner.send(f':dollar: {strTeamName} just paid £{intValue * 2} on {strProperty}, even though they got the answer incorrect!')
            intUpdatedMoney = intOwnersMoney + (intValue * 2)
            dbcursor.execute(f"UPDATE tbl_{strGuildID} SET money = ? WHERE id = ?", (intUpdatedMoney, strOwner))

        # Error #
        else:

            # Set current_location to empty #
            dbcursor.execute(f"UPDATE tbl_{strGuildID} SET current_location = ? WHERE id = ?", ("", strTeamName))
            logging.error(f'Unexpected error: Answer, Correct Answer, Answer Correct, Owner, Double Rent, Afford is not valid! {strAnswer, strCorrectAnswer, blnAnswerCorrect, strOwner, blnDoubleRent, }')
            await ctx.send(f':satellite: An unexpected error occurred! ```The error is: Answer, Correct Answer, Answer Correct, Owner, Double Rent, Afford is not valid! {strAnswer, strCorrectAnswer, blnAnswerCorrect, strOwner, blnDoubleRent, }``` ')