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)
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))
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")
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)
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)
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"
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
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
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
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"
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
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
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
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
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)
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
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)
import discord from discord.ext import commands from antispam import AntiSpamHandler, Options from antispam.plugins import AntiSpamTracker from jsonLoader import read_json bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) file = read_json("token") bot.handler = AntiSpamHandler(bot, options=Options(no_punish=True, message_duplicate_count=3)) bot.tracker = AntiSpamTracker(bot.handler, 5) bot.handler.register_plugin(bot.tracker) """ For every message after (and including your third duplicate message) it adds one to your tracked count When its hits 5 'spammed' messages, it triggers. Which is 7 messages overall. """ @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)
import hikari from antispam import AntiSpamHandler from antispam.enums import Library from examples.jsonLoader import read_json file = read_json("token") bot = hikari.GatewayBot(token=file["token"], ) handler = AntiSpamHandler(bot, library=Library.HIKARI) @bot.listen() async def ping(event: hikari.GuildMessageCreateEvent) -> None: if event.is_bot or not event.content: return await handler.propagate(event.message) bot.run()
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"])
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)
async def test_custom_lib(self, create_bot): ash = AntiSpamHandler(create_bot, library=Library.CUSTOM) with pytest.raises(UnsupportedAction): await ash.propagate(MockedMessage().to_mock())
def test_dpy_setup(self): handler = AntiSpamHandler(commands.Bot(command_prefix="!")) assert handler.lib_handler.__class__.__name__ == "DPY"
def test_hikari_setup(self): handler = AntiSpamHandler( commands.Bot(command_prefix="!"), library=Library.HIKARI ) assert handler.lib_handler.__class__.__name__ == "Hikari"
from pincer import Client, Intents from pincer.objects import UserMessage from antispam import AntiSpamHandler from antispam.enums import Library from examples.jsonLoader import read_json file = read_json("token") class Bot(Client): @Client.event async def on_ready(self): print(f"Started client on {self.bot}\n" "Registered commands: " + ", ".join(self.chat_commands)) @Client.event async def on_message(self, message: UserMessage): await self.antispam.propagate(message) # noqa intents = Intents.all() # intents >>= 8 b = Bot(file["token"], intents=intents) b.antispam = AntiSpamHandler(b, library=Library.PINCER) b.run()
def create_handler(): """Create a simple handler for usage""" return AntiSpamHandler(MockedMember(mock_type="bot").to_mock())
import discord from discord.ext import commands from antispam.enums import Library from jsonLoader import read_json from antispam import AntiSpamHandler bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) file = read_json("token") bot.handler = AntiSpamHandler(bot, library=Library.YOUR_LIBRARY_HERE) @bot.event async def on_ready(): 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"])
def test_options_typing(self, create_bot): """Tests the handler raises on incorrect option types""" with pytest.raises(ValueError): AntiSpamHandler(create_bot, options=1)
import discord from discord.ext import commands from antispam.enums import Library from jsonLoader import read_json from antispam import AntiSpamHandler, Options from antispam.plugins import AntiSpamTracker bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) file = read_json("token") bot.handler = AntiSpamHandler( bot, library=Library.YOUR_LIBRARY_HERE, options=Options(no_punish=True, message_duplicate_count=3), ) bot.tracker = AntiSpamTracker(bot.handler, 5) bot.handler.register_plugin(bot.tracker) """ For every message after (and including your third duplicate message) it adds one to your tracked count When its hits 5 'spammed' messages, it triggers. Which is 7 messages overall. """ @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-----")