From 9efc42fe3e04f926a7693904d84bd45e88099745 Mon Sep 17 00:00:00 2001 From: Naman Date: Sat, 29 Jan 2022 10:45:08 +0530 Subject: [PATCH 1/2] added antispam and reformatted --- Pipfile | 3 +- bot/bot.py | 10 ++- bot/cogs/__init__.py | 2 +- bot/cogs/admin.py | 170 +++++++++++++++++++++++++----------- bot/cogs/antispamhandler.py | 14 +++ bot/cogs/docs.py | 41 +++++---- bot/cogs/extras.py | 27 ++++-- bot/constants.py | 2 +- bot/utils/db_parser.py | 34 ++++---- bot/utils/extensions.py | 4 +- 10 files changed, 208 insertions(+), 99 deletions(-) create mode 100644 bot/cogs/antispamhandler.py diff --git a/Pipfile b/Pipfile index 08f7735..302f04e 100644 --- a/Pipfile +++ b/Pipfile @@ -9,7 +9,8 @@ google-cloud-bigquery = "*" psycopg2-binary = "*" requests = "*" beautifulsoup4 = "*" - +Discord-Anti-Spam = "*" +fuzzywuzzy = "*" [dev-packages] python-dotenv = "*" pre-commit = "*" diff --git a/bot/bot.py b/bot/bot.py index ce3b8ed..34405d2 100644 --- a/bot/bot.py +++ b/bot/bot.py @@ -14,8 +14,11 @@ class Bot(commands.Bot): """ def __init__(self) -> None: - super().__init__(command_prefix=constants.Client.prefix, - description="Online", intents=discord.Intents.all()) + super().__init__( + command_prefix=constants.Client.prefix, + description="Online", + intents=discord.Intents.all(), + ) async def on_ready(self) -> None: """Using self.wait_until_ready() to wait for the Guild to be Available""" @@ -30,7 +33,8 @@ async def on_member_join(self, member: discord.Member) -> None: await self.get_channel(constants.Channels.welcome).send( f"Hello {member.mention}, thanks for joining the server\n" f"Be sure to follow the <#{constants.Channels.rules}> of this server\n" - f"Consider introducing yourself in <#{constants.Channels.announcements}>") + f"Consider introducing yourself in <#{constants.Channels.announcements}>" + ) def add_cog(self, cog: commands.Cog) -> None: """Adds a Cog""" diff --git a/bot/cogs/__init__.py b/bot/cogs/__init__.py index f0d558f..fd68103 100644 --- a/bot/cogs/__init__.py +++ b/bot/cogs/__init__.py @@ -1 +1 @@ -__all__ = ["admin", "docs", "extras"] +__all__ = ["admin", "docs", "extras", "antispamhandler"] diff --git a/bot/cogs/admin.py b/bot/cogs/admin.py index 70db412..3c0f262 100644 --- a/bot/cogs/admin.py +++ b/bot/cogs/admin.py @@ -69,17 +69,23 @@ def __init__(self, bot: commands.Bot) -> None: @commands.command(name="ban") @commands.has_any_role("Mod Level 2") - async def ban(self, ctx: commands.Context, member: discord.Member, *reason: str) -> None: + async def ban( + self, ctx: commands.Context, member: discord.Member, *reason: str + ) -> None: """ Permanently Ban a Member """ reason = [x for x in reason] - await member.ban(reason=' '.join(reason)) + await member.ban(reason=" ".join(reason)) await ctx.message.delete() - await ctx.send(embed=discord.Embed(title=f"Banned {member.display_name}", - description=f"Banned by {ctx.author} for {' '.join(reason)}", - colour=discord.Color.random())) + await ctx.send( + embed=discord.Embed( + title=f"Banned {member.display_name}", + description=f"Banned by {ctx.author} for {' '.join(reason)}", + colour=discord.Color.random(), + ) + ) @commands.command(name="unban") @commands.has_any_role("Mod Level 2") @@ -91,9 +97,13 @@ async def unban(self, ctx: commands.Context, id: int) -> None: user = await self.bot.fetch_user(id) await ctx.guild.unban(user) await ctx.message.delete() - await ctx.send(embed=discord.Embed(title=f"Unban {user.display_name}", - description=f"{ctx.author} has removed the Ban", - colour=discord.Color.random())) + await ctx.send( + embed=discord.Embed( + title=f"Unban {user.display_name}", + description=f"{ctx.author} has removed the Ban", + colour=discord.Color.random(), + ) + ) # TODO: Improve the Message Format @commands.command(name="listbans") @@ -108,24 +118,35 @@ async def list_bans(self, ctx: commands.Context) -> None: banned = [str(x) for x in bans] if banned: - await ctx.send(embed=discord.Embed(title="Banned Users", - description=" ".join(banned), - colour=discord.Color.random())) + await ctx.send( + embed=discord.Embed( + title="Banned Users", + description=" ".join(banned), + colour=discord.Color.random(), + ) + ) else: - await ctx.send(embed=discord.Embed(title="Banned Users", - description="No Banned Users", - colour=discord.Color.random())) + await ctx.send( + embed=discord.Embed( + title="Banned Users", + description="No Banned Users", + colour=discord.Color.random(), + ) + ) @commands.command(name="warn") @commands.has_any_role("Mod Level 1") - async def warn(self, ctx: commands.Context, member: discord.Member, *reason: str) -> None: + async def warn( + self, ctx: commands.Context, member: discord.Member, *reason: str + ) -> None: """ Warn a Member for Violation of Rules """ member_id = member.id num_of_warns = execute( - f"SELECT num_of_warnings FROM flagged_user WHERE user_id={member_id}") + f"SELECT num_of_warnings FROM flagged_user WHERE user_id={member_id}" + ) num_of_warns = 0 if not num_of_warns else num_of_warns[0][0] message = [x for x in reason] @@ -136,28 +157,42 @@ async def warn(self, ctx: commands.Context, member: discord.Member, *reason: str warn_message = f"Last warning for {member.display_name}" elif num_of_warns >= 3: - await member.ban(reason=' '.join(message)) - await ctx.send(embed=discord.Embed(title=f"{member.display_name} has been banned", - description=f"Warned multiple times by {ctx.author} for {' '.join(message) if message else 'unknown reason'}", - colour=discord.Color.random())) + await member.ban(reason=" ".join(message)) + await ctx.send( + embed=discord.Embed( + title=f"{member.display_name} has been banned", + description=f"Warned multiple times by {ctx.author} for {' '.join(message) if message else 'unknown reason'}", + colour=discord.Color.random(), + ) + ) execute(f"DELETE FROM flagged_user WHERE user_id={member_id}", "w") return if message: - await ctx.send(embed=discord.Embed(title=warn_message, - description=f"Warned by {ctx.author} for {' '.join(message)}", - colour=discord.Color.random())) + await ctx.send( + embed=discord.Embed( + title=warn_message, + description=f"Warned by {ctx.author} for {' '.join(message)}", + colour=discord.Color.random(), + ) + ) else: - await ctx.send(embed=discord.Embed(title=warn_message, - description=f"Warned by {ctx.author}", - colour=discord.Color.random())) + await ctx.send( + embed=discord.Embed( + title=warn_message, + description=f"Warned by {ctx.author}", + colour=discord.Color.random(), + ) + ) if num_of_warns == 0: if execute(f"INSERT INTO flagged_user VALUES ({member_id}, 1)", "w"): print("INSERTED") else: execute( - f"UPDATE flagged_user SET num_of_warnings={num_of_warns+1} WHERE user_id={member_id}", "w") + f"UPDATE flagged_user SET num_of_warnings={num_of_warns+1} WHERE user_id={member_id}", + "w", + ) @commands.command(name="clear") @commands.has_any_role("Mod Level 1") @@ -171,21 +206,31 @@ async def clear(self, ctx: commands.Context, amount: int = 2) -> None: @commands.command(name="kick") @commands.has_any_role("Mod Level 1") - async def kick(self, ctx: commands.Context, member: discord.Member, *reason: str) -> None: + async def kick( + self, ctx: commands.Context, member: discord.Member, *reason: str + ) -> None: """ Remove a Member """ await member.kick(reason=" ".join(reason)) - #await ctx.message.delete() + # await ctx.message.delete() reason = [x for x in reason] - await ctx.send(embed=discord.Embed(title=f"Kicked {member.display_name}", - description=f"Kicked by {ctx.author} for {' '.join(reason)}" if reason else f"Kicked by {ctx.author}", - colour=discord.Color.random())) + await ctx.send( + embed=discord.Embed( + title=f"Kicked {member.display_name}", + description=f"Kicked by {ctx.author} for {' '.join(reason)}" + if reason + else f"Kicked by {ctx.author}", + colour=discord.Color.random(), + ) + ) @commands.command(name="tempban") @commands.has_any_role("Mod Level 1") - async def tempban(self, ctx: commands.Context, member: discord.Member, *reason: str) -> None: + async def tempban( + self, ctx: commands.Context, member: discord.Member, *reason: str + ) -> None: """ Temporarily Ban a Member """ @@ -197,15 +242,23 @@ async def tempban(self, ctx: commands.Context, member: discord.Member, *reason: return reason = [x for x in reason] - await member.add_roles(discord.Object(constants.Roles.banned), reason=' '.join(reason)) - - await ctx.send(embed=discord.Embed(title="Temporary Ban", - description=f"{ctx.author} has applied Temporary Ban to {member.mention} for {' '.join(reason)}", - colour=discord.Color.random())) + await member.add_roles( + discord.Object(constants.Roles.banned), reason=" ".join(reason) + ) + + await ctx.send( + embed=discord.Embed( + title="Temporary Ban", + description=f"{ctx.author} has applied Temporary Ban to {member.mention} for {' '.join(reason)}", + colour=discord.Color.random(), + ) + ) @commands.command(name="removetempban") @commands.has_any_role("Mod Level 1") - async def remove_temp_ban(self, ctx: commands.Context, member: discord.Member) -> None: + async def remove_temp_ban( + self, ctx: commands.Context, member: discord.Member + ) -> None: """ Remove the Temporary Ban from a Member """ @@ -213,30 +266,39 @@ async def remove_temp_ban(self, ctx: commands.Context, member: discord.Member) - has_role = check_member_role(member, constants.Roles.banned) await ctx.message.delete() if has_role: - await member.remove_roles(discord.Object(constants.Roles.banned), reason="Temporary Ban Removed") - - await ctx.send(embed=discord.Embed(title="Temporary Ban Removed", - description=f"{ctx.author} has removed the Temporary Ban from {member.mention}!", - colour=discord.Color.random())) + await member.remove_roles( + discord.Object(constants.Roles.banned), reason="Temporary Ban Removed" + ) + + await ctx.send( + embed=discord.Embed( + title="Temporary Ban Removed", + description=f"{ctx.author} has removed the Temporary Ban from {member.mention}!", + colour=discord.Color.random(), + ) + ) return await ctx.send(f"{member.mention} is not under Temporary Ban!") @commands.command(name="stream") @commands.has_any_role("Mod Level 1") - async def stream(self, ctx: commands.Context, member: discord.Member, reason: str) -> None: + async def stream( + self, ctx: commands.Context, member: discord.Member, reason: str + ) -> None: """ Give Streaming Permission """ - has_role = check_member_role( - member=member, role_id=constants.Roles.video) + has_role = check_member_role(member=member, role_id=constants.Roles.video) if has_role: await ctx.send(f"{member.mention} already has Streaming Permission!") return await member.add_roles(discord.Object(constants.Roles.video), reason=reason) - await ctx.send(f"{ctx.author.mention} gave Streaming Permission to {member.mention}") + await ctx.send( + f"{ctx.author.mention} gave Streaming Permission to {member.mention}" + ) @commands.command(name="removestream") @commands.has_any_role("Mod Level 1") @@ -245,11 +307,15 @@ async def removestream(self, ctx: commands.Context, member: discord.Member) -> N Remove Streaming Permission """ - has_role = check_member_role( - member=member, role_id=constants.Roles.video) + has_role = check_member_role(member=member, role_id=constants.Roles.video) if has_role: - await member.remove_roles(discord.Object(constants.Roles.video), reason="Remove Streaming Permission") - await ctx.send(f"{ctx.author.mention} has removed Streaming Permission from {member.mention}") + await member.remove_roles( + discord.Object(constants.Roles.video), + reason="Remove Streaming Permission", + ) + await ctx.send( + f"{ctx.author.mention} has removed Streaming Permission from {member.mention}" + ) return await ctx.send(f"{member.mention} doesn't have Streaming Permission") diff --git a/bot/cogs/antispamhandler.py b/bot/cogs/antispamhandler.py new file mode 100644 index 0000000..a5d82ef --- /dev/null +++ b/bot/cogs/antispamhandler.py @@ -0,0 +1,14 @@ +from antispam import AntiSpamHandler +from discord.ext.commands import Cog + + +class AntiSpam(Cog): + def __init__(self, bot): + super().__init__() + self.bot = bot + + @Cog.listeners("on_message") + def spam_handler(self, message): + handler = AntiSpamHandler(self.bot) + await handler.propagate(message) + await self.bot.process_commands(message) diff --git a/bot/cogs/docs.py b/bot/cogs/docs.py index c862641..3cc530c 100644 --- a/bot/cogs/docs.py +++ b/bot/cogs/docs.py @@ -45,12 +45,9 @@ async def docs(self, ctx: commands.Context, *args: Optional[str]) -> None: topic, descp, argums, returs, link = data embed = discord.Embed(title=topic, color=discord.Color.random()) - embed.add_field(name="Description", - value=f"```\n{descp}```", inline=False) - embed.add_field(name="Arguments", - value=f"```python\n{argums}```", inline=False) - embed.add_field( - name="Returns", value=f"```python\n{returs}```", inline=False) + embed.add_field(name="Description", value=f"```\n{descp}```", inline=False) + embed.add_field(name="Arguments", value=f"```python\n{argums}```", inline=False) + embed.add_field(name="Returns", value=f"```python\n{returs}```", inline=False) embed.add_field(name="Link", value=link, inline=False) await ctx.send(ctx.author.mention, embed=embed) @@ -68,7 +65,8 @@ async def examples(self, ctx: commands.Context, *args: Optional[str]) -> None: embed = discord.Embed(title=data[0], color=discord.Color.random()) for info in data[1]: embed.add_field( - name=info[1], value=f"```python\n{info[0]}```", inline=False) + name=info[1], value=f"```python\n{info[0]}```", inline=False + ) await ctx.send(ctx.author.mention, embed=embed) @commands.command(name="exception") @@ -83,8 +81,7 @@ async def exception(self, ctx: commands.Context, *args: Optional[str]) -> None: return await ctx.send(f"{ctx.author.mention} No Results Found!") embed = discord.Embed(title=data[0], color=discord.Color.random()) - embed.add_field(name="Description", - value=f"`{data[1]}`", inline=False) + embed.add_field(name="Description", value=f"`{data[1]}`", inline=False) embed.add_field(name="Fix", value=f"`{data[2]}`", inline=False) await ctx.send(ctx.author.mention, embed=embed) @@ -96,21 +93,33 @@ async def list(self, ctx: commands.Context, topic: str) -> None: """ if "function" in topic.lower(): - functions = "\n".join(f":rocket: {i[0]}" for i in db_parser.execute( - "SELECT topic FROM command")) + functions = "\n".join( + f":rocket: {i[0]}" + for i in db_parser.execute("SELECT topic FROM command") + ) embed = discord.Embed( - title="Available searches", description=functions, color=discord.Color.random()) + title="Available searches", + description=functions, + color=discord.Color.random(), + ) await ctx.send(ctx.author.mention, embed=embed) elif "exception" in topic.lower(): - exceptions = "\n".join(f":rocket: {i[0]}" for i in db_parser.execute( - "SELECT topic FROM exception")) + exceptions = "\n".join( + f":rocket: {i[0]}" + for i in db_parser.execute("SELECT topic FROM exception") + ) embed = discord.Embed( - title="Available searches", description=exceptions, color=discord.Color.random()) + title="Available searches", + description=exceptions, + color=discord.Color.random(), + ) await ctx.send(ctx.author.mention, embed=embed) else: - return await ctx.send(f"{ctx.author.mention} Please enter a Valid Value (function, exception)!") + return await ctx.send( + f"{ctx.author.mention} Please enter a Valid Value (function, exception)!" + ) def setup(bot: commands.Bot) -> None: diff --git a/bot/cogs/extras.py b/bot/cogs/extras.py index dbb1a72..a6e04e2 100644 --- a/bot/cogs/extras.py +++ b/bot/cogs/extras.py @@ -36,9 +36,14 @@ async def subscribe(self, ctx: commands.Context) -> None: await ctx.send(f"{ctx.author.mention} You're already Subscribed!") return - await ctx.author.add_roles(discord.Object(constants.Roles.announcements), reason="Subscribed to announcements") + await ctx.author.add_roles( + discord.Object(constants.Roles.announcements), + reason="Subscribed to announcements", + ) - await ctx.send(f"{ctx.author.mention} Subscribed to <#{constants.Channels.announcements}>") + await ctx.send( + f"{ctx.author.mention} Subscribed to <#{constants.Channels.announcements}>" + ) @commands.command(name="unsubscribe") @commands.cooldown(1, 15, commands.BucketType.user) @@ -50,12 +55,18 @@ async def unsubscribe(self, ctx: commands.Context) -> None: has_role = check_self_role(ctx, constants.Roles.announcements) if has_role: - await ctx.author.remove_roles(discord.Object(constants.Roles.announcements), reason="Unsubscribe to " - "announcements") - await ctx.send(f"{ctx.author.mention} Unsubscribed to <#{constants.Channels.announcements}>") + await ctx.author.remove_roles( + discord.Object(constants.Roles.announcements), + reason="Unsubscribe to " "announcements", + ) + await ctx.send( + f"{ctx.author.mention} Unsubscribed to <#{constants.Channels.announcements}>" + ) return - await ctx.send(f"{ctx.author.mention} You're not Subscribed to <#{constants.Channels.announcements}>") + await ctx.send( + f"{ctx.author.mention} You're not Subscribed to <#{constants.Channels.announcements}>" + ) @commands.command(name="prefix") @commands.cooldown(1, 15, commands.BucketType.user) @@ -64,7 +75,9 @@ async def prefix(self, ctx: commands.Context) -> None: Get the Bot Prefix """ - await ctx.send(f"{ctx.author.mention} the Bot Prefix is {self.bot.command_prefix}") + await ctx.send( + f"{ctx.author.mention} the Bot Prefix is {self.bot.command_prefix}" + ) def setup(bot: commands.Bot) -> None: diff --git a/bot/constants.py b/bot/constants.py index 3c84e57..f4d0e9b 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -18,7 +18,7 @@ class Channels(NamedTuple): welcome = 830319475387531296 introduce = 830319507360186389 rules = 830332694231384074 - announcements = 830319507360186389#830340707951968267 + announcements = 830319507360186389 # 830340707951968267 class Client(NamedTuple): diff --git a/bot/utils/db_parser.py b/bot/utils/db_parser.py index 15bdcd4..e323c2b 100644 --- a/bot/utils/db_parser.py +++ b/bot/utils/db_parser.py @@ -8,23 +8,23 @@ CUR = CONN.cursor() MATCHING = { - "ASCII Art": ("ascii", "ascii art", "art"), - "Text to Handwriting": ("ascii", "ascii" "art", "art"), - "Shutdown": ("shutdown",), - "Cancel Shutdown": ("Cancel Shutdown",), - "Send Mail": ("mail", "send mail"), - "Send HTML Mail": ("send hmail", "html mail"), - "Info": ("info", "wikipedia"), - "Play on YT": ("playonyt", "youtube", "search on yt"), - "Search Google": ("google", "search"), - "Show History": ("history",), - "Take Screenshot": ("screenshot", "take screenshot"), - "Open Web": ("open web", "web"), - "Close Tab": ("close tab",), - "Send WhatsApp Message": ("sendwhatmsg", "send message"), - "Sending Message Instantly": ("sendwhatmsg_instantly", "send message instantly"), + "ASCII Art": ("ascii", "ascii art", "art"), + "Text to Handwriting": ("ascii", "ascii" "art", "art"), + "Shutdown": ("shutdown",), + "Cancel Shutdown": ("Cancel Shutdown",), + "Send Mail": ("mail", "send mail"), + "Send HTML Mail": ("send hmail", "html mail"), + "Info": ("info", "wikipedia"), + "Play on YT": ("playonyt", "youtube", "search on yt"), + "Search Google": ("google", "search"), + "Show History": ("history",), + "Take Screenshot": ("screenshot", "take screenshot"), + "Open Web": ("open web", "web"), + "Close Tab": ("close tab",), + "Send WhatsApp Message": ("sendwhatmsg", "send message"), + "Sending Message Instantly": ("sendwhatmsg_instantly", "send message instantly"), "Sending Message to a Group": ("sendwhatmsg_to_group", "group message"), - "Sending WhatsApp Media": ("sendwhats_image", "send image", "send media"), + "Sending WhatsApp Media": ("sendwhats_image", "send image", "send media"), } @@ -46,7 +46,7 @@ def execute(sql: str, mode: str = "r") -> Union[bool, list[tuple[Any, ...]], Non def match_string(string: str) -> Union[str, None]: - """Match the String with the Command """ + """Match the String with the Command""" for k, v in MATCHING.items(): if string.lower() in v: return k diff --git a/bot/utils/extensions.py b/bot/utils/extensions.py index 013540a..293f50d 100644 --- a/bot/utils/extensions.py +++ b/bot/utils/extensions.py @@ -17,7 +17,9 @@ def walk_extensions() -> Iterator[str]: def on_error(name: str) -> None: raise ImportError(name=name) - for module in pkgutil.walk_packages(cogs.__path__, f"{cogs.__name__}.", onerror=on_error): + for module in pkgutil.walk_packages( + cogs.__path__, f"{cogs.__name__}.", onerror=on_error + ): if unqualify(module.name).startswith("_"): continue From c56984e1fd4b09bde95dbfe7e06ddf88f689462e Mon Sep 17 00:00:00 2001 From: Naman Sharma Date: Sun, 30 Jan 2022 13:19:56 +0530 Subject: [PATCH 2/2] Update antispamhandler.py --- bot/cogs/antispamhandler.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/bot/cogs/antispamhandler.py b/bot/cogs/antispamhandler.py index a5d82ef..ab8233d 100644 --- a/bot/cogs/antispamhandler.py +++ b/bot/cogs/antispamhandler.py @@ -1,5 +1,5 @@ from antispam import AntiSpamHandler -from discord.ext.commands import Cog +from discord.ext.commands import Cog, Bot class AntiSpam(Cog): @@ -12,3 +12,7 @@ def spam_handler(self, message): handler = AntiSpamHandler(self.bot) await handler.propagate(message) await self.bot.process_commands(message) + +def setup(bot: Bot): + bot.add_cog(Antispam(bot)) +