Example #1
0
 def setUp(self):
     """
     Simply setup our User obj before usage
     """
     self.user = User(0, 3, {})
     self.user.messages = Message(0, "Hello world", 0, 2, 3)
     self.user.messages = Message(1, "Foo Bar", 0, 2, 3)
Example #2
0
 def setUp(self):
     """
     Simply setup our User obj before usage
     """
     self.user = User(
         None, 0, 3, Static.DEFAULTS, logger=logging.getLogger(__name__)
     )
     self.user.messages = Message(0, "Hello world", 0, 2, 3)
     self.user.messages = Message(1, "Foo Bar", 0, 2, 3)
Example #3
0
    def propagate(self, value: discord.Message):
        """
        This method handles a message object and then adds it to
        the relevant user

        Parameters
        ==========
        value : discord.Message
            The message that needs to be propagated out
        """
        if not isinstance(value, discord.Message):
            raise ValueError("Expected message of type: discord.Message")

        self.CleanUp(datetime.datetime.now(datetime.timezone.utc))

        # No point saving empty messages, although discord shouldn't allow them anyway
        if not bool(value.content and value.content.strip()):
            if not value.embeds:
                return

            else:
                embed = value.embeds[0]
                if not isinstance(embed, discord.Embed):
                    return

                if embed.type.lower() != "rich":
                    return

                content = EmbedToString(embed)

                message = Message(
                    value.id,
                    content,
                    value.author.id,
                    value.channel.id,
                    value.guild.id,
                )

        else:
            message = Message(
                value.id,
                value.clean_content,
                value.author.id,
                value.channel.id,
                value.guild.id,
            )

        for messageObj in self.messages:
            if message == messageObj:
                raise DuplicateObject

        relationToOthers = []
        for messageObj in self.messages[::-1]:
            # This calculates the relation to each other
            relationToOthers.append(
                fuzz.token_sort_ratio(message.content, messageObj.content))

        self.messages = message
        self.logger.info(f"Created Message: {message.id}")

        # Check if this message is a duplicate of the most recent messages
        for i, proportion in enumerate(relationToOthers):
            if proportion >= self.options["messageDuplicateAccuracy"]:
                """
                The handler works off an internal message duplicate counter 
                so just increment that and then let our logic process it
                """
                self.duplicateCounter += 1
                message.isDuplicate = True
                break  # we don't want to increment to much

        if self.duplicateCounter >= self.options["messageDuplicateCount"]:
            self.logger.debug(
                f"Message: ({message.id}) requires some form of punishment")
            # We need to punish the user with something

            if (self.duplicateCounter >= self.options["warnThreshold"]
                    and self.warnCount < self.options["kickThreshold"]
                    and self.kickCount < self.options["banThreshold"]):
                self.logger.debug(f"Attempting to warn: {message.authorId}")
                """
                The user has yet to reach the warn threshold,
                after the warn threshold is reached this will
                then become a kick and so on
                """
                # We are still in the warning area
                # TODO Tell the user if its there final warning before a kick
                channel = value.channel
                message = Template(
                    self.options["warnMessage"]).safe_substitute({
                        "MENTIONUSER":
                        value.author.mention,
                        "USERNAME":
                        value.author.display_name,
                    })

                asyncio.ensure_future(self.SendToObj(channel, message))
                self.warnCount += 1

            elif (self.warnCount >= self.options["kickThreshold"]
                  and self.kickCount < self.options["banThreshold"]):
                self.logger.debug(f"Attempting to kick: {message.authorId}")
                # We should kick the user
                # TODO Tell the user if its there final kick before a ban
                dcChannel = value.channel
                message = Template(
                    self.options["kickMessage"]).safe_substitute({
                        "MENTIONUSER":
                        value.author.mention,
                        "USERNAME":
                        value.author.display_name,
                    })
                asyncio.ensure_future(
                    self.PunishUser(
                        value.guild,
                        value.author,
                        dcChannel,
                        f"You were kicked from {value.guild.name} for spam.",
                        message,
                        Static.KICK,
                    ))
                self.kickCount += 1

            elif self.kickCount >= self.options["banThreshold"]:
                self.logger.debug(f"Attempting to ban: {message.authorId}")
                # We should ban the user
                dcChannel = value.channel
                message = Template(self.options["banMessage"]).safe_substitute(
                    {
                        "MENTIONUSER": value.author.mention,
                        "USERNAME": value.author.display_name,
                    })
                asyncio.ensure_future(
                    self.PunishUser(
                        value.guild,
                        value.author,
                        dcChannel,
                        f"You were banned from {value.guild.name} for spam.",
                        message,
                        Static.BAN,
                    ))
                self.kickCount += 1

            else:
                print("else?")
                raise LogicError
Example #4
0
 def test_messageRaisesDuplicate(self):
     with self.assertRaises(DuplicateObject):
         self.user.messages = Message(1, "Testing", 0, 2, 3)
Example #5
0
 def test_messageAssignment(self):
     self.assertEqual(len(self.user.messages), 2)
     self.user.messages = Message(3, "Test", 0, 2, 3)
     self.assertEqual(len(self.user.messages), 3)
Example #6
0
 def setUp(self):
     """
     Simply setup our Message obj before usage
     """
     self.message = Message(0, "Hello world", 2, 3, 4)
Example #7
0
 def test_eqNotEqual(self):
     obj = Message(1, "Hello world", 2, 3, 4)
     self.assertFalse(self.message == obj)
Example #8
0
 def test_eqEqual(self):
     obj = Message(0, "Hello world", 2, 3, 4)
     self.assertTrue(self.message == obj)
Example #9
0
    def propagate(self, value: discord.Message):
        """
        This method handles a message object and then adds it to
        the relevant user

        Parameters
        ==========
        value : discord.Message
            The message that needs to be propagated out
        """
        if not isinstance(value, discord.Message):
            raise ValueError("Expected message of type: discord.Message")

        message = Message(
            value.id,
            value.clean_content,
            value.author.id,
            value.channel.id,
            value.guild.id,
        )
        for messageObj in self.messages:
            if message == messageObj:
                raise DuplicateObject

        # TODO Add checks for if there isn't any content. If there isn't
        #      we shouldn't bother saving them

        # TODO Compare incoming message to other messages in order
        relationToOthers = []
        for messageObj in self.messages[::-1]:
            # This calculates the relation to each other
            relationToOthers.append(
                fuzz.token_sort_ratio(message.content, messageObj.content))

        self.messages = message

        # Check if this message is a duplicate of the most recent messages
        for i, proportion in enumerate(relationToOthers):
            if proportion >= self.options["messageDuplicateAccuracy"]:
                """
                The handler works off an internal message duplicate counter 
                so just increment that and then let our logic process it
                """
                self.duplicateCounter += 1
                message.isDuplicate = True
                break  # we don't want to increment to much

        if self.duplicateCounter >= self.options["messageDuplicateCount"]:
            print("Punish time")
            # We need to punish the user with something

            # TODO Figure out why the logic likes having +1 of the actual count
            #      before it decides its time to actually punish the user properly

            if (self.duplicateCounter >= self.options["warnThreshold"]
                    and self.warnCount < self.options["kickThreshold"]
                    and self.kickCount < self.options["banThreshold"]):
                print("Warn time")
                """
                The user has yet to reach the warn threshold,
                after the warn threshold is reached this will
                then become a kick and so on
                """
                # We are still in the warning area
                channel = value.channel
                message = Template(
                    self.options["warnMessage"]).safe_substitute({
                        "MENTIONUSER":
                        value.author.mention,
                        "USERNAME":
                        value.author.display_name,
                    })

                asyncio.ensure_future(self.SendToObj(channel, message))
                self.warnCount += 1

            elif (self.warnCount >= self.options["kickThreshold"]
                  and self.kickCount < self.options["banThreshold"]):
                print("kick time")
                # We should kick the user
                dcChannel = value.channel
                message = Template(
                    self.options["kickMessage"]).safe_substitute({
                        "MENTIONUSER":
                        value.author.mention,
                        "USERNAME":
                        value.author.display_name,
                    })
                asyncio.ensure_future(
                    self.KickFromGuild(
                        value.guild,
                        value.author,
                        dcChannel,
                        f"You were kicked from {value.guild.name} for spam.",
                        message,
                    ))
                self.kickCount += 1

            elif self.kickCount >= self.options["banThreshold"]:
                print("ban time")
                # We should ban the user
                pass

            else:
                print("else?")
                raise LogicError
Example #10
0
 def test_messageRaisesMismatch(self):
     with self.assertRaises(ObjectMismatch):
         self.user.messages = Message(20, "Testing", 20, 20, 20)