Exemplo n.º 1
0
    def test_cache_typing(self, create_bot):
        """Tests the cache typing raises on incorrect instances"""
        with pytest.raises(ValueError):
            AntiSpamHandler(create_bot, cache=MockClass())

        with pytest.raises(ValueError):
            AntiSpamHandler(create_bot, cache=MockClass)

        with pytest.raises(ValueError):
            AntiSpamHandler(create_bot, cache=1)
    def test_library_inits(self, create_bot):
        hikari = AntiSpamHandler(create_bot, library=Library.HIKARI)
        assert isinstance(hikari.lib_handler, Hikari)

        pincer = AntiSpamHandler(
            create_bot, library=Library.PINCER, options=Options(use_timeouts=False)
        )
        assert isinstance(pincer.lib_handler, Pincer)

        with pytest.raises(UnsupportedAction):
            AntiSpamHandler(create_bot, library=Library.PINCER)

        with pytest.raises(UnsupportedAction):
            AntiSpamHandler(
                create_bot, library=Library.PINCER, options=Options(use_timeouts=True)
            )

        disnake = AntiSpamHandler(create_bot, library=Library.DISNAKE)
        assert isinstance(disnake.lib_handler, Disnake)

        enhanced_dpy = AntiSpamHandler(create_bot, library=Library.ENHANCED_DPY)
        assert isinstance(enhanced_dpy.lib_handler, EnhancedDPY)

        nextcord = AntiSpamHandler(create_bot, library=Library.NEXTCORD)
        assert isinstance(nextcord.lib_handler, Nextcord)

        with pytest.raises(UnsupportedAction):
            AntiSpamHandler(create_bot, library=Library.PYCORD)

        dpy = AntiSpamHandler(create_bot, library=Library.DPY)
        assert isinstance(dpy.lib_handler, DPY)
Exemplo n.º 3
0
    async def test_propagate_pre_invoke(self):
        bot = AsyncMock()
        bot.user.id = 919191
        create_handler = AntiSpamHandler(bot)

        class PreInvoke(BasePlugin):
            async def propagate(self, msg):
                return 1

        create_handler.register_plugin(PreInvoke())

        message = MockedMessage().to_mock()
        return_data = await create_handler.propagate(message)

        assert len(return_data.pre_invoke_extensions) == 1
        assert return_data.pre_invoke_extensions["PreInvoke"] == 1
Exemplo n.º 4
0
def create_handler():
    """Create a simple handler for usage"""
    mock = MockedMember(mock_type="bot").to_mock()
    mock.get_guild = Mock()
    return AntiSpamHandler(mock,
                           library=Library.DPY,
                           options=Options(use_timeouts=False))
    def test_custom_options(self, create_bot):
        """Tests custom options get set correct"""
        handler = AntiSpamHandler(
            create_bot, Library.DPY, options=Options(no_punish=True)
        )

        assert handler.options != Options()
        assert handler.options == Options(no_punish=True)
Exemplo n.º 6
0
    async def test_set_member_keyerror(self):
        """A test to test set_member_data throws a keyerror"""
        plugin_cache = PluginCache(AntiSpamHandler(commands.Bot("!")), MockClass())
        await plugin_cache.set_guild_data(1, "A test")
        with pytest.raises(MemberNotFound):
            await plugin_cache.get_member_data(1, 1)

        await plugin_cache.set_member_data(1, 1, "A member test")
Exemplo n.º 7
0
    def test_unregister_extension(self, create_handler: AntiSpamHandler):
        class Test(BasePlugin):
            def __init__(self, invoke=True):
                self.is_pre_invoke = invoke

        create_handler.register_plugin(Test(invoke=False))
        assert len(create_handler.after_invoke_extensions.values()) == 1
        create_handler.unregister_plugin("Test")
        assert len(create_handler.after_invoke_extensions.values()) == 0

        with pytest.raises(PluginError):
            create_handler.unregister_plugin("Invalid Extension")

        create_handler.register_plugin(Test())
        assert len(create_handler.pre_invoke_plugins.values()) == 1
        create_handler.unregister_plugin("Test")
        assert len(create_handler.pre_invoke_plugins.values()) == 0
 async def test_conflicting_init_args(self, create_bot):
     options = Options(
         no_punish=True,
         delete_spam=True,
         warn_only=True,
         per_channel_spam=True,
         use_timeouts=False,
     )
     AntiSpamHandler(create_bot, Library.DPY, options=options)
Exemplo n.º 9
0
    async def test_propagate_exits(self):
        bot = AsyncMock()
        bot.user.id = 9
        create_handler = AntiSpamHandler(bot)

        # TODO Until files get stubbed, we cant check this.
        """
        with pytest.raises(ValueError):
            await create_handler.propagate(1)

        with pytest.raises(ValueError):
            await create_handler.propagate("2")

        with pytest.raises(ValueError):
            await create_handler.propagate(MockClass)
        """

        return_data = await create_handler.propagate(
            MockedMessage(is_in_guild=False).to_mock()
        )
        assert return_data["status"] == "Ignoring messages from dm's"

        return_data = await create_handler.propagate(
            MockedMessage(author_id=9).to_mock()
        )
        assert return_data["status"] == "Ignoring messages from myself (the bot)"

        create_handler.options = Options(ignore_bots=True)
        return_data = await create_handler.propagate(
            MockedMessage(author_is_bot=True).to_mock()
        )
        assert return_data["status"] == "Ignoring messages from bots"
        create_handler.options = Options()

        create_handler.options.ignored_members.add(12345)
        return_data = await create_handler.propagate(MockedMessage().to_mock())
        assert return_data["status"] == "Ignoring this member: 12345"
        create_handler.options.ignored_members.discard(12345)

        create_handler.options.ignored_channels.add(98987)
        return_data = await create_handler.propagate(MockedMessage().to_mock())
        assert return_data["status"] == "Ignoring this channel: 98987"
        create_handler.options.ignored_channels.discard(98987)
Exemplo n.º 10
0
    async def test_set_guild_data_dictionaries(self, arg):
        """Test the cache sets guild addon's correct using lists of datetimes"""
        plugin_cache = PluginCache(AntiSpamHandler(commands.Bot("!")), MockClass())

        with pytest.raises(GuildNotFound):
            await plugin_cache.get_guild_data(1)

        await plugin_cache.set_guild_data(1, arg)

        assert await plugin_cache.get_guild_data(1) == arg
Exemplo n.º 11
0
    async def test_set_member_data_text(self, arg):
        """Test the cache sets member addon's correct using text"""
        plugin_cache = PluginCache(AntiSpamHandler(commands.Bot("!")), MockClass())

        with pytest.raises(GuildNotFound):
            await plugin_cache.get_member_data(1, 1)

        await plugin_cache.set_member_data(1, 1, arg)

        assert await plugin_cache.get_member_data(1, 1) == arg
Exemplo n.º 12
0
    async def test_propagate_role_raises(self):
        bot = AsyncMock()
        bot.user.id = 919191
        create_handler = AntiSpamHandler(bot)

        create_handler.options.ignored_roles.add(252525)

        message = MockedMessage().to_mock()
        return_data = await create_handler.propagate(message)
        assert return_data["status"] == "Ignoring this role: 252525"
Exemplo n.º 13
0
    async def test_propagate_after_invoke(self):
        bot = AsyncMock()
        bot.user.id = 919191
        create_handler = AntiSpamHandler(bot)

        class AfterInvoke(BasePlugin):
            def __init__(self):
                super().__init__(False)

            async def propagate(self, msg, data):
                return 2

        create_handler.register_plugin(AfterInvoke())

        message = MockedMessage().to_mock()
        return_data = await create_handler.propagate(message)

        assert len(return_data.after_invoke_extensions) == 1
        assert return_data.after_invoke_extensions["AfterInvoke"] == 2
Exemplo n.º 14
0
    async def test_set_member_data_dictionaries(self):
        """Test the cache sets member addon's correct"""
        plugin_cache = PluginCache(AntiSpamHandler(commands.Bot("!")), MockClass())
        arg = {"test": "tester"}

        with pytest.raises(GuildNotFound):
            await plugin_cache.get_member_data(1, 1)

        await plugin_cache.set_member_data(1, 1, arg)

        assert await plugin_cache.get_member_data(1, 1) == arg
Exemplo n.º 15
0
    async def test_propagate_guild_ignore(self):
        bot = AsyncMock()
        bot.user.id = 919191
        create_handler = AntiSpamHandler(bot)

        create_handler.options.ignored_guilds.add(1)

        message = MockedMessage(guild_id=1).to_mock()
        return_data = await create_handler.propagate(message)

        assert return_data["status"] == "Ignoring this guild: 1"
Exemplo n.º 16
0
    def test_register_extension(self, create_handler: AntiSpamHandler):
        with pytest.raises(PluginError):
            create_handler.register_plugin(MockClass())

        class Test(BasePlugin):
            def __init__(self, invoke=True):
                self.is_pre_invoke = invoke

        assert len(create_handler.pre_invoke_plugins.values()) == 0
        create_handler.register_plugin(Test())
        assert len(create_handler.pre_invoke_plugins.values()) == 1

        # Test overwrite
        with pytest.raises(PluginError):
            create_handler.register_plugin(Test())

        create_handler.register_plugin(Test(), force_overwrite=True)

        assert len(create_handler.after_invoke_extensions.values()) == 0
        create_handler.register_plugin(Test(invoke=False), force_overwrite=True)
        assert len(create_handler.after_invoke_extensions.values()) == 1
Exemplo n.º 17
0
    async def test_set_guild_data_text(self):
        """Test the cache sets guild addon's correct using text"""
        plugin_cache = PluginCache(AntiSpamHandler(commands.Bot("!")), MockClass())

        arg = "Hello world"

        with pytest.raises(GuildNotFound):
            await plugin_cache.get_guild_data(1)

        await plugin_cache.set_guild_data(1, arg)

        assert await plugin_cache.get_guild_data(1) == arg
Exemplo n.º 18
0
    def test_remove_ignored_member(self, create_handler: AntiSpamHandler):
        assert len(create_handler.options.ignored_members) == 0
        create_handler.remove_ignored_item(1, IgnoreType.MEMBER)
        assert len(create_handler.options.ignored_members) == 0

        create_handler.add_ignored_item(1, IgnoreType.MEMBER)
        assert len(create_handler.options.ignored_members) == 1
        create_handler.remove_ignored_item(1, IgnoreType.MEMBER)
        assert len(create_handler.options.ignored_members) == 0
Exemplo n.º 19
0
    def test_remove_ignored_channel(self, create_handler: AntiSpamHandler):
        assert len(create_handler.options.ignored_channels) == 0
        create_handler.remove_ignored_item(1, IgnoreType.CHANNEL)
        assert len(create_handler.options.ignored_channels) == 0

        create_handler.add_ignored_item(1, IgnoreType.CHANNEL)
        assert len(create_handler.options.ignored_channels) == 1
        create_handler.remove_ignored_item(1, IgnoreType.CHANNEL)
        assert len(create_handler.options.ignored_channels) == 0
Exemplo n.º 20
0
    def test_remove_ignored_guild(self, create_handler: AntiSpamHandler):
        assert len(create_handler.options.ignored_guilds) == 0
        create_handler.remove_ignored_item(1, IgnoreType.GUILD)
        assert len(create_handler.options.ignored_guilds) == 0

        create_handler.add_ignored_item(1, IgnoreType.GUILD)
        assert len(create_handler.options.ignored_guilds) == 1
        create_handler.remove_ignored_item(1, IgnoreType.GUILD)
        assert len(create_handler.options.ignored_guilds) == 0
Exemplo n.º 21
0
    def test_remove_ignored_role(self, create_handler: AntiSpamHandler):
        assert len(create_handler.options.ignored_roles) == 0
        create_handler.remove_ignored_item(1, IgnoreType.ROLE)
        assert len(create_handler.options.ignored_roles) == 0

        create_handler.add_ignored_item(1, IgnoreType.ROLE)
        assert len(create_handler.options.ignored_roles) == 1
        create_handler.remove_ignored_item(1, IgnoreType.ROLE)
        assert len(create_handler.options.ignored_roles) == 0
Exemplo n.º 22
0
    async def test_add_guild_log_channel_exists(self):
        mock_channel = MagicMock()
        mock_channel.id = 2
        mock_channel.guild.id = 1

        mock_bot = MagicMock()
        mock_bot.fetch_channel = AsyncMock(return_value=mock_channel)

        assert await mock_bot.fetch_channel.called_with(1)

        handler = AntiSpamHandler(mock_bot)
        await handler.cache.set_guild(Guild(1, Options()))

        await handler.add_guild_log_channel(2, 1)
        g = await handler.cache.get_guild(1)
        assert g.log_channel_id == 2
Exemplo n.º 23
0
    async def test_add_guild_log_channel(self):
        # Mock it up
        mock_channel = MagicMock()
        mock_channel.id = 2
        mock_channel.guild.id = 1

        mock_bot = MagicMock()
        mock_bot.fetch_channel = AsyncMock(return_value=mock_channel)

        assert await mock_bot.fetch_channel.called_with(1)

        handler = AntiSpamHandler(mock_bot, Library.DPY)

        await handler.add_guild_log_channel(2, 1)
        g = await handler.cache.get_guild(1)
        assert g.log_channel_id == 2
Exemplo n.º 24
0
    async def test_propagate_missing_perms(self):
        bot = AsyncMock()
        bot.user.id = 919191
        create_handler = AntiSpamHandler(bot)

        message = MockedMessage().to_mock()
        message.guild.me.guild_permissions.kick_members = False
        message.guild.me.guild_permissions.ban_members = False

        with pytest.raises(MissingGuildPermissions):
            await create_handler.propagate(message)

        # Reset cache rather then make a new test
        create_handler.cache.cache = {}

        message.guild.me.guild_permissions.kick_members = True
        message.guild.me.guild_permissions.ban_members = False

        with pytest.raises(MissingGuildPermissions):
            await create_handler.propagate(message)
Exemplo n.º 25
0
    async def test_save_to_dict_with_plugin(self, create_handler: AntiSpamHandler):
        await create_handler.cache.set_guild(Guild(1, Options()))

        class Plugin(BasePlugin):
            async def save_to_dict(self):
                return {"Plugin me"}

        create_handler.register_plugin(Plugin())
        data = await create_handler.save_to_dict()

        with open("tests/raw.json", "r") as file:
            stored_data = json.load(file)
        stored_data["pre_invoke_plugins"]["Plugin"] = {"Plugin me"}

        assert data == stored_data

        create_handler.unregister_plugin("Plugin")
        create_handler.register_plugin(Plugin(is_pre_invoke=False))
        stored_data["pre_invoke_plugins"] = {}
        stored_data["after_invoke_plugins"]["Plugin"] = {"Plugin me"}

        data_two = await create_handler.save_to_dict()
        assert data_two == stored_data
Exemplo n.º 26
0
import discord
from discord.ext import commands

from antispam import AntiSpamHandler
from jsonLoader import read_json

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

file = read_json("token")

bot.handler = AntiSpamHandler(bot)


@bot.event
async def on_ready():
    # On ready, print some details to standard out
    print(f"-----\nLogged in as: {bot.user.name} : {bot.user.id}\n-----")


@bot.event
async def on_message(message):
    await bot.handler.propagate(message)
    await bot.process_commands(message)


if __name__ == "__main__":
    bot.run(file["token"])
Exemplo n.º 27
0
import discord
from AntiSpamTrackerSubclass import MyCustomTracker
from discord.ext import commands

from antispam import AntiSpamHandler, Options
from antispam.enums import Library
from examples.jsonLoader import read_json

bot = commands.Bot(command_prefix=".", intents=discord.Intents.all())

file = read_json("token")

# Generally you only need/want AntiSpamHandler(bot)
bot.handler = AntiSpamHandler(
    bot,
    library=Library.YOUR_LIBRARY_HERE,
    options=Options(ignore_bots=False, no_punish=True, use_timeouts=False),
)
bot.tracker = MyCustomTracker(bot.handler, 3)
bot.handler.register_plugin(bot.tracker)


@bot.event
async def on_ready():
    # On ready, print some details to standard out
    print(f"-----\nLogged in as: {bot.user.name} : {bot.user.id}\n-----")


@bot.event
async def on_message(message):
    await bot.handler.propagate(message)
Exemplo n.º 28
0
 def test_options_typing(self, create_bot):
     """Tests the handler raises on incorrect option types"""
     with pytest.raises(ValueError):
         AntiSpamHandler(create_bot, options=1)
Exemplo n.º 29
0
 def test_dpy_setup(self):
     handler = AntiSpamHandler(commands.Bot(command_prefix="!"))
     assert handler.lib_handler.__class__.__name__ == "DPY"
Exemplo n.º 30
0
 def test_hikari_setup(self):
     handler = AntiSpamHandler(
         commands.Bot(command_prefix="!"), library=Library.HIKARI
     )
     assert handler.lib_handler.__class__.__name__ == "Hikari"