From deea0e7c47060ba3d00dece08a32cbc19fb07c9f Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Thu, 27 Oct 2022 19:13:57 +0000 Subject: [PATCH 01/16] Restyled by autopep8 --- bot.py | 125 +++++++++++++++++++++++++++------------------------------ 1 file changed, 60 insertions(+), 65 deletions(-) diff --git a/bot.py b/bot.py index a696025..5172813 100644 --- a/bot.py +++ b/bot.py @@ -84,8 +84,7 @@ async def help(ctx): embed.add_field( name="AutoMod Services :robot:", - value= - f"Swear Word Detector and wuto warn.\n Using a +880 swear word database", + value=f"Swear Word Detector and wuto warn.\n Using a +880 swear word database", inline=True, ) @@ -111,8 +110,7 @@ async def help(ctx): embed.add_field( name="""Useful Links: :link:""", - value= - f"""[:classical_building: Hammer Bot Support](https://discord.gg/fMSyQA6) + value=f"""[:classical_building: Hammer Bot Support](https://discord.gg/fMSyQA6) [:link: Hammer Invite Link](https://discordapp.com/api/oauth2/authorize?client_id=591633652493058068&permissions=8&scope=bot) [:newspaper: Vote Hammer](https://top.gg/bot/591633652493058068) """, @@ -145,8 +143,8 @@ async def respondNotifOwner(text): await bot.get_channel(int(SECURITY_CHANNEL)).respond(text) -async def GetWarnings(userid: int, guildid:int, fullData: bool=False): - cur.execute("SELECT * FROM warns WHERE userid=? AND guildid=?", (userid,guildid,)) +async def GetWarnings(userid: int, guildid: int, fullData: bool = False): + cur.execute("SELECT * FROM warns WHERE userid=? AND guildid=?", (userid, guildid,)) rows = cur.fetchall() if not fullData: return len(rows) @@ -156,7 +154,7 @@ async def GetWarnings(userid: int, guildid:int, fullData: bool=False): # Function to add a warning and save it at the database async def AddWarning( - userid: int, guildid:int, reason + userid: int, guildid: int, reason ): warncount = await GetWarnings(userid, guildid) cur.execute( @@ -168,10 +166,11 @@ async def AddWarning( conn.commit() return warncount + 1 + async def Removewarn( - userid: int, guildId:int, relativeWarnId:int + userid: int, guildId: int, relativeWarnId: int ): - c=0 + c = 0 for warn in await GetWarnings(userid, guildId, fullData=True): warnRealId, _, _, SubReason, _ = warn if c == relativeWarnId: @@ -191,11 +190,13 @@ async def Clearwarns(userid: int, guildId: int): (userid, guildId)) conn.commit() return + + async def getAllWarns( - userid: int, guildid:int + userid: int, guildid: int ): allwarns = [] - c=0 + c = 0 for warn in await GetWarnings(userid, guildid, fullData=True): _, _, _, SubReason, timestamp = warn dt = timestamp @@ -204,10 +205,10 @@ async def getAllWarns( else: emojis = str(c) - ddt=int(str(dt)[:str(dt).find(".")]) + ddt = int(str(dt)[:str(dt).find(".")]) allwarns.append(f"- **ID: {emojis}** Reason: ``{SubReason}`` ") - - c=c+1 + + c = c + 1 return allwarns @@ -266,8 +267,7 @@ def ErrorEmbed(error): embed = Embed(title=f":no_entry_sign: Error!", description=error) embed.set_thumbnail( - url= - "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ficonsplace.com%2Fwp-content%2Fuploads%2F_icons%2Fff0000%2F256%2Fpng%2Ferror-icon-14-256.png&f=1&nofb=1" + url="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ficonsplace.com%2Fwp-content%2Fuploads%2F_icons%2Fff0000%2F256%2Fpng%2Ferror-icon-14-256.png&f=1&nofb=1" ) embed.set_footer( @@ -347,8 +347,7 @@ async def on_message(message): s = "s" if warn > 1 else "" embed.add_field( name="Warn count", - value= - f"The user {member} has {warn} warn{s}. Be careful. Run /seewarns @user to check its warnhistory", + value=f"The user {member} has {warn} warn{s}. Be careful. Run /seewarns @user to check its warnhistory", inline=True, ) bannedmessage = ( @@ -583,48 +582,50 @@ async def warn(ctx, member: discord.Member, reason=None): administrator=True, ) async def seewarns(ctx, member: discord.Member): allwarns = await getAllWarns(member.id, ctx.guild.id) - if(len(allwarns) == 0): allwarns = ['User had no warns at the moment'] + if (len(allwarns) == 0): + allwarns = ['User had no warns at the moment'] message = '\n'.join(allwarns) - - c=0 - data=[] + + c = 0 + data = [] for warn in await GetWarnings(member.id, ctx.guild.id, fullData=True): - _,_,_,_,timestamp =warn - c=c+1 - data.append({'t':str(datetime.datetime.fromtimestamp(int(str(timestamp)[:str(timestamp).find(".")]))),'y':c}) + _, _, _, _, timestamp = warn + c = c + 1 + data.append({'t': str(datetime.datetime.fromtimestamp( + int(str(timestamp)[:str(timestamp).find(".")]))), 'y': c}) qc = QuickChart() qc.width = 500 qc.height = 300 qc.device_pixel_ratio = 2.0 qc.config = { - "type": "line", - "data": { - "datasets": [ - { - "fill": False, - "label": [f"Warns of {member}"], - "lineTension": 0, - "backgroundColor": "#7289DA", - "borderColor": "#7289DA", - "data": data - } - ] - }, - "options": { - "scales": { - "xAxes": [{ - "type": "time", - "time": { - "parser": "YYYY-MM-DD HH:mm:ss", - "displayFormats": { - "day": "DD/MM/YYYY" - } + "type": "line", + "data": { + "datasets": [ + { + "fill": False, + "label": [f"Warns of {member}"], + "lineTension": 0, + "backgroundColor": "#7289DA", + "borderColor": "#7289DA", + "data": data + } + ] + }, + "options": { + "scales": { + "xAxes": [{ + "type": "time", + "time": { + "parser": "YYYY-MM-DD HH:mm:ss", + "displayFormats": { + "day": "DD/MM/YYYY" + } + } + }] + } } - }] } - } -} uurl = qc.get_url() @@ -643,12 +644,12 @@ async def seewarns(ctx, member: discord.Member): @discord.default_permissions( kick_members=True, ) -async def unwarn(ctx, member: discord.Member, id: int=None , *, reason=None): - if(await GetWarnings(member.id, ctx.guild.id) == 0): +async def unwarn(ctx, member: discord.Member, id: int = None, *, reason=None): + if (await GetWarnings(member.id, ctx.guild.id) == 0): return await ctx.respond("This user does not have any warn!") if id == None: message = f"""To select a warn to remove, use argument id and specify its value.""" - + embed = Embed(title=f"ERROR! Need to select a warn :hammer_pick:", description=message) allwarns = await getAllWarns(member.id, ctx.guild.id) embed.add_field( @@ -798,8 +799,7 @@ async def restart(ctx): @bot.slash_command( guild_only=True, name="setdelay", - description= - "Updates the message delay in a channel with a set of custom time interval", + description="Updates the message delay in a channel with a set of custom time interval", ) @discord.default_permissions( manage_messages=True, ) @@ -808,8 +808,7 @@ async def setdelay(ctx, seconds: float, reason: str = ""): m = "modified" if seconds > 0.0 else "removed" embed = Embed( title=f"Delay {m} on #{ctx.channel} :hammer_pick:", - description= - f"This channel now has a delay of **{seconds}** seconds for {reason}" + description=f"This channel now has a delay of **{seconds}** seconds for {reason}" if reason != None and reason != "" else f"This channel now has a delay of **{seconds}** seconds", ) @@ -869,8 +868,7 @@ async def mute(ctx, member: discord.Member, *, reason=None): @bot.slash_command( guild_only=True, name="unmute", - description= - "Restores the hability to talk or join voice channels to a user", + description="Restores the hability to talk or join voice channels to a user", ) @discord.default_permissions( manage_messages=True, ) @@ -921,8 +919,7 @@ async def lock(ctx, channel: discord.TextChannel = None, reason=None): @bot.slash_command( guild_only=True, name="unlock", - description= - "Removes the blocking in a channel from not being used as a chat.", + description="Removes the blocking in a channel from not being used as a chat.", ) async def unlock(ctx, channel: discord.TextChannel = None, reason=None): @@ -971,8 +968,7 @@ async def suggest(ctx, suggestion: str): async def invite(ctx): embed = Embed( title=f"Invite Hammer Bot to your server! :hammer_pick:", - description= - f"[**🔗 Hammer Invite Link**](https://discordapp.com/api/oauth2/authorize?client_id=591633652493058068&permissions=8&scope=bot)", + description=f"[**🔗 Hammer Invite Link**](https://discordapp.com/api/oauth2/authorize?client_id=591633652493058068&permissions=8&scope=bot)", ) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", @@ -1024,8 +1020,7 @@ async def settings(ctx, module: str = None, value: str = None): f"Enable it by doing ``{COMMAND_PREFIX}settings automod on``") embed.add_field( name="AutoMod Services :robot:", - value= - f"Actual status: {automodStatustr}\n {recommendedactivityAutomod}", + value=f"Actual status: {automodStatustr}\n {recommendedactivityAutomod}", inline=True, ) embed.set_footer( From 8230d7b473d386c3e3ffe89d8b0e5e56a2dfaa2d Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Thu, 27 Oct 2022 19:13:59 +0000 Subject: [PATCH 02/16] Restyled by black --- bot.py | 223 +++++++++++++++++++++++++++++++-------------------------- 1 file changed, 122 insertions(+), 101 deletions(-) diff --git a/bot.py b/bot.py index 5172813..cf7c63d 100644 --- a/bot.py +++ b/bot.py @@ -23,21 +23,26 @@ from get_enviroment import SECURITY_GUILD from get_enviroment import SWEAR_WORDS_LIST from get_enviroment import TOKEN + # database import & connection conn = sqlite3.connect("maindatabase1.db") cur = conn.cursor() -cur.execute("""CREATE TABLE IF NOT EXISTS `warns` ( +cur.execute( + """CREATE TABLE IF NOT EXISTS `warns` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `userid` INT(100), `guildid` INT, `reason` TEXT, `timestamp` INT); - """) -cur.execute("""CREATE TABLE IF NOT EXISTS `settings` ( + """ +) +cur.execute( + """CREATE TABLE IF NOT EXISTS `settings` ( `guildid` INT(100) UNIQUE, `automod` INT); - """) + """ +) hammericon = "https://images-ext-2.discordapp.net/external/OKc8xu6AILGNFY3nSTt7wGbg-Mi1iQZonoLTFg85o-E/%3Fsize%3D1024/https/cdn.discordapp.com/avatars/591633652493058068/e6011129c5169b29ed05a6dc873175cb.png?width=670&height=670" @@ -55,9 +60,9 @@ # -@bot.slash_command(name="help", - description="Displays all the available commands for Hammer" - ) +@bot.slash_command( + name="help", description="Displays all the available commands for Hammer" +) async def help(ctx): # Define each page @@ -66,9 +71,9 @@ async def help(ctx): **Hammer's commands:** """ - embed = Embed(title="Hammer Bot Help", - description=descr, - colour=discord.Colour.lighter_grey()) + embed = Embed( + title="Hammer Bot Help", description=descr, colour=discord.Colour.lighter_grey() + ) embed.add_field( name="Moderation Commands :tools:", @@ -127,8 +132,9 @@ async def help(ctx): inline=True, ) - embed.set_footer(text=f"Hammer | Command executed by {ctx.author}", - icon_url=hammericon) + embed.set_footer( + text=f"Hammer | Command executed by {ctx.author}", icon_url=hammericon + ) await ctx.respond(embed=embed) @@ -144,7 +150,13 @@ async def respondNotifOwner(text): async def GetWarnings(userid: int, guildid: int, fullData: bool = False): - cur.execute("SELECT * FROM warns WHERE userid=? AND guildid=?", (userid, guildid,)) + cur.execute( + "SELECT * FROM warns WHERE userid=? AND guildid=?", + ( + userid, + guildid, + ), + ) rows = cur.fetchall() if not fullData: return len(rows) @@ -153,9 +165,7 @@ async def GetWarnings(userid: int, guildid: int, fullData: bool = False): # Function to add a warning and save it at the database -async def AddWarning( - userid: int, guildid: int, reason -): +async def AddWarning(userid: int, guildid: int, reason): warncount = await GetWarnings(userid, guildid) cur.execute( """INSERT OR IGNORE INTO warns (userid, guildid, reason, timestamp) @@ -167,9 +177,7 @@ async def AddWarning( return warncount + 1 -async def Removewarn( - userid: int, guildId: int, relativeWarnId: int -): +async def Removewarn(userid: int, guildId: int, relativeWarnId: int): c = 0 for warn in await GetWarnings(userid, guildId, fullData=True): warnRealId, _, _, SubReason, _ = warn @@ -186,15 +194,12 @@ async def Removewarn( async def Clearwarns(userid: int, guildId: int): # delete all rows - cur.execute("DELETE FROM warns WHERE userid=? AND guildid=?", - (userid, guildId)) + cur.execute("DELETE FROM warns WHERE userid=? AND guildid=?", (userid, guildId)) conn.commit() return -async def getAllWarns( - userid: int, guildid: int -): +async def getAllWarns(userid: int, guildid: int): allwarns = [] c = 0 for warn in await GetWarnings(userid, guildid, fullData=True): @@ -205,7 +210,7 @@ async def getAllWarns( else: emojis = str(c) - ddt = int(str(dt)[:str(dt).find(".")]) + ddt = int(str(dt)[: str(dt).find(".")]) allwarns.append(f"- **ID: {emojis}** Reason: ``{SubReason}`` ") c = c + 1 @@ -213,8 +218,7 @@ async def getAllWarns( async def GetSettings(guildid: int): - cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", - (guildid, )) + cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", (guildid,)) rows = cur.fetchall() if len(rows) > 0: return rows[0][1] @@ -223,13 +227,10 @@ async def GetSettings(guildid: int): async def SaveSetting(guildid: int, module: str, value: int): - cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", - (guildid, )) + cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", (guildid,)) rows = cur.fetchall() # print(rows) - if len( - rows - ) > 0: # cur.execute('INSERT INTO foo (a,b) values (?,?)', (strA, strB)) + if len(rows) > 0: # cur.execute('INSERT INTO foo (a,b) values (?,?)', (strA, strB)) query = f"""UPDATE settings SET automod = {value} WHERE guildid={guildid} """ @@ -335,15 +336,17 @@ async def on_message(message): descr = ( f"The user {member} has been warned because said a banned swear word" ) - embed = Embed(title=f"{member} has been warned! :hammer_pick:", - description=descr) + embed = Embed( + title=f"{member} has been warned! :hammer_pick:", description=descr + ) embed.set_footer( text=f"Hammer | Automod service", icon_url=hammericon, ) embed.set_thumbnail(url=member.display_avatar) - warn = await AddWarning(member.id, message.guild.id, - "Said a banned swear word") + warn = await AddWarning( + member.id, message.guild.id, "Said a banned swear word" + ) s = "s" if warn > 1 else "" embed.add_field( name="Warn count", @@ -351,9 +354,12 @@ async def on_message(message): inline=True, ) bannedmessage = ( - message.content[:message.content.find(word)] + "~~" + word + - "~~" + - message.content[message.content.find(word) + len(word):]) + message.content[: message.content.find(word)] + + "~~" + + word + + "~~" + + message.content[message.content.find(word) + len(word) :] + ) embed.add_field( name="Message Removed:", value=f"The removed message was \n||{bannedmessage}||", @@ -369,15 +375,17 @@ async def on_message(message): embed = ErrorEmbed( await message.channel.send( f"Could not deliver the message to the user {member}\n This may be caused because the user is a bot, has blocked me or has the DMs turned off. \n\n**But the user is warned** and I have saved it into my beautiful unforgettable database" - ), ) + ), + ) # if(str(message.content).startswith(COMMAND_PREFIX)): # print("command executed", message.content) @bot.event async def on_ready(): - await bot.change_presence(activity=discord.Activity( - type=discord.ActivityType.watching, name="you")) + await bot.change_presence( + activity=discord.Activity(type=discord.ActivityType.watching, name="you") + ) print("HAMMER BOT Ready!", datetime.datetime.now()) botname = await bot.application_info() print("logged in as:", botname.name) @@ -394,9 +402,7 @@ async def on_ready(): debug = False -@bot.slash_command(guild_only=True, - name="hello", - guild_ids=[int(SECURITY_GUILD)]) +@bot.slash_command(guild_only=True, name="hello", guild_ids=[int(SECURITY_GUILD)]) async def hello(ctx): await ctx.respond("Hammer is back!") @@ -465,7 +471,8 @@ async def whois(ctx, member: discord.Member): description="Keeps out a user permanently, forbidding its entry", ) @discord.default_permissions( - ban_members=True, ) + ban_members=True, +) async def ban(ctx, member: discord.Member, *, reason=None): if member == ctx.author: @@ -476,8 +483,7 @@ async def ban(ctx, member: discord.Member, *, reason=None): message = f"You have been banned from {ctx.guild.name} for {reason}" descr = f"The user {member} has been banned for {reason}" - embed = Embed(title=f"{member} has been banned! :hammer_pick:", - description=descr) + embed = Embed(title=f"{member} has been banned! :hammer_pick:", description=descr) embed.set_image(url="https://i.imgflip.com/19zat3.jpg") embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", @@ -500,11 +506,12 @@ async def ban(ctx, member: discord.Member, *, reason=None): await SendMessageTo(ctx, member, message) -@bot.slash_command(guild_only=True, - name="kick", - description="Kicks out a member from the server") +@bot.slash_command( + guild_only=True, name="kick", description="Kicks out a member from the server" +) @discord.default_permissions( - kick_members=True, ) + kick_members=True, +) async def kick(ctx, member: discord.Member, *, reason=None): if member == ctx.author: @@ -525,8 +532,7 @@ async def kick(ctx, member: discord.Member, *, reason=None): ) return descr = f"The user {member} has been kicked for {reason}" - embed = Embed(title=f"{member} has been kicked! :hammer_pick:", - description=descr) + embed = Embed(title=f"{member} has been kicked! :hammer_pick:", description=descr) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", icon_url=hammericon, @@ -543,7 +549,8 @@ async def kick(ctx, member: discord.Member, *, reason=None): description="Sets a warning for a user, at 3 warns/strikes they get kicked", ) @discord.default_permissions( - administrator=True, ) + administrator=True, +) async def warn(ctx, member: discord.Member, reason=None): if member == ctx.author: @@ -554,8 +561,7 @@ async def warn(ctx, member: discord.Member, reason=None): message = f"You have been warned for {reason}" descr = f"The user {member} has been warned for {reason}" - embed = Embed(title=f"{member} has been warned! :hammer_pick:", - description=descr) + embed = Embed(title=f"{member} has been warned! :hammer_pick:", description=descr) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", icon_url=hammericon, @@ -579,20 +585,29 @@ async def warn(ctx, member: discord.Member, reason=None): description="Displays the warn history of a user in the guild", ) @discord.default_permissions( - administrator=True, ) + administrator=True, +) async def seewarns(ctx, member: discord.Member): allwarns = await getAllWarns(member.id, ctx.guild.id) - if (len(allwarns) == 0): - allwarns = ['User had no warns at the moment'] - message = '\n'.join(allwarns) + if len(allwarns) == 0: + allwarns = ["User had no warns at the moment"] + message = "\n".join(allwarns) c = 0 data = [] for warn in await GetWarnings(member.id, ctx.guild.id, fullData=True): _, _, _, _, timestamp = warn c = c + 1 - data.append({'t': str(datetime.datetime.fromtimestamp( - int(str(timestamp)[:str(timestamp).find(".")]))), 'y': c}) + data.append( + { + "t": str( + datetime.datetime.fromtimestamp( + int(str(timestamp)[: str(timestamp).find(".")]) + ) + ), + "y": c, + } + ) qc = QuickChart() qc.width = 500 @@ -608,23 +623,23 @@ async def seewarns(ctx, member: discord.Member): "lineTension": 0, "backgroundColor": "#7289DA", "borderColor": "#7289DA", - "data": data + "data": data, } ] }, "options": { "scales": { - "xAxes": [{ - "type": "time", - "time": { - "parser": "YYYY-MM-DD HH:mm:ss", - "displayFormats": { - "day": "DD/MM/YYYY" - } + "xAxes": [ + { + "type": "time", + "time": { + "parser": "YYYY-MM-DD HH:mm:ss", + "displayFormats": {"day": "DD/MM/YYYY"}, + }, } - }] + ] } - } + }, } uurl = qc.get_url() @@ -638,19 +653,23 @@ async def seewarns(ctx, member: discord.Member): return await ctx.respond(embed=embed) -@bot.slash_command(guild_only=True, - name="unwarn", - description="Removes a strike from a user") +@bot.slash_command( + guild_only=True, name="unwarn", description="Removes a strike from a user" +) @discord.default_permissions( kick_members=True, ) async def unwarn(ctx, member: discord.Member, id: int = None, *, reason=None): - if (await GetWarnings(member.id, ctx.guild.id) == 0): + if await GetWarnings(member.id, ctx.guild.id) == 0: return await ctx.respond("This user does not have any warn!") if id == None: - message = f"""To select a warn to remove, use argument id and specify its value.""" + message = ( + f"""To select a warn to remove, use argument id and specify its value.""" + ) - embed = Embed(title=f"ERROR! Need to select a warn :hammer_pick:", description=message) + embed = Embed( + title=f"ERROR! Need to select a warn :hammer_pick:", description=message + ) allwarns = await getAllWarns(member.id, ctx.guild.id) embed.add_field( name=f"**Historic of {member.name}**:", @@ -662,8 +681,7 @@ async def unwarn(ctx, member: discord.Member, id: int = None, *, reason=None): message = f"You have been unwarned for {reason}" descr = f"The user {member} has been unwarned for {reason}" - embed = Embed(title=f"{member} has been unwarned! :hammer_pick:", - description=descr) + embed = Embed(title=f"{member} has been unwarned! :hammer_pick:", description=descr) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", icon_url=hammericon, @@ -681,11 +699,12 @@ async def unwarn(ctx, member: discord.Member, id: int = None, *, reason=None): await SendMessageTo(ctx, member, message) -@bot.slash_command(guild_only=True, - name="clearwarns", - description="Removes all strikes from a user") +@bot.slash_command( + guild_only=True, name="clearwarns", description="Removes all strikes from a user" +) @discord.default_permissions( - kick_members=True, ) + kick_members=True, +) async def clearwarns(ctx, member: discord.Member, *, reason=None): if reason == None: @@ -802,15 +821,16 @@ async def restart(ctx): description="Updates the message delay in a channel with a set of custom time interval", ) @discord.default_permissions( - manage_messages=True, ) + manage_messages=True, +) async def setdelay(ctx, seconds: float, reason: str = ""): m = "modified" if seconds > 0.0 else "removed" embed = Embed( title=f"Delay {m} on #{ctx.channel} :hammer_pick:", description=f"This channel now has a delay of **{seconds}** seconds for {reason}" - if reason != None and reason != "" else - f"This channel now has a delay of **{seconds}** seconds", + if reason != None and reason != "" + else f"This channel now has a delay of **{seconds}** seconds", ) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", @@ -828,7 +848,8 @@ async def setdelay(ctx, seconds: float, reason: str = ""): description="Removes the hability to talk or join voice channels to a user", ) @discord.default_permissions( - manage_messages=True, ) + manage_messages=True, +) async def mute(ctx, member: discord.Member, *, reason=None): guild = ctx.guild @@ -871,7 +892,8 @@ async def mute(ctx, member: discord.Member, *, reason=None): description="Restores the hability to talk or join voice channels to a user", ) @discord.default_permissions( - manage_messages=True, ) + manage_messages=True, +) async def unmute(ctx, member: discord.Member, *, reason=None): mutedRole = discord.utils.get(ctx.guild.roles, name="Muted") @@ -881,8 +903,8 @@ async def unmute(ctx, member: discord.Member, *, reason=None): reason = "for " + reason await member.remove_roles(mutedRole) SendMessageTo( - ctx, member, - f":tada: You have been unmuted from: {ctx.guild.name} {reason}") + ctx, member, f":tada: You have been unmuted from: {ctx.guild.name} {reason}" + ) embed = discord.Embed( title=f"User Unmuted: {member}", description=f"User {member.mention} has been unmuted {reason}", @@ -981,9 +1003,9 @@ async def invite(ctx): @discord.default_permissions(administrator=True) -@bot.slash_command(name="settings", - description="Modifies some Hammer config values", - guild_only=True) +@bot.slash_command( + name="settings", description="Modifies some Hammer config values", guild_only=True +) @option( "module", description="Pick a module to switch!", @@ -1000,12 +1022,10 @@ async def settings(ctx, module: str = None, value: str = None): value = 1 if value == "on" else 0 await SaveSetting(ctx.guild.id, module, value) action = "enabled" if value else "disabled" - await ctx.respond(f"Module {module} {action} successfully!", - ephemeral=True) + await ctx.respond(f"Module {module} {action} successfully!", ephemeral=True) return else: - await ctx.respond("Use: ``/settings module on/off``", - ephemeral=True) + await ctx.respond("Use: ``/settings module on/off``", ephemeral=True) return embed = Embed( title=f"Hammer Bot Settings :hammer_pick:", @@ -1016,8 +1036,9 @@ async def settings(ctx, module: str = None, value: str = None): automodStatustr = "**✅ ON**" if automodStatus else "**❌ OFF**" recommendedactivityAutomod = ( f"Disable it by doing: ``{COMMAND_PREFIX}settings automod off``" - if automodStatus else - f"Enable it by doing ``{COMMAND_PREFIX}settings automod on``") + if automodStatus + else f"Enable it by doing ``{COMMAND_PREFIX}settings automod on``" + ) embed.add_field( name="AutoMod Services :robot:", value=f"Actual status: {automodStatustr}\n {recommendedactivityAutomod}", From b43a3955121bb2459c7408f02e479c4b1978580b Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Thu, 27 Oct 2022 19:14:01 +0000 Subject: [PATCH 03/16] Restyled by isort --- bot.py | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/bot.py b/bot.py index cf7c63d..4278dc4 100644 --- a/bot.py +++ b/bot.py @@ -2,27 +2,21 @@ import os import sqlite3 import sys +import urllib from email import message from pydoc import describe from time import time -from quickchart import QuickChart -import urllib import discord -from discord import Embed -from discord import guild_only +from discord import Embed, guild_only from discord.commands import option from discord.ext import commands from discord.ext.commands.core import command +from quickchart import QuickChart -from get_enviroment import ANNOUNCEMENTS_CHANNEL -from get_enviroment import COMMAND_PREFIX -from get_enviroment import DEV_SUGGESTIONS_CHANNEL -from get_enviroment import OWNER -from get_enviroment import SECURITY_CHANNEL -from get_enviroment import SECURITY_GUILD -from get_enviroment import SWEAR_WORDS_LIST -from get_enviroment import TOKEN +from get_enviroment import (ANNOUNCEMENTS_CHANNEL, COMMAND_PREFIX, + DEV_SUGGESTIONS_CHANNEL, OWNER, SECURITY_CHANNEL, + SECURITY_GUILD, SWEAR_WORDS_LIST, TOKEN) # database import & connection From 557a368d228af0747b354609169a15b8310b82b7 Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Thu, 27 Oct 2022 19:14:02 +0000 Subject: [PATCH 04/16] Restyled by reorder-python-imports --- bot.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/bot.py b/bot.py index 4278dc4..e2bf7cf 100644 --- a/bot.py +++ b/bot.py @@ -8,15 +8,21 @@ from time import time import discord -from discord import Embed, guild_only +from discord import Embed +from discord import guild_only from discord.commands import option from discord.ext import commands from discord.ext.commands.core import command from quickchart import QuickChart -from get_enviroment import (ANNOUNCEMENTS_CHANNEL, COMMAND_PREFIX, - DEV_SUGGESTIONS_CHANNEL, OWNER, SECURITY_CHANNEL, - SECURITY_GUILD, SWEAR_WORDS_LIST, TOKEN) +from get_enviroment import ANNOUNCEMENTS_CHANNEL +from get_enviroment import COMMAND_PREFIX +from get_enviroment import DEV_SUGGESTIONS_CHANNEL +from get_enviroment import OWNER +from get_enviroment import SECURITY_CHANNEL +from get_enviroment import SECURITY_GUILD +from get_enviroment import SWEAR_WORDS_LIST +from get_enviroment import TOKEN # database import & connection From 64984e3d7d4754ce8037ed54943db2d098566d73 Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Thu, 27 Oct 2022 19:14:06 +0000 Subject: [PATCH 05/16] Restyled by yapf --- bot.py | 247 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 122 insertions(+), 125 deletions(-) diff --git a/bot.py b/bot.py index e2bf7cf..d971be2 100644 --- a/bot.py +++ b/bot.py @@ -28,21 +28,17 @@ conn = sqlite3.connect("maindatabase1.db") cur = conn.cursor() -cur.execute( - """CREATE TABLE IF NOT EXISTS `warns` ( +cur.execute("""CREATE TABLE IF NOT EXISTS `warns` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `userid` INT(100), `guildid` INT, `reason` TEXT, `timestamp` INT); - """ -) -cur.execute( - """CREATE TABLE IF NOT EXISTS `settings` ( + """) +cur.execute("""CREATE TABLE IF NOT EXISTS `settings` ( `guildid` INT(100) UNIQUE, `automod` INT); - """ -) + """) hammericon = "https://images-ext-2.discordapp.net/external/OKc8xu6AILGNFY3nSTt7wGbg-Mi1iQZonoLTFg85o-E/%3Fsize%3D1024/https/cdn.discordapp.com/avatars/591633652493058068/e6011129c5169b29ed05a6dc873175cb.png?width=670&height=670" @@ -60,9 +56,9 @@ # -@bot.slash_command( - name="help", description="Displays all the available commands for Hammer" -) +@bot.slash_command(name="help", + description="Displays all the available commands for Hammer" + ) async def help(ctx): # Define each page @@ -71,9 +67,9 @@ async def help(ctx): **Hammer's commands:** """ - embed = Embed( - title="Hammer Bot Help", description=descr, colour=discord.Colour.lighter_grey() - ) + embed = Embed(title="Hammer Bot Help", + description=descr, + colour=discord.Colour.lighter_grey()) embed.add_field( name="Moderation Commands :tools:", @@ -89,7 +85,8 @@ async def help(ctx): embed.add_field( name="AutoMod Services :robot:", - value=f"Swear Word Detector and wuto warn.\n Using a +880 swear word database", + value= + f"Swear Word Detector and wuto warn.\n Using a +880 swear word database", inline=True, ) @@ -115,7 +112,8 @@ async def help(ctx): embed.add_field( name="""Useful Links: :link:""", - value=f"""[:classical_building: Hammer Bot Support](https://discord.gg/fMSyQA6) + value= + f"""[:classical_building: Hammer Bot Support](https://discord.gg/fMSyQA6) [:link: Hammer Invite Link](https://discordapp.com/api/oauth2/authorize?client_id=591633652493058068&permissions=8&scope=bot) [:newspaper: Vote Hammer](https://top.gg/bot/591633652493058068) """, @@ -132,9 +130,8 @@ async def help(ctx): inline=True, ) - embed.set_footer( - text=f"Hammer | Command executed by {ctx.author}", icon_url=hammericon - ) + embed.set_footer(text=f"Hammer | Command executed by {ctx.author}", + icon_url=hammericon) await ctx.respond(embed=embed) @@ -194,7 +191,8 @@ async def Removewarn(userid: int, guildId: int, relativeWarnId: int): async def Clearwarns(userid: int, guildId: int): # delete all rows - cur.execute("DELETE FROM warns WHERE userid=? AND guildid=?", (userid, guildId)) + cur.execute("DELETE FROM warns WHERE userid=? AND guildid=?", + (userid, guildId)) conn.commit() return @@ -210,15 +208,17 @@ async def getAllWarns(userid: int, guildid: int): else: emojis = str(c) - ddt = int(str(dt)[: str(dt).find(".")]) - allwarns.append(f"- **ID: {emojis}** Reason: ``{SubReason}`` ") + ddt = int(str(dt)[:str(dt).find(".")]) + allwarns.append( + f"- **ID: {emojis}** Reason: ``{SubReason}`` ") c = c + 1 return allwarns async def GetSettings(guildid: int): - cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", (guildid,)) + cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", + (guildid, )) rows = cur.fetchall() if len(rows) > 0: return rows[0][1] @@ -227,10 +227,13 @@ async def GetSettings(guildid: int): async def SaveSetting(guildid: int, module: str, value: int): - cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", (guildid,)) + cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", + (guildid, )) rows = cur.fetchall() # print(rows) - if len(rows) > 0: # cur.execute('INSERT INTO foo (a,b) values (?,?)', (strA, strB)) + if len( + rows + ) > 0: # cur.execute('INSERT INTO foo (a,b) values (?,?)', (strA, strB)) query = f"""UPDATE settings SET automod = {value} WHERE guildid={guildid} """ @@ -268,7 +271,8 @@ def ErrorEmbed(error): embed = Embed(title=f":no_entry_sign: Error!", description=error) embed.set_thumbnail( - url="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ficonsplace.com%2Fwp-content%2Fuploads%2F_icons%2Fff0000%2F256%2Fpng%2Ferror-icon-14-256.png&f=1&nofb=1" + url= + "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ficonsplace.com%2Fwp-content%2Fuploads%2F_icons%2Fff0000%2F256%2Fpng%2Ferror-icon-14-256.png&f=1&nofb=1" ) embed.set_footer( @@ -336,30 +340,26 @@ async def on_message(message): descr = ( f"The user {member} has been warned because said a banned swear word" ) - embed = Embed( - title=f"{member} has been warned! :hammer_pick:", description=descr - ) + embed = Embed(title=f"{member} has been warned! :hammer_pick:", + description=descr) embed.set_footer( text=f"Hammer | Automod service", icon_url=hammericon, ) embed.set_thumbnail(url=member.display_avatar) - warn = await AddWarning( - member.id, message.guild.id, "Said a banned swear word" - ) + warn = await AddWarning(member.id, message.guild.id, + "Said a banned swear word") s = "s" if warn > 1 else "" embed.add_field( name="Warn count", - value=f"The user {member} has {warn} warn{s}. Be careful. Run /seewarns @user to check its warnhistory", + value= + f"The user {member} has {warn} warn{s}. Be careful. Run /seewarns @user to check its warnhistory", inline=True, ) bannedmessage = ( - message.content[: message.content.find(word)] - + "~~" - + word - + "~~" - + message.content[message.content.find(word) + len(word) :] - ) + message.content[:message.content.find(word)] + "~~" + word + + "~~" + + message.content[message.content.find(word) + len(word):]) embed.add_field( name="Message Removed:", value=f"The removed message was \n||{bannedmessage}||", @@ -375,17 +375,15 @@ async def on_message(message): embed = ErrorEmbed( await message.channel.send( f"Could not deliver the message to the user {member}\n This may be caused because the user is a bot, has blocked me or has the DMs turned off. \n\n**But the user is warned** and I have saved it into my beautiful unforgettable database" - ), - ) + ), ) # if(str(message.content).startswith(COMMAND_PREFIX)): # print("command executed", message.content) @bot.event async def on_ready(): - await bot.change_presence( - activity=discord.Activity(type=discord.ActivityType.watching, name="you") - ) + await bot.change_presence(activity=discord.Activity( + type=discord.ActivityType.watching, name="you")) print("HAMMER BOT Ready!", datetime.datetime.now()) botname = await bot.application_info() print("logged in as:", botname.name) @@ -402,7 +400,9 @@ async def on_ready(): debug = False -@bot.slash_command(guild_only=True, name="hello", guild_ids=[int(SECURITY_GUILD)]) +@bot.slash_command(guild_only=True, + name="hello", + guild_ids=[int(SECURITY_GUILD)]) async def hello(ctx): await ctx.respond("Hammer is back!") @@ -471,8 +471,7 @@ async def whois(ctx, member: discord.Member): description="Keeps out a user permanently, forbidding its entry", ) @discord.default_permissions( - ban_members=True, -) + ban_members=True, ) async def ban(ctx, member: discord.Member, *, reason=None): if member == ctx.author: @@ -483,7 +482,8 @@ async def ban(ctx, member: discord.Member, *, reason=None): message = f"You have been banned from {ctx.guild.name} for {reason}" descr = f"The user {member} has been banned for {reason}" - embed = Embed(title=f"{member} has been banned! :hammer_pick:", description=descr) + embed = Embed(title=f"{member} has been banned! :hammer_pick:", + description=descr) embed.set_image(url="https://i.imgflip.com/19zat3.jpg") embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", @@ -506,12 +506,11 @@ async def ban(ctx, member: discord.Member, *, reason=None): await SendMessageTo(ctx, member, message) -@bot.slash_command( - guild_only=True, name="kick", description="Kicks out a member from the server" -) +@bot.slash_command(guild_only=True, + name="kick", + description="Kicks out a member from the server") @discord.default_permissions( - kick_members=True, -) + kick_members=True, ) async def kick(ctx, member: discord.Member, *, reason=None): if member == ctx.author: @@ -532,7 +531,8 @@ async def kick(ctx, member: discord.Member, *, reason=None): ) return descr = f"The user {member} has been kicked for {reason}" - embed = Embed(title=f"{member} has been kicked! :hammer_pick:", description=descr) + embed = Embed(title=f"{member} has been kicked! :hammer_pick:", + description=descr) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", icon_url=hammericon, @@ -549,8 +549,7 @@ async def kick(ctx, member: discord.Member, *, reason=None): description="Sets a warning for a user, at 3 warns/strikes they get kicked", ) @discord.default_permissions( - administrator=True, -) + administrator=True, ) async def warn(ctx, member: discord.Member, reason=None): if member == ctx.author: @@ -561,7 +560,8 @@ async def warn(ctx, member: discord.Member, reason=None): message = f"You have been warned for {reason}" descr = f"The user {member} has been warned for {reason}" - embed = Embed(title=f"{member} has been warned! :hammer_pick:", description=descr) + embed = Embed(title=f"{member} has been warned! :hammer_pick:", + description=descr) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", icon_url=hammericon, @@ -585,8 +585,7 @@ async def warn(ctx, member: discord.Member, reason=None): description="Displays the warn history of a user in the guild", ) @discord.default_permissions( - administrator=True, -) + administrator=True, ) async def seewarns(ctx, member: discord.Member): allwarns = await getAllWarns(member.id, ctx.guild.id) if len(allwarns) == 0: @@ -598,16 +597,14 @@ async def seewarns(ctx, member: discord.Member): for warn in await GetWarnings(member.id, ctx.guild.id, fullData=True): _, _, _, _, timestamp = warn c = c + 1 - data.append( - { - "t": str( - datetime.datetime.fromtimestamp( - int(str(timestamp)[: str(timestamp).find(".")]) - ) - ), - "y": c, - } - ) + data.append({ + "t": + str( + datetime.datetime.fromtimestamp( + int(str(timestamp)[:str(timestamp).find(".")]))), + "y": + c, + }) qc = QuickChart() qc.width = 500 @@ -616,28 +613,26 @@ async def seewarns(ctx, member: discord.Member): qc.config = { "type": "line", "data": { - "datasets": [ - { - "fill": False, - "label": [f"Warns of {member}"], - "lineTension": 0, - "backgroundColor": "#7289DA", - "borderColor": "#7289DA", - "data": data, - } - ] + "datasets": [{ + "fill": False, + "label": [f"Warns of {member}"], + "lineTension": 0, + "backgroundColor": "#7289DA", + "borderColor": "#7289DA", + "data": data, + }] }, "options": { "scales": { - "xAxes": [ - { - "type": "time", - "time": { - "parser": "YYYY-MM-DD HH:mm:ss", - "displayFormats": {"day": "DD/MM/YYYY"}, + "xAxes": [{ + "type": "time", + "time": { + "parser": "YYYY-MM-DD HH:mm:ss", + "displayFormats": { + "day": "DD/MM/YYYY" }, - } - ] + }, + }] } }, } @@ -653,12 +648,11 @@ async def seewarns(ctx, member: discord.Member): return await ctx.respond(embed=embed) -@bot.slash_command( - guild_only=True, name="unwarn", description="Removes a strike from a user" -) +@bot.slash_command(guild_only=True, + name="unwarn", + description="Removes a strike from a user") @discord.default_permissions( - kick_members=True, -) + kick_members=True, ) async def unwarn(ctx, member: discord.Member, id: int = None, *, reason=None): if await GetWarnings(member.id, ctx.guild.id) == 0: return await ctx.respond("This user does not have any warn!") @@ -667,9 +661,8 @@ async def unwarn(ctx, member: discord.Member, id: int = None, *, reason=None): f"""To select a warn to remove, use argument id and specify its value.""" ) - embed = Embed( - title=f"ERROR! Need to select a warn :hammer_pick:", description=message - ) + embed = Embed(title=f"ERROR! Need to select a warn :hammer_pick:", + description=message) allwarns = await getAllWarns(member.id, ctx.guild.id) embed.add_field( name=f"**Historic of {member.name}**:", @@ -681,7 +674,8 @@ async def unwarn(ctx, member: discord.Member, id: int = None, *, reason=None): message = f"You have been unwarned for {reason}" descr = f"The user {member} has been unwarned for {reason}" - embed = Embed(title=f"{member} has been unwarned! :hammer_pick:", description=descr) + embed = Embed(title=f"{member} has been unwarned! :hammer_pick:", + description=descr) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", icon_url=hammericon, @@ -699,12 +693,11 @@ async def unwarn(ctx, member: discord.Member, id: int = None, *, reason=None): await SendMessageTo(ctx, member, message) -@bot.slash_command( - guild_only=True, name="clearwarns", description="Removes all strikes from a user" -) +@bot.slash_command(guild_only=True, + name="clearwarns", + description="Removes all strikes from a user") @discord.default_permissions( - kick_members=True, -) + kick_members=True, ) async def clearwarns(ctx, member: discord.Member, *, reason=None): if reason == None: @@ -818,19 +811,20 @@ async def restart(ctx): @bot.slash_command( guild_only=True, name="setdelay", - description="Updates the message delay in a channel with a set of custom time interval", + description= + "Updates the message delay in a channel with a set of custom time interval", ) @discord.default_permissions( - manage_messages=True, -) + manage_messages=True, ) async def setdelay(ctx, seconds: float, reason: str = ""): m = "modified" if seconds > 0.0 else "removed" embed = Embed( title=f"Delay {m} on #{ctx.channel} :hammer_pick:", - description=f"This channel now has a delay of **{seconds}** seconds for {reason}" - if reason != None and reason != "" - else f"This channel now has a delay of **{seconds}** seconds", + description= + f"This channel now has a delay of **{seconds}** seconds for {reason}" + if reason != None and reason != "" else + f"This channel now has a delay of **{seconds}** seconds", ) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", @@ -848,8 +842,7 @@ async def setdelay(ctx, seconds: float, reason: str = ""): description="Removes the hability to talk or join voice channels to a user", ) @discord.default_permissions( - manage_messages=True, -) + manage_messages=True, ) async def mute(ctx, member: discord.Member, *, reason=None): guild = ctx.guild @@ -889,11 +882,11 @@ async def mute(ctx, member: discord.Member, *, reason=None): @bot.slash_command( guild_only=True, name="unmute", - description="Restores the hability to talk or join voice channels to a user", + description= + "Restores the hability to talk or join voice channels to a user", ) @discord.default_permissions( - manage_messages=True, -) + manage_messages=True, ) async def unmute(ctx, member: discord.Member, *, reason=None): mutedRole = discord.utils.get(ctx.guild.roles, name="Muted") @@ -903,8 +896,8 @@ async def unmute(ctx, member: discord.Member, *, reason=None): reason = "for " + reason await member.remove_roles(mutedRole) SendMessageTo( - ctx, member, f":tada: You have been unmuted from: {ctx.guild.name} {reason}" - ) + ctx, member, + f":tada: You have been unmuted from: {ctx.guild.name} {reason}") embed = discord.Embed( title=f"User Unmuted: {member}", description=f"User {member.mention} has been unmuted {reason}", @@ -941,7 +934,8 @@ async def lock(ctx, channel: discord.TextChannel = None, reason=None): @bot.slash_command( guild_only=True, name="unlock", - description="Removes the blocking in a channel from not being used as a chat.", + description= + "Removes the blocking in a channel from not being used as a chat.", ) async def unlock(ctx, channel: discord.TextChannel = None, reason=None): @@ -990,7 +984,8 @@ async def suggest(ctx, suggestion: str): async def invite(ctx): embed = Embed( title=f"Invite Hammer Bot to your server! :hammer_pick:", - description=f"[**🔗 Hammer Invite Link**](https://discordapp.com/api/oauth2/authorize?client_id=591633652493058068&permissions=8&scope=bot)", + description= + f"[**🔗 Hammer Invite Link**](https://discordapp.com/api/oauth2/authorize?client_id=591633652493058068&permissions=8&scope=bot)", ) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", @@ -1003,9 +998,9 @@ async def invite(ctx): @discord.default_permissions(administrator=True) -@bot.slash_command( - name="settings", description="Modifies some Hammer config values", guild_only=True -) +@bot.slash_command(name="settings", + description="Modifies some Hammer config values", + guild_only=True) @option( "module", description="Pick a module to switch!", @@ -1022,10 +1017,12 @@ async def settings(ctx, module: str = None, value: str = None): value = 1 if value == "on" else 0 await SaveSetting(ctx.guild.id, module, value) action = "enabled" if value else "disabled" - await ctx.respond(f"Module {module} {action} successfully!", ephemeral=True) + await ctx.respond(f"Module {module} {action} successfully!", + ephemeral=True) return else: - await ctx.respond("Use: ``/settings module on/off``", ephemeral=True) + await ctx.respond("Use: ``/settings module on/off``", + ephemeral=True) return embed = Embed( title=f"Hammer Bot Settings :hammer_pick:", @@ -1036,12 +1033,12 @@ async def settings(ctx, module: str = None, value: str = None): automodStatustr = "**✅ ON**" if automodStatus else "**❌ OFF**" recommendedactivityAutomod = ( f"Disable it by doing: ``{COMMAND_PREFIX}settings automod off``" - if automodStatus - else f"Enable it by doing ``{COMMAND_PREFIX}settings automod on``" - ) + if automodStatus else + f"Enable it by doing ``{COMMAND_PREFIX}settings automod on``") embed.add_field( name="AutoMod Services :robot:", - value=f"Actual status: {automodStatustr}\n {recommendedactivityAutomod}", + value= + f"Actual status: {automodStatustr}\n {recommendedactivityAutomod}", inline=True, ) embed.set_footer( From 95095e7fa75024d09656bdfde185f2c2aa8264b2 Mon Sep 17 00:00:00 2001 From: EncryptEx Date: Thu, 10 Nov 2022 16:40:12 +0100 Subject: [PATCH 06/16] major update --- bot.py | 195 ++++++++++++++++++++++++++++++++++----------------------- 1 file changed, 118 insertions(+), 77 deletions(-) diff --git a/bot.py b/bot.py index d971be2..e6696af 100644 --- a/bot.py +++ b/bot.py @@ -2,10 +2,11 @@ import os import sqlite3 import sys -import urllib from email import message from pydoc import describe from time import time +from quickchart import QuickChart +import urllib import discord from discord import Embed @@ -13,7 +14,6 @@ from discord.commands import option from discord.ext import commands from discord.ext.commands.core import command -from quickchart import QuickChart from get_enviroment import ANNOUNCEMENTS_CHANNEL from get_enviroment import COMMAND_PREFIX @@ -23,7 +23,6 @@ from get_enviroment import SECURITY_GUILD from get_enviroment import SWEAR_WORDS_LIST from get_enviroment import TOKEN - # database import & connection conn = sqlite3.connect("maindatabase1.db") @@ -35,6 +34,13 @@ `reason` TEXT, `timestamp` INT); """) +cur.execute("""CREATE TABLE IF NOT EXISTS `customWords` ( + `id` INTEGER PRIMARY KEY AUTOINCREMENT, + `guildid` INT, + `uploaderId`INT, + `word` TEXT, + `type` INT); + """) cur.execute("""CREATE TABLE IF NOT EXISTS `settings` ( `guildid` INT(100) UNIQUE, `automod` INT); @@ -79,6 +85,7 @@ async def help(ctx): {COMMAND_PREFIX}warn [user] {COMMAND_PREFIX}unwarn [user] [id] {COMMAND_PREFIX}clearwarns [user] + {COMMAND_PREFIX}seewarns [user] """, inline=True, ) @@ -146,14 +153,8 @@ async def respondNotifOwner(text): await bot.get_channel(int(SECURITY_CHANNEL)).respond(text) -async def GetWarnings(userid: int, guildid: int, fullData: bool = False): - cur.execute( - "SELECT * FROM warns WHERE userid=? AND guildid=?", - ( - userid, - guildid, - ), - ) +async def GetWarnings(userid: int, guildid:int, fullData: bool=False): + cur.execute("SELECT * FROM warns WHERE userid=? AND guildid=?", (userid,guildid,)) rows = cur.fetchall() if not fullData: return len(rows) @@ -162,7 +163,9 @@ async def GetWarnings(userid: int, guildid: int, fullData: bool = False): # Function to add a warning and save it at the database -async def AddWarning(userid: int, guildid: int, reason): +async def AddWarning( + userid: int, guildid:int, reason +): warncount = await GetWarnings(userid, guildid) cur.execute( """INSERT OR IGNORE INTO warns (userid, guildid, reason, timestamp) @@ -173,9 +176,10 @@ async def AddWarning(userid: int, guildid: int, reason): conn.commit() return warncount + 1 - -async def Removewarn(userid: int, guildId: int, relativeWarnId: int): - c = 0 +async def Removewarn( + userid: int, guildId:int, relativeWarnId:int +): + c=0 for warn in await GetWarnings(userid, guildId, fullData=True): warnRealId, _, _, SubReason, _ = warn if c == relativeWarnId: @@ -195,11 +199,11 @@ async def Clearwarns(userid: int, guildId: int): (userid, guildId)) conn.commit() return - - -async def getAllWarns(userid: int, guildid: int): +async def getAllWarns( + userid: int, guildid:int +): allwarns = [] - c = 0 + c=0 for warn in await GetWarnings(userid, guildid, fullData=True): _, _, _, SubReason, timestamp = warn dt = timestamp @@ -208,14 +212,38 @@ async def getAllWarns(userid: int, guildid: int): else: emojis = str(c) - ddt = int(str(dt)[:str(dt).find(".")]) - allwarns.append( - f"- **ID: {emojis}** Reason: ``{SubReason}`` ") - - c = c + 1 + ddt=int(str(dt)[:str(dt).find(".")]) + allwarns.append(f"- **ID: {emojis}** Reason: ``{SubReason}`` ") + + c=c+1 return allwarns + +async def GetAutomodCustomWords(guildid: int, mode: str): + wtype = 1 if mode == "allow" else 0 + cur.execute("SELECT word FROM customWords WHERE guildid = ? AND type=? LIMIT 1", + (guildid, wtype)) + rows = cur.fetchall() + if len(rows) > 0: + return rows + else: + return [] # default is emptys +async def AddAllowedWord( + guildid: int, userid:int, word:str +): + try: + cur.execute( + """INSERT OR IGNORE INTO warns (id, guildid,uploaderid, word, type) + VALUES (NULL, ?, ?, ?, 1) + """, + (guildid, userid, word), + ) + conn.commit() + except: + return False + return True + async def GetSettings(guildid: int): cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", (guildid, )) @@ -325,13 +353,16 @@ async def on_message(message): if int(await GetSettings(message.guild.id)) != 1: return # user has disabled Automod words = message.content.split() + allowed_words_guild_list = await GetAutomodCustomWords(message.guild.id, "allow") + denied_words_guild_list = await GetAutomodCustomWords(message.guild.id, "deny") print("scanned: ", message.content) for word in words: # print("scanning word:",word) word = str(word).lower() - if word in SWEAR_WORDS_LIST: - # print("detected word:",word) - # print("user",message.author.name,"said",message.content) + if word in allowed_words_guild_list: + continue + + if word in denied_words_guild_list or word in SWEAR_WORDS_LIST: member = message.author # if member == .has perms : # return # is admin so don't warn it @@ -365,6 +396,11 @@ async def on_message(message): value=f"The removed message was \n||{bannedmessage}||", inline=True, ) + embed.add_field( + name="Not happy with this?", + value=f"Disable this feature with ``/settings automod off`` or simply ``/suggest`` a new change", + inline=False, + ) await message.channel.send(embed=embed) await message.delete() try: @@ -588,54 +624,48 @@ async def warn(ctx, member: discord.Member, reason=None): administrator=True, ) async def seewarns(ctx, member: discord.Member): allwarns = await getAllWarns(member.id, ctx.guild.id) - if len(allwarns) == 0: - allwarns = ["User had no warns at the moment"] - message = "\n".join(allwarns) - - c = 0 - data = [] + if(len(allwarns) == 0): allwarns = ['User had no warns at the moment'] + message = '\n'.join(allwarns) + + c=0 + data=[] for warn in await GetWarnings(member.id, ctx.guild.id, fullData=True): - _, _, _, _, timestamp = warn - c = c + 1 - data.append({ - "t": - str( - datetime.datetime.fromtimestamp( - int(str(timestamp)[:str(timestamp).find(".")]))), - "y": - c, - }) + _,_,_,_,timestamp =warn + c=c+1 + data.append({'t':str(datetime.datetime.fromtimestamp(int(str(timestamp)[:str(timestamp).find(".")]))),'y':c}) qc = QuickChart() qc.width = 500 qc.height = 300 qc.device_pixel_ratio = 2.0 qc.config = { - "type": "line", - "data": { - "datasets": [{ - "fill": False, - "label": [f"Warns of {member}"], - "lineTension": 0, - "backgroundColor": "#7289DA", - "borderColor": "#7289DA", - "data": data, - }] - }, - "options": { - "scales": { - "xAxes": [{ - "type": "time", - "time": { - "parser": "YYYY-MM-DD HH:mm:ss", - "displayFormats": { - "day": "DD/MM/YYYY" - }, - }, - }] - } - }, + "type": "line", + "data": { + "datasets": [ + { + "fill": False, + "label": [f"Warns of {member}"], + "lineTension": 0, + "backgroundColor": "#7289DA", + "borderColor": "#7289DA", + "data": data + } + ] + }, + "options": { + "scales": { + "xAxes": [{ + "type": "time", + "time": { + "parser": "YYYY-MM-DD HH:mm:ss", + "displayFormats": { + "day": "DD/MM/YYYY" + } + } + }] } + } +} uurl = qc.get_url() @@ -652,17 +682,15 @@ async def seewarns(ctx, member: discord.Member): name="unwarn", description="Removes a strike from a user") @discord.default_permissions( - kick_members=True, ) -async def unwarn(ctx, member: discord.Member, id: int = None, *, reason=None): - if await GetWarnings(member.id, ctx.guild.id) == 0: + kick_members=True, +) +async def unwarn(ctx, member: discord.Member, id: int=None , *, reason=None): + if(await GetWarnings(member.id, ctx.guild.id) == 0): return await ctx.respond("This user does not have any warn!") if id == None: - message = ( - f"""To select a warn to remove, use argument id and specify its value.""" - ) - - embed = Embed(title=f"ERROR! Need to select a warn :hammer_pick:", - description=message) + message = f"""To select a warn to remove, use argument id and specify its value.""" + + embed = Embed(title=f"ERROR! Need to select a warn :hammer_pick:", description=message) allwarns = await getAllWarns(member.id, ctx.guild.id) embed.add_field( name=f"**Historic of {member.name}**:", @@ -723,6 +751,19 @@ async def clearwarns(ctx, member: discord.Member, *, reason=None): await ctx.respond(embed=embed, ephemeral=False) await SendMessageTo(ctx, member, message) +@bot.slash_command(guild_only=True, + name="automod", + description="Customizes in this guild Hammer's automod") +@discord.default_permissions( + administrator=True, +) +@option( + "function", + description="Select add/remove", + autocomplete=discord.utils.basic_autocomplete(["add", "remove"]), +) +def automod(funtion: str, word: str): + @bot.slash_command(guild_only=True, guild_ids=[int(SECURITY_GUILD)]) async def evaluate(ctx, code): @@ -739,7 +780,7 @@ async def evaluate(ctx, code): "discord": discord, "sys": sys, "os": os, - "cur": cur, + "sqlite3": sqlite3, "imp": __import__, "ctx": ctx, "bot": bot, From 02f4f1215fbbf1d1b1cff90c4c0ce5fa64c78de0 Mon Sep 17 00:00:00 2001 From: EncryptEx Date: Thu, 10 Nov 2022 16:44:02 +0100 Subject: [PATCH 07/16] added help --- bot.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/bot.py b/bot.py index e6696af..fc6e8fb 100644 --- a/bot.py +++ b/bot.py @@ -93,7 +93,13 @@ async def help(ctx): embed.add_field( name="AutoMod Services :robot:", value= - f"Swear Word Detector and wuto warn.\n Using a +880 swear word database", + f"""Swear Word Detector and wuto warn. +Using a +880 swear word database + +Customize it with: +{COMMAND_PREFIX}automod [add/remove] [word] +Or switch it on/off with: +{COMMAND_PREFIX}settings [automod] [on/off]""", inline=True, ) From 6d5c264d9ad3708da4bceb596347c05c12c92983 Mon Sep 17 00:00:00 2001 From: EncryptEx Date: Thu, 10 Nov 2022 17:21:04 +0100 Subject: [PATCH 08/16] added correct command, wip to delete words --- bot.py | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/bot.py b/bot.py index fc6e8fb..50d104f 100644 --- a/bot.py +++ b/bot.py @@ -240,7 +240,7 @@ async def AddAllowedWord( ): try: cur.execute( - """INSERT OR IGNORE INTO warns (id, guildid,uploaderid, word, type) + """INSERT OR IGNORE INTO customWords (id, guildid,uploaderid, word, type) VALUES (NULL, ?, ?, ?, 1) """, (guildid, userid, word), @@ -764,12 +764,22 @@ async def clearwarns(ctx, member: discord.Member, *, reason=None): administrator=True, ) @option( - "function", + "action", description="Select add/remove", autocomplete=discord.utils.basic_autocomplete(["add", "remove"]), ) -def automod(funtion: str, word: str): - +async def automod(ctx, action: str, word: str): + if(action == "add"): + response = AddAllowedWord(ctx.guild.id, ctx.author.id, word) + elif (action == "remove"): + response = AddAllowedWord(ctx.guild.id, ctx.author.id, word) + else: + return await ctx.respond(embed=ErrorEmbed("Wrong syntax, please use /automod add/remove [word]"), ephemeral=True) + if(response): + return await ctx.respond("Word ||"+str(word)+f"|| successfully {action}ed to the database. :tools:", ephemeral=True) + else: + return await ctx.respond(embed=ErrorEmbed( + f"Could not save the word ||{word}|| to the database. Please contact the administrator or bot developer for further information. "), ephemeral=True) @bot.slash_command(guild_only=True, guild_ids=[int(SECURITY_GUILD)]) async def evaluate(ctx, code): From 62bc2612854b434a43bcdffa056a837862501630 Mon Sep 17 00:00:00 2001 From: EncryptEx Date: Thu, 10 Nov 2022 23:12:30 +0100 Subject: [PATCH 09/16] added await --- bot.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/bot.py b/bot.py index 50d104f..f5e78cc 100644 --- a/bot.py +++ b/bot.py @@ -240,7 +240,7 @@ async def AddAllowedWord( ): try: cur.execute( - """INSERT OR IGNORE INTO customWords (id, guildid,uploaderid, word, type) + """INSERT OR IGNORE INTO customWords (id, guildid, uploaderId, word, type) VALUES (NULL, ?, ?, ?, 1) """, (guildid, userid, word), @@ -770,9 +770,9 @@ async def clearwarns(ctx, member: discord.Member, *, reason=None): ) async def automod(ctx, action: str, word: str): if(action == "add"): - response = AddAllowedWord(ctx.guild.id, ctx.author.id, word) + response = await AddAllowedWord(ctx.guild.id, ctx.author.id, word) elif (action == "remove"): - response = AddAllowedWord(ctx.guild.id, ctx.author.id, word) + response = await AddAllowedWord(ctx.guild.id, ctx.author.id, word) else: return await ctx.respond(embed=ErrorEmbed("Wrong syntax, please use /automod add/remove [word]"), ephemeral=True) if(response): From 365a5471d2135fd4407bec6e639d7e5c6c09f5de Mon Sep 17 00:00:00 2001 From: EncryptEx Date: Fri, 11 Nov 2022 00:14:05 +0100 Subject: [PATCH 10/16] wip but progressed, --- bot.py | 2250 ++++++++++++++++++++++++++++---------------------------- 1 file changed, 1142 insertions(+), 1108 deletions(-) diff --git a/bot.py b/bot.py index f5e78cc..dd98e95 100644 --- a/bot.py +++ b/bot.py @@ -1,1108 +1,1142 @@ -import datetime -import os -import sqlite3 -import sys -from email import message -from pydoc import describe -from time import time -from quickchart import QuickChart -import urllib - -import discord -from discord import Embed -from discord import guild_only -from discord.commands import option -from discord.ext import commands -from discord.ext.commands.core import command - -from get_enviroment import ANNOUNCEMENTS_CHANNEL -from get_enviroment import COMMAND_PREFIX -from get_enviroment import DEV_SUGGESTIONS_CHANNEL -from get_enviroment import OWNER -from get_enviroment import SECURITY_CHANNEL -from get_enviroment import SECURITY_GUILD -from get_enviroment import SWEAR_WORDS_LIST -from get_enviroment import TOKEN -# database import & connection - -conn = sqlite3.connect("maindatabase1.db") -cur = conn.cursor() -cur.execute("""CREATE TABLE IF NOT EXISTS `warns` ( - `id` INTEGER PRIMARY KEY AUTOINCREMENT, - `userid` INT(100), - `guildid` INT, - `reason` TEXT, - `timestamp` INT); - """) -cur.execute("""CREATE TABLE IF NOT EXISTS `customWords` ( - `id` INTEGER PRIMARY KEY AUTOINCREMENT, - `guildid` INT, - `uploaderId`INT, - `word` TEXT, - `type` INT); - """) -cur.execute("""CREATE TABLE IF NOT EXISTS `settings` ( - `guildid` INT(100) UNIQUE, - `automod` INT); - """) - -hammericon = "https://images-ext-2.discordapp.net/external/OKc8xu6AILGNFY3nSTt7wGbg-Mi1iQZonoLTFg85o-E/%3Fsize%3D1024/https/cdn.discordapp.com/avatars/591633652493058068/e6011129c5169b29ed05a6dc873175cb.png?width=670&height=670" - -intents = discord.Intents.default() -intents.members = True -intents.message_content = True - -bot = commands.AutoShardedBot(command_prefix=COMMAND_PREFIX, intents=intents) -client = discord.Client() - -bot.remove_command("help") - -# -# HELP SECITON -# - - -@bot.slash_command(name="help", - description="Displays all the available commands for Hammer" - ) -async def help(ctx): - # Define each page - - descr = f"""Hammer is a multiuse bot focused on moderation, which its goal is to improve your discord community. - For an extense command description, use ``{COMMAND_PREFIX}help [command name]`` (comming soon) - **Hammer's commands:** - """ - - embed = Embed(title="Hammer Bot Help", - description=descr, - colour=discord.Colour.lighter_grey()) - - embed.add_field( - name="Moderation Commands :tools:", - value=f""" - {COMMAND_PREFIX}ban [user] - {COMMAND_PREFIX}kick [user] - {COMMAND_PREFIX}warn [user] - {COMMAND_PREFIX}unwarn [user] [id] - {COMMAND_PREFIX}clearwarns [user] - {COMMAND_PREFIX}seewarns [user] - """, - inline=True, - ) - - embed.add_field( - name="AutoMod Services :robot:", - value= - f"""Swear Word Detector and wuto warn. -Using a +880 swear word database - -Customize it with: -{COMMAND_PREFIX}automod [add/remove] [word] -Or switch it on/off with: -{COMMAND_PREFIX}settings [automod] [on/off]""", - inline=True, - ) - - embed.add_field( - name="Chat Moderation Commands :file_folder:", - value=f""" - {COMMAND_PREFIX}setdelay [seconds] - {COMMAND_PREFIX}mute [user] - {COMMAND_PREFIX}unmute [user] - {COMMAND_PREFIX}lock - {COMMAND_PREFIX}unlock - """, - inline=True, - ) - - embed.add_field( - name="Various Utilities :screwdriver:", - value=f""" - {COMMAND_PREFIX}whois [user] - """, - inline=True, - ) - - embed.add_field( - name="""Useful Links: :link:""", - value= - f"""[:classical_building: Hammer Bot Support](https://discord.gg/fMSyQA6) - [:link: Hammer Invite Link](https://discordapp.com/api/oauth2/authorize?client_id=591633652493058068&permissions=8&scope=bot) - [:newspaper: Vote Hammer](https://top.gg/bot/591633652493058068) - """, - inline=True, - ) - - embed.add_field( - name="Help Commands", - value=f""" - {COMMAND_PREFIX}help - {COMMAND_PREFIX}invite - {COMMAND_PREFIX}suggest [suggestion] - """, - inline=True, - ) - - embed.set_footer(text=f"Hammer | Command executed by {ctx.author}", - icon_url=hammericon) - - await ctx.respond(embed=embed) - - -# -# VARIOUS FUNCTIONS -# - - -# Function to alert the owner of something, normally to log use of eval command. -async def respondNotifOwner(text): - await bot.get_channel(int(SECURITY_CHANNEL)).respond(text) - - -async def GetWarnings(userid: int, guildid:int, fullData: bool=False): - cur.execute("SELECT * FROM warns WHERE userid=? AND guildid=?", (userid,guildid,)) - rows = cur.fetchall() - if not fullData: - return len(rows) - else: - return rows - - -# Function to add a warning and save it at the database -async def AddWarning( - userid: int, guildid:int, reason -): - warncount = await GetWarnings(userid, guildid) - cur.execute( - """INSERT OR IGNORE INTO warns (userid, guildid, reason, timestamp) - VALUES (?, ?, ?, ?) - """, - (userid, guildid, reason, time()), - ) - conn.commit() - return warncount + 1 - -async def Removewarn( - userid: int, guildId:int, relativeWarnId:int -): - c=0 - for warn in await GetWarnings(userid, guildId, fullData=True): - warnRealId, _, _, SubReason, _ = warn - if c == relativeWarnId: - # delete that row - cur.execute( - "DELETE FROM warns WHERE userid=? AND guildid=? AND id=? LIMIT 1", - (userid, guildId, warnRealId), - ) - c = c + 1 - conn.commit() - return c - 1 - - -async def Clearwarns(userid: int, guildId: int): - # delete all rows - cur.execute("DELETE FROM warns WHERE userid=? AND guildid=?", - (userid, guildId)) - conn.commit() - return -async def getAllWarns( - userid: int, guildid:int -): - allwarns = [] - c=0 - for warn in await GetWarnings(userid, guildid, fullData=True): - _, _, _, SubReason, timestamp = warn - dt = timestamp - if c <= 9: - emojis = ":" + numToEmoji(c) + ":" - else: - - emojis = str(c) - ddt=int(str(dt)[:str(dt).find(".")]) - allwarns.append(f"- **ID: {emojis}** Reason: ``{SubReason}`` ") - - c=c+1 - return allwarns - -async def GetAutomodCustomWords(guildid: int, mode: str): - wtype = 1 if mode == "allow" else 0 - cur.execute("SELECT word FROM customWords WHERE guildid = ? AND type=? LIMIT 1", - (guildid, wtype)) - rows = cur.fetchall() - if len(rows) > 0: - return rows - else: - return [] # default is emptys - - -async def AddAllowedWord( - guildid: int, userid:int, word:str -): - try: - cur.execute( - """INSERT OR IGNORE INTO customWords (id, guildid, uploaderId, word, type) - VALUES (NULL, ?, ?, ?, 1) - """, - (guildid, userid, word), - ) - conn.commit() - except: - return False - return True - -async def GetSettings(guildid: int): - cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", - (guildid, )) - rows = cur.fetchall() - if len(rows) > 0: - return rows[0][1] - else: - return 1 # default is on - - -async def SaveSetting(guildid: int, module: str, value: int): - cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", - (guildid, )) - rows = cur.fetchall() - # print(rows) - if len( - rows - ) > 0: # cur.execute('INSERT INTO foo (a,b) values (?,?)', (strA, strB)) - query = f"""UPDATE settings - SET automod = {value} - WHERE guildid={guildid} """ - cur.execute(query) - else: - cur.execute( - """INSERT OR IGNORE INTO settings (guildid, automod) - VALUES (?,?) - """, - ( - guildid, - value, - ), - ) - - conn.commit() - return - - -# Function to try to send a message to a user -async def SendMessageTo(ctx, member, message): - try: - await member.send(message) - except: - await ctx.respond( - embed=ErrorEmbed( - f"Could not deliver the message to the user {member}\n This may be caused because the user is a bot, has blocked me or has the DMs turned off. \n\n**But the user is warned** and I have saved it into my beautiful unforgettable database" - ), - ephemeral=True, - ) - - -# Function to create a template for all errors. -def ErrorEmbed(error): - embed = Embed(title=f":no_entry_sign: Error!", description=error) - - embed.set_thumbnail( - url= - "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ficonsplace.com%2Fwp-content%2Fuploads%2F_icons%2Fff0000%2F256%2Fpng%2Ferror-icon-14-256.png&f=1&nofb=1" - ) - - embed.set_footer( - text=f"Hammer", - icon_url=hammericon, - ) - return embed - - -def numToEmoji(num): - v = "" - if num == 0: - v = "zero" - if num == 1: - v = "one" - if num == 2: - v = "two" - if num == 3: - v = "three" - if num == 4: - v = "four" - if num == 5: - v = "five" - if num == 6: - v = "six" - if num == 7: - v = "seven" - if num == 8: - v = "eight" - if num == 9: - v = "nine" - return v - - -# -# MAIN COMMANDS - BOT -# - -# # swear words detector - - -@bot.event -async def on_message(message): - await bot.process_commands(message) - # Skip bot messages - if message.author.bot: - return - if message.content == "" or message.content == None: - return - if int(await GetSettings(message.guild.id)) != 1: - return # user has disabled Automod - words = message.content.split() - allowed_words_guild_list = await GetAutomodCustomWords(message.guild.id, "allow") - denied_words_guild_list = await GetAutomodCustomWords(message.guild.id, "deny") - print("scanned: ", message.content) - for word in words: - # print("scanning word:",word) - word = str(word).lower() - if word in allowed_words_guild_list: - continue - - if word in denied_words_guild_list or word in SWEAR_WORDS_LIST: - member = message.author - # if member == .has perms : - # return # is admin so don't warn it - - # maybe new function to optionally say the word (settings) - descr = ( - f"The user {member} has been warned because said a banned swear word" - ) - embed = Embed(title=f"{member} has been warned! :hammer_pick:", - description=descr) - embed.set_footer( - text=f"Hammer | Automod service", - icon_url=hammericon, - ) - embed.set_thumbnail(url=member.display_avatar) - warn = await AddWarning(member.id, message.guild.id, - "Said a banned swear word") - s = "s" if warn > 1 else "" - embed.add_field( - name="Warn count", - value= - f"The user {member} has {warn} warn{s}. Be careful. Run /seewarns @user to check its warnhistory", - inline=True, - ) - bannedmessage = ( - message.content[:message.content.find(word)] + "~~" + word + - "~~" + - message.content[message.content.find(word) + len(word):]) - embed.add_field( - name="Message Removed:", - value=f"The removed message was \n||{bannedmessage}||", - inline=True, - ) - embed.add_field( - name="Not happy with this?", - value=f"Disable this feature with ``/settings automod off`` or simply ``/suggest`` a new change", - inline=False, - ) - await message.channel.send(embed=embed) - await message.delete() - try: - channel = await member.create_dm() - await channel.send(embed=embed) - - except: - embed = ErrorEmbed( - await message.channel.send( - f"Could not deliver the message to the user {member}\n This may be caused because the user is a bot, has blocked me or has the DMs turned off. \n\n**But the user is warned** and I have saved it into my beautiful unforgettable database" - ), ) - # if(str(message.content).startswith(COMMAND_PREFIX)): - # print("command executed", message.content) - - -@bot.event -async def on_ready(): - await bot.change_presence(activity=discord.Activity( - type=discord.ActivityType.watching, name="you")) - print("HAMMER BOT Ready!", datetime.datetime.now()) - botname = await bot.application_info() - print("logged in as:", botname.name) - if botname.name == "Hammer": - print("I'm on:") - print(len(bot.guilds), "servers") - print(sum(1 for x in bot.get_all_channels()), "channels") - print(sum(1 for x in bot.get_all_members()), "members") - chnl = bot.get_channel(int(ANNOUNCEMENTS_CHANNEL)) - await chnl.send("Bot UP!") - print("Sent message to #" + str(chnl)) - - -debug = False - - -@bot.slash_command(guild_only=True, - name="hello", - guild_ids=[int(SECURITY_GUILD)]) -async def hello(ctx): - await ctx.respond("Hammer is back!") - - -@bot.event -async def on_command_error(ctx, error): - if isinstance(error, commands.MissingRequiredArgument): - await ctx.respond( - f"**[ERROR 404]** Please pass in all requirements :hammer_pick:. ```{error}```\nDo {COMMAND_PREFIX}help command for more help", - ephemeral=True, - ) - if isinstance(error, commands.MissingPermissions): - error = getattr(error, "original", error) - missing = [ - perm.replace("_", " ").replace("guild", "server").title() - for perm in error.missing_perms - ] - if len(missing) > 2: - fmt = "{}, and {}".format("**, **".join(missing[:-1]), missing[-1]) - else: - fmt = " and ".join(missing) - await ctx.respond( - "[**ERROR 403**] You don't have the correct permission to do that :hammer:, You need {fmt} permission(s) to perform this action", - ephemeral=True, - ) - - -@bot.slash_command( - guild_only=True, - name="whois", - description="Displays all the public info from a specific user", -) -async def whois(ctx, member: discord.Member): - - try: - username, discriminator = str(member).split("#") - isbot = ":white_check_mark:" if member.bot else ":negative_squared_cross_mark:" - descr = f""" - **Nick:** {member.nick} - **Username:** {username} - **Discriminator:** {discriminator} - **Created account at:** {member.created_at} - **Joined server at:** {member.joined_at} - **Is bot:** {isbot} - **User ID:** {member.id} - **Avatar URL:** [Click Here]({member.display_avatar}) - **Top role:** {member.top_role} - **Warns:** {await GetWarnings(member.id, ctx.guild.id)} - """ - embed = Embed(title=f"Who is {member} ?", description=descr) - - embed.set_thumbnail(url=member.display_avatar) - - embed.set_footer( - text=f"Hammer | Command executed by {ctx.author}", - icon_url=hammericon, - ) - await ctx.respond(embed=embed) - except Exception as e: - await ctx.respond(e) - - -@bot.slash_command( - guild_only=True, - name="ban", - description="Keeps out a user permanently, forbidding its entry", -) -@discord.default_permissions( - ban_members=True, ) -async def ban(ctx, member: discord.Member, *, reason=None): - - if member == ctx.author: - await ctx.respond("You cannot ban yourself", ephemeral=True) - return - if reason == None: - reason = "bad behaviour 💥" - message = f"You have been banned from {ctx.guild.name} for {reason}" - - descr = f"The user {member} has been banned for {reason}" - embed = Embed(title=f"{member} has been banned! :hammer_pick:", - description=descr) - embed.set_image(url="https://i.imgflip.com/19zat3.jpg") - embed.set_footer( - text=f"Hammer | Command executed by {ctx.author}", - icon_url=hammericon, - ) - if not debug: - try: - await member.ban(reason=reason) - except: - ctx.respond( - embed=ErrorEmbed( - f"Could not ban the user {member}\n This may be caused because I do not have the permission to do that or the user has a higher role than me." - ), - ephemeral=True, - ) - return - - embed.set_thumbnail(url=member.display_avatar) - await ctx.respond(embed=embed) - await SendMessageTo(ctx, member, message) - - -@bot.slash_command(guild_only=True, - name="kick", - description="Kicks out a member from the server") -@discord.default_permissions( - kick_members=True, ) -async def kick(ctx, member: discord.Member, *, reason=None): - - if member == ctx.author: - await ctx.respond("You cannot kick yourself", ephemeral=True) - return - if reason == None: - reason = "bad behaviour 💥" - message = f"You have been kicked from {ctx.guild.name} for {reason}" - if not debug: - try: - await member.kick(reason=reason) - except: - ctx.respond( - embed=ErrorEmbed( - f"Could not kick the user {member}\n This may be caused because I do not have the permission to do that or the user has a higher role than me." - ), - ephemeral=True, - ) - return - descr = f"The user {member} has been kicked for {reason}" - embed = Embed(title=f"{member} has been kicked! :hammer_pick:", - description=descr) - embed.set_footer( - text=f"Hammer | Command executed by {ctx.author}", - icon_url=hammericon, - ) - embed.set_thumbnail(url=member.display_avatar) - # # embed.image = member.image - await ctx.respond(embed=embed) - await SendMessageTo(ctx, member, message) - - -@bot.slash_command( - guild_only=True, - name="warn", - description="Sets a warning for a user, at 3 warns/strikes they get kicked", -) -@discord.default_permissions( - administrator=True, ) -async def warn(ctx, member: discord.Member, reason=None): - - if member == ctx.author: - await ctx.respond("You cannot warn yourself :(", ephemeral=True) - return - if reason == None: - reason = "bad behaviour 💥" - message = f"You have been warned for {reason}" - - descr = f"The user {member} has been warned for {reason}" - embed = Embed(title=f"{member} has been warned! :hammer_pick:", - description=descr) - embed.set_footer( - text=f"Hammer | Command executed by {ctx.author}", - icon_url=hammericon, - ) - embed.set_thumbnail(url=member.display_avatar) - warn = await AddWarning(member.id, ctx.guild.id, reason) - s = "s" if warn > 1 else "" - embed.add_field( - name="Warn count", - value=f"The user {member} has {warn} warn{s}. Be careful.", - inline=True, - ) - await ctx.respond(embed=embed) - - await SendMessageTo(ctx, member, message) - - -@bot.slash_command( - guild_only=True, - name="seewarns", - description="Displays the warn history of a user in the guild", -) -@discord.default_permissions( - administrator=True, ) -async def seewarns(ctx, member: discord.Member): - allwarns = await getAllWarns(member.id, ctx.guild.id) - if(len(allwarns) == 0): allwarns = ['User had no warns at the moment'] - message = '\n'.join(allwarns) - - c=0 - data=[] - for warn in await GetWarnings(member.id, ctx.guild.id, fullData=True): - _,_,_,_,timestamp =warn - c=c+1 - data.append({'t':str(datetime.datetime.fromtimestamp(int(str(timestamp)[:str(timestamp).find(".")]))),'y':c}) - - qc = QuickChart() - qc.width = 500 - qc.height = 300 - qc.device_pixel_ratio = 2.0 - qc.config = { - "type": "line", - "data": { - "datasets": [ - { - "fill": False, - "label": [f"Warns of {member}"], - "lineTension": 0, - "backgroundColor": "#7289DA", - "borderColor": "#7289DA", - "data": data - } - ] - }, - "options": { - "scales": { - "xAxes": [{ - "type": "time", - "time": { - "parser": "YYYY-MM-DD HH:mm:ss", - "displayFormats": { - "day": "DD/MM/YYYY" - } - } - }] - } - } -} - - uurl = qc.get_url() - - embed = Embed(title=f"**Historic of {member}**", description=message) - embed.set_image(url=uurl) - embed.set_footer( - text=f"Hammer | Command executed by {ctx.author}", - icon_url=hammericon, - ) - return await ctx.respond(embed=embed) - - -@bot.slash_command(guild_only=True, - name="unwarn", - description="Removes a strike from a user") -@discord.default_permissions( - kick_members=True, -) -async def unwarn(ctx, member: discord.Member, id: int=None , *, reason=None): - if(await GetWarnings(member.id, ctx.guild.id) == 0): - return await ctx.respond("This user does not have any warn!") - if id == None: - message = f"""To select a warn to remove, use argument id and specify its value.""" - - embed = Embed(title=f"ERROR! Need to select a warn :hammer_pick:", description=message) - allwarns = await getAllWarns(member.id, ctx.guild.id) - embed.add_field( - name=f"**Historic of {member.name}**:", - value="\n".join(allwarns), - ) - return await ctx.respond(embed=embed) - if reason == None: - reason = "good behaviour ✅" - message = f"You have been unwarned for {reason}" - - descr = f"The user {member} has been unwarned for {reason}" - embed = Embed(title=f"{member} has been unwarned! :hammer_pick:", - description=descr) - embed.set_footer( - text=f"Hammer | Command executed by {ctx.author}", - icon_url=hammericon, - ) - embed.set_thumbnail(url=member.display_avatar) - warn = await Removewarn(member.id, ctx.guild.id, id) - s = "s" if warn > 1 else "" - congrats = "Yey! :tada:" if warn == 0 else "" - embed.add_field( - name="Warn count", - value=f"The user {member} has now {warn} warn{s}. {congrats}", - inline=True, - ) - await ctx.respond(embed=embed) - await SendMessageTo(ctx, member, message) - - -@bot.slash_command(guild_only=True, - name="clearwarns", - description="Removes all strikes from a user") -@discord.default_permissions( - kick_members=True, ) -async def clearwarns(ctx, member: discord.Member, *, reason=None): - - if reason == None: - reason = "good behaviour ✅" - message = f"Your warns have been cleared for {reason}" - - descr = f"The user {member} has 0 warns for {reason}" - embed = Embed( - title=f"The warns of {member} have been removed! :hammer_pick:", - description=descr, - ) - embed.set_footer( - text=f"Hammer | Command executed by {ctx.author}", - icon_url=hammericon, - ) - embed.set_thumbnail(url=member.display_avatar) - warn = await Clearwarns(member.id, ctx.guild.id) - embed.add_field( - name="Warn count", - value=f"The user {member} has now {warn} warns. Yey! :tada:", - inline=True, - ) - await ctx.respond(embed=embed, ephemeral=False) - await SendMessageTo(ctx, member, message) - -@bot.slash_command(guild_only=True, - name="automod", - description="Customizes in this guild Hammer's automod") -@discord.default_permissions( - administrator=True, -) -@option( - "action", - description="Select add/remove", - autocomplete=discord.utils.basic_autocomplete(["add", "remove"]), -) -async def automod(ctx, action: str, word: str): - if(action == "add"): - response = await AddAllowedWord(ctx.guild.id, ctx.author.id, word) - elif (action == "remove"): - response = await AddAllowedWord(ctx.guild.id, ctx.author.id, word) - else: - return await ctx.respond(embed=ErrorEmbed("Wrong syntax, please use /automod add/remove [word]"), ephemeral=True) - if(response): - return await ctx.respond("Word ||"+str(word)+f"|| successfully {action}ed to the database. :tools:", ephemeral=True) - else: - return await ctx.respond(embed=ErrorEmbed( - f"Could not save the word ||{word}|| to the database. Please contact the administrator or bot developer for further information. "), ephemeral=True) - -@bot.slash_command(guild_only=True, guild_ids=[int(SECURITY_GUILD)]) -async def evaluate(ctx, code): - - if str(ctx.author.id) == str(OWNER): - try: - # await respondNotifOwner( - # f"User {ctx.author} used command evaluate | id {ctx.author.id}" - # ) - print("RECIEVED:", code) - # t = ctx.author.id,"used the command eval at", datetime.now() - # print(t) - args = { - "discord": discord, - "sys": sys, - "os": os, - "sqlite3": sqlite3, - "imp": __import__, - "ctx": ctx, - "bot": bot, - } - try: - exec(f"async def func(): return {code}", args) - a = time() - response = await eval("func()", args) - await ctx.respond( - f"```py\n{response}``````{type(response).__name__}``` `| {(time() - a) / 1000} ms`", - ephemeral=True, - ) - except Exception as e: - await ctx.respond( - f"Error occurred:```\n{type(e).__name__}: {str(e)}```", - ephemeral=True, - ) - except Exception as e: - await ctx.respond(e, ephemeral=True) - else: - await ctx.respond("you're not allowed to do that") - - -def restart_bot(): - os.execv(sys.executable, ["python"] + sys.argv) - - -@bot.slash_command(guild_only=True, guild_ids=[int(SECURITY_GUILD)]) -async def restart(ctx): - - if str(ctx.author.id) == str(OWNER): - try: - # await respondNotifOwner( - # f"User {ctx.author} used command evaluate | id {ctx.author.id}" - # ) - print("===== RESTART asked by", ctx.author, "=====") - # t = ctx.author.id,"used the command eval at", datetime.now() - # print(t) - print("CLOSING SESSION") - - await bot.close() - print("FETCHING NEW CHANGES IN GITHUB") - import subprocess - - try: - if not debug: - # Remove any changes done - res = subprocess.check_output(["git", "reset", "--hard"]) - for line in res.splitlines(): - print(line) - # Update files - res = subprocess.check_output(["git", "pull"]) - for line in res.splitlines(): - print(line) - except Exception as e: - await ctx.respond(e, ephemeral=True) - print("===== STARTING BOT AGAIN =====") - try: - restart_bot() - except Exception as e: - print(e) - await ctx.respond("Bot restarted successfully!", ephemeral=True) - except Exception as e: - await ctx.respond(e, ephemeral=True) - else: - await ctx.respond("you're not allowed to do that") - - -@bot.slash_command( - guild_only=True, - name="setdelay", - description= - "Updates the message delay in a channel with a set of custom time interval", -) -@discord.default_permissions( - manage_messages=True, ) -async def setdelay(ctx, seconds: float, reason: str = ""): - - m = "modified" if seconds > 0.0 else "removed" - embed = Embed( - title=f"Delay {m} on #{ctx.channel} :hammer_pick:", - description= - f"This channel now has a delay of **{seconds}** seconds for {reason}" - if reason != None and reason != "" else - f"This channel now has a delay of **{seconds}** seconds", - ) - embed.set_footer( - text=f"Hammer | Command executed by {ctx.author}", - icon_url=hammericon, - ) - - await ctx.channel.edit(slowmode_delay=seconds) - await ctx.respond(embed=embed) - - -# description="Mutes the specified user." -@bot.slash_command( - guild_only=True, - name="mute", - description="Removes the hability to talk or join voice channels to a user", -) -@discord.default_permissions( - manage_messages=True, ) -async def mute(ctx, member: discord.Member, *, reason=None): - - guild = ctx.guild - mutedRole = discord.utils.get(guild.roles, name="Muted") - - if not mutedRole: - mutedRole = await guild.create_role(name="Muted") - - for channel in guild.channels: - await channel.set_permissions( - mutedRole, - speak=False, - respond_messages=False, - read_message_history=True, - read_messages=False, - ) - - if reason == None: - reason = "bad behaviour 💥" - - embed = discord.Embed( - title=f"User Muted: {member}", - description=f"User {member.mention} has been muted for {reason}", - colour=discord.Colour.red(), - ) - await ctx.respond(embed=embed) - await member.add_roles(mutedRole, reason=reason) - - SendMessageTo( - ctx, - member, - f":no_entry: You have been muted from: {ctx.guild.name} for {reason}", - ) - - -# description="Unmutes a specified user." -@bot.slash_command( - guild_only=True, - name="unmute", - description= - "Restores the hability to talk or join voice channels to a user", -) -@discord.default_permissions( - manage_messages=True, ) -async def unmute(ctx, member: discord.Member, *, reason=None): - - mutedRole = discord.utils.get(ctx.guild.roles, name="Muted") - if reason == None: - reason = " " - else: - reason = "for " + reason - await member.remove_roles(mutedRole) - SendMessageTo( - ctx, member, - f":tada: You have been unmuted from: {ctx.guild.name} {reason}") - embed = discord.Embed( - title=f"User Unmuted: {member}", - description=f"User {member.mention} has been unmuted {reason}", - colour=discord.Colour.light_gray(), - ) - await ctx.respond(embed=embed) - - -@discord.default_permissions(manage_channels=True) -@bot.slash_command( - guild_only=True, - name="lock", - description="Blocks a channel from being used as a chat.", -) -async def lock(ctx, channel: discord.TextChannel = None, reason=None): - - channel = channel or ctx.channel - reason = "for " + reason if reason else "" - overwrite = channel.overwrites_for(ctx.guild.default_role) - overwrite.send_messages = False - await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite) - embed = Embed( - title=f"The channel #{ctx.channel} has been locked! :hammer_pick:", - description=f"This channel is now locked {reason}", - ) - embed.set_footer( - text=f"Hammer | Command executed by {ctx.author}", - icon_url=hammericon, - ) - await ctx.respond(embed=embed) - - -@discord.default_permissions(manage_channels=True) -@bot.slash_command( - guild_only=True, - name="unlock", - description= - "Removes the blocking in a channel from not being used as a chat.", -) -async def unlock(ctx, channel: discord.TextChannel = None, reason=None): - - channel = channel or ctx.channel - reason = "for " + reason if reason else "" - overwrite = channel.overwrites_for(ctx.guild.default_role) - overwrite.send_messages = True - await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite) - embed = Embed( - title=f"The channel #{ctx.channel} has been unlocked! :hammer_pick:", - description=f"This channel is now unlocked {reason}", - ) - embed.set_footer( - text=f"Hammer | Command executed by {ctx.author}", - icon_url=hammericon, - ) - await ctx.respond(embed=embed) - - -@bot.slash_command( - name="suggest", - description="Sends a suggestion to the developer of Hammer.", -) -async def suggest(ctx, suggestion: str): - - embed = Embed( - title=f"The user {ctx.author} has posted a suggestion! :hammer_pick:", - description=f"{suggestion}", - ) - embed.set_footer( - text=f"Hammer | Command executed by {ctx.author}", - icon_url=hammericon, - ) - suggestionChannel = bot.get_channel(int(DEV_SUGGESTIONS_CHANNEL)) - await suggestionChannel.send(embed=embed) - await ctx.respond( - "[200 OK] ✅ Your suggestion has been successfully recieved! \n Join our support server to see how does it progress! (in /help you'll find the link)", - ephemeral=True, - ) - - -@bot.slash_command( - name="invite", - description="Returns the bot's invitation link.", -) -async def invite(ctx): - embed = Embed( - title=f"Invite Hammer Bot to your server! :hammer_pick:", - description= - f"[**🔗 Hammer Invite Link**](https://discordapp.com/api/oauth2/authorize?client_id=591633652493058068&permissions=8&scope=bot)", - ) - embed.set_footer( - text=f"Hammer | Command executed by {ctx.author}", - icon_url=hammericon, - ) - await ctx.respond(embed=embed) - - -modules = ["automod"] - - -@discord.default_permissions(administrator=True) -@bot.slash_command(name="settings", - description="Modifies some Hammer config values", - guild_only=True) -@option( - "module", - description="Pick a module to switch!", - autocomplete=discord.utils.basic_autocomplete(modules), -) -@option( - "value", - description="Select on/off", - autocomplete=discord.utils.basic_autocomplete(["on", "off"]), -) -async def settings(ctx, module: str = None, value: str = None): - if module != None and value != None: - if module in modules and value == "on" or value == "off": - value = 1 if value == "on" else 0 - await SaveSetting(ctx.guild.id, module, value) - action = "enabled" if value else "disabled" - await ctx.respond(f"Module {module} {action} successfully!", - ephemeral=True) - return - else: - await ctx.respond("Use: ``/settings module on/off``", - ephemeral=True) - return - embed = Embed( - title=f"Hammer Bot Settings :hammer_pick:", - description=f"Here you can enable or disable some modules", - ) - print("getting settings from discord.Guild.id", ctx.guild.id) - automodStatus = await GetSettings(ctx.guild.id) - automodStatustr = "**✅ ON**" if automodStatus else "**❌ OFF**" - recommendedactivityAutomod = ( - f"Disable it by doing: ``{COMMAND_PREFIX}settings automod off``" - if automodStatus else - f"Enable it by doing ``{COMMAND_PREFIX}settings automod on``") - embed.add_field( - name="AutoMod Services :robot:", - value= - f"Actual status: {automodStatustr}\n {recommendedactivityAutomod}", - inline=True, - ) - embed.set_footer( - text=f"Hammer | Command executed by {ctx.author}", - icon_url=hammericon, - ) - await ctx.respond(embed=embed) - - -bot.run(TOKEN) +import datetime +import os +import sqlite3 +import sys +from email import message +from pydoc import describe +from time import time +from quickchart import QuickChart +import urllib + +import discord +from discord import Embed +from discord import guild_only +from discord.commands import option +from discord.ext import commands +from discord.ext.commands.core import command + +from get_enviroment import ANNOUNCEMENTS_CHANNEL +from get_enviroment import COMMAND_PREFIX +from get_enviroment import DEV_SUGGESTIONS_CHANNEL +from get_enviroment import OWNER +from get_enviroment import SECURITY_CHANNEL +from get_enviroment import SECURITY_GUILD +from get_enviroment import SWEAR_WORDS_LIST +from get_enviroment import TOKEN +# database import & connection + +conn = sqlite3.connect("maindatabase1.db") +cur = conn.cursor() +cur.execute("""CREATE TABLE IF NOT EXISTS `warns` ( + `id` INTEGER PRIMARY KEY AUTOINCREMENT, + `userid` INT(100), + `guildid` INT, + `reason` TEXT, + `timestamp` INT); + """) +cur.execute("""CREATE TABLE IF NOT EXISTS `customWords` ( + `id` INTEGER PRIMARY KEY AUTOINCREMENT, + `guildid` INT, + `uploaderId`INT, + `word` TEXT, + `type` INT); + """) +cur.execute("""CREATE TABLE IF NOT EXISTS `settings` ( + `guildid` INT(100) UNIQUE, + `automod` INT); + """) + +hammericon = "https://images-ext-2.discordapp.net/external/OKc8xu6AILGNFY3nSTt7wGbg-Mi1iQZonoLTFg85o-E/%3Fsize%3D1024/https/cdn.discordapp.com/avatars/591633652493058068/e6011129c5169b29ed05a6dc873175cb.png?width=670&height=670" + +intents = discord.Intents.default() +intents.members = True +intents.message_content = True + +bot = commands.AutoShardedBot(command_prefix=COMMAND_PREFIX, intents=intents) +client = discord.Client() + +bot.remove_command("help") + +# +# HELP SECITON +# + + +@bot.slash_command(name="help", + description="Displays all the available commands for Hammer" + ) +async def help(ctx): + # Define each page + + descr = f"""Hammer is a multiuse bot focused on moderation, which its goal is to improve your discord community. + For an extense command description, use ``{COMMAND_PREFIX}help [command name]`` (comming soon) + **Hammer's commands:** + """ + + embed = Embed(title="Hammer Bot Help", + description=descr, + colour=discord.Colour.lighter_grey()) + + embed.add_field( + name="Moderation Commands :tools:", + value=f""" + {COMMAND_PREFIX}ban [user] + {COMMAND_PREFIX}kick [user] + {COMMAND_PREFIX}warn [user] + {COMMAND_PREFIX}unwarn [user] [id] + {COMMAND_PREFIX}clearwarns [user] + {COMMAND_PREFIX}seewarns [user] + """, + inline=True, + ) + + embed.add_field( + name="AutoMod Services :robot:", + value= + f"""Swear Word Detector and wuto warn. +Using a +880 swear word database + +Customize it with: +{COMMAND_PREFIX}automod [add/remove] [word] +Or switch it on/off with: +{COMMAND_PREFIX}settings [automod] [on/off]""", + inline=True, + ) + + embed.add_field( + name="Chat Moderation Commands :file_folder:", + value=f""" + {COMMAND_PREFIX}setdelay [seconds] + {COMMAND_PREFIX}mute [user] + {COMMAND_PREFIX}unmute [user] + {COMMAND_PREFIX}lock + {COMMAND_PREFIX}unlock + """, + inline=True, + ) + + embed.add_field( + name="Various Utilities :screwdriver:", + value=f""" + {COMMAND_PREFIX}whois [user] + """, + inline=True, + ) + + embed.add_field( + name="""Useful Links: :link:""", + value= + f"""[:classical_building: Hammer Bot Support](https://discord.gg/fMSyQA6) + [:link: Hammer Invite Link](https://discordapp.com/api/oauth2/authorize?client_id=591633652493058068&permissions=8&scope=bot) + [:newspaper: Vote Hammer](https://top.gg/bot/591633652493058068) + """, + inline=True, + ) + + embed.add_field( + name="Help Commands", + value=f""" + {COMMAND_PREFIX}help + {COMMAND_PREFIX}invite + {COMMAND_PREFIX}suggest [suggestion] + """, + inline=True, + ) + + embed.set_footer(text=f"Hammer | Command executed by {ctx.author}", + icon_url=hammericon) + + await ctx.respond(embed=embed) + + +# +# VARIOUS FUNCTIONS +# + + +# Function to alert the owner of something, normally to log use of eval command. +async def respondNotifOwner(text): + await bot.get_channel(int(SECURITY_CHANNEL)).respond(text) + + +async def GetWarnings(userid: int, guildid:int, fullData: bool=False): + cur.execute("SELECT * FROM warns WHERE userid=? AND guildid=?", (userid,guildid,)) + rows = cur.fetchall() + if not fullData: + return len(rows) + else: + return rows + + +# Function to add a warning and save it at the database +async def AddWarning( + userid: int, guildid:int, reason +): + warncount = await GetWarnings(userid, guildid) + cur.execute( + """INSERT OR IGNORE INTO warns (userid, guildid, reason, timestamp) + VALUES (?, ?, ?, ?) + """, + (userid, guildid, reason, time()), + ) + conn.commit() + return warncount + 1 + +async def Removewarn( + userid: int, guildId:int, relativeWarnId:int +): + c=0 + for warn in await GetWarnings(userid, guildId, fullData=True): + warnRealId, _, _, SubReason, _ = warn + if c == relativeWarnId: + # delete that row + cur.execute( + "DELETE FROM warns WHERE userid=? AND guildid=? AND id=? LIMIT 1", + (userid, guildId, warnRealId), + ) + c = c + 1 + conn.commit() + return c - 1 + + +async def Clearwarns(userid: int, guildId: int): + # delete all rows + cur.execute("DELETE FROM warns WHERE userid=? AND guildid=?", + (userid, guildId)) + conn.commit() + return +async def getAllWarns( + userid: int, guildid:int +): + allwarns = [] + c=0 + for warn in await GetWarnings(userid, guildid, fullData=True): + _, _, _, SubReason, timestamp = warn + dt = timestamp + if c <= 9: + emojis = ":" + numToEmoji(c) + ":" + else: + + emojis = str(c) + ddt=int(str(dt)[:str(dt).find(".")]) + allwarns.append(f"- **ID: {emojis}** Reason: ``{SubReason}`` ") + + c=c+1 + return allwarns + +async def GetAutomodCustomWords(guildid: int, mode: str): + wtype = 1 if mode == "allow" else 0 + cur.execute("SELECT word FROM customWords WHERE guildid = ? AND type = ?", + (guildid, wtype)) + words = cur.fetchall() + a=[] + if len(words) > 0: + for word in words: + a.append(str(word[0])) + return a + else: + return [] # default is emptys + + +async def AddAllowedWord( + guildid: int, userid:int, word:str +): + # check if user is in blacklist + # if(word in await GetAutomodCustomWords(guildid, "deny")): + + + try: + cur.execute( + """DELETE FROM customWords WHERE guildid=? AND word=? AND type=0 + """, + (guildid, word), + ) + + cur.execute( + """INSERT OR IGNORE INTO customWords (id, guildid, uploaderId, word, type) + VALUES (NULL, ?, ?, ?, 1) + """, + (guildid, userid, word), + ) + conn.commit() + except: + return False + return True + +async def AddDeniedWord( + guildid: int, userid:int, word:str +): + try: + cur.execute( + """DELETE FROM customWords WHERE guildid=? AND word=? AND type=1 + """, + (guildid, word), + ) + + cur.execute( + """INSERT OR IGNORE INTO customWords (id, guildid, uploaderId, word, type) + VALUES (NULL, ?, ?, ?, 0) + """, + (guildid, userid, word), + ) + conn.commit() + except: + return False + return True + +async def GetSettings(guildid: int): + cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", + (guildid, )) + rows = cur.fetchall() + if len(rows) > 0: + return rows[0][1] + else: + return 1 # default is on + + +async def SaveSetting(guildid: int, module: str, value: int): + cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", + (guildid, )) + rows = cur.fetchall() + # print(rows) + if len( + rows + ) > 0: # cur.execute('INSERT INTO foo (a,b) values (?,?)', (strA, strB)) + query = f"""UPDATE settings + SET automod = {value} + WHERE guildid={guildid} """ + cur.execute(query) + else: + cur.execute( + """INSERT OR IGNORE INTO settings (guildid, automod) + VALUES (?,?) + """, + ( + guildid, + value, + ), + ) + + conn.commit() + return + + +# Function to try to send a message to a user +async def SendMessageTo(ctx, member, message): + try: + await member.send(message) + except: + await ctx.respond( + embed=ErrorEmbed( + f"Could not deliver the message to the user {member}\n This may be caused because the user is a bot, has blocked me or has the DMs turned off. \n\n**But the user is warned** and I have saved it into my beautiful unforgettable database" + ), + ephemeral=True, + ) + + +# Function to create a template for all errors. +def ErrorEmbed(error): + embed = Embed(title=f":no_entry_sign: Error!", description=error) + + embed.set_thumbnail( + url= + "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ficonsplace.com%2Fwp-content%2Fuploads%2F_icons%2Fff0000%2F256%2Fpng%2Ferror-icon-14-256.png&f=1&nofb=1" + ) + + embed.set_footer( + text=f"Hammer", + icon_url=hammericon, + ) + return embed + + +def numToEmoji(num): + v = "" + if num == 0: + v = "zero" + if num == 1: + v = "one" + if num == 2: + v = "two" + if num == 3: + v = "three" + if num == 4: + v = "four" + if num == 5: + v = "five" + if num == 6: + v = "six" + if num == 7: + v = "seven" + if num == 8: + v = "eight" + if num == 9: + v = "nine" + return v + + +# +# MAIN COMMANDS - BOT +# + +# # swear words detector + + +@bot.event +async def on_message(message): + await bot.process_commands(message) + # Skip bot messages + if message.author.bot: + return + if message.content == "" or message.content == None: + return + if int(await GetSettings(message.guild.id)) != 1: + return # user has disabled Automod + words = message.content.split() + allowed_words_guild_list = await GetAutomodCustomWords(message.guild.id, "allow") + denied_words_guild_list = await GetAutomodCustomWords(message.guild.id, "deny") + print("scanned: ", message.content) + for word in words: + # print("scanning word:",word) + word = str(word).lower() + if word in allowed_words_guild_list: + continue + + if word in denied_words_guild_list or word in SWEAR_WORDS_LIST: + member = message.author + # if member == .has perms : + # return # is admin so don't warn it + + # maybe new function to optionally say the word (settings) + descr = ( + f"The user {member} has been warned because said a banned swear word" + ) + embed = Embed(title=f"{member} has been warned! :hammer_pick:", + description=descr) + embed.set_footer( + text=f"Hammer | Automod service", + icon_url=hammericon, + ) + embed.set_thumbnail(url=member.display_avatar) + warn = await AddWarning(member.id, message.guild.id, + "Said a banned swear word") + s = "s" if warn > 1 else "" + embed.add_field( + name="Warn count", + value= + f"The user {member} has {warn} warn{s}. Be careful. Run /seewarns @user to check its warnhistory", + inline=True, + ) + bannedmessage = ( + message.content[:message.content.find(word)] + "~~" + word + + "~~" + + message.content[message.content.find(word) + len(word):]) + embed.add_field( + name="Message Removed:", + value=f"The removed message was \n||{bannedmessage}||", + inline=True, + ) + embed.add_field( + name="Not happy with this?", + value=f"Disable this feature with ``/settings automod off`` or simply ``/suggest`` a new change", + inline=False, + ) + await message.channel.send(embed=embed) + await message.delete() + try: + channel = await member.create_dm() + await channel.send(embed=embed) + + except: + embed = ErrorEmbed( + await message.channel.send( + f"Could not deliver the message to the user {member}\n This may be caused because the user is a bot, has blocked me or has the DMs turned off. \n\n**But the user is warned** and I have saved it into my beautiful unforgettable database" + ), ) + # if(str(message.content).startswith(COMMAND_PREFIX)): + # print("command executed", message.content) + + +@bot.event +async def on_ready(): + await bot.change_presence(activity=discord.Activity( + type=discord.ActivityType.watching, name="you")) + print("HAMMER BOT Ready!", datetime.datetime.now()) + botname = await bot.application_info() + print("logged in as:", botname.name) + if botname.name == "Hammer": + print("I'm on:") + print(len(bot.guilds), "servers") + print(sum(1 for x in bot.get_all_channels()), "channels") + print(sum(1 for x in bot.get_all_members()), "members") + chnl = bot.get_channel(int(ANNOUNCEMENTS_CHANNEL)) + await chnl.send("Bot UP!") + print("Sent message to #" + str(chnl)) + + +debug = False + + +@bot.slash_command(guild_only=True, + name="hello", + guild_ids=[int(SECURITY_GUILD)]) +async def hello(ctx): + await ctx.respond("Hammer is back!") + + +@bot.event +async def on_command_error(ctx, error): + if isinstance(error, commands.MissingRequiredArgument): + await ctx.respond( + f"**[ERROR 404]** Please pass in all requirements :hammer_pick:. ```{error}```\nDo {COMMAND_PREFIX}help command for more help", + ephemeral=True, + ) + if isinstance(error, commands.MissingPermissions): + error = getattr(error, "original", error) + missing = [ + perm.replace("_", " ").replace("guild", "server").title() + for perm in error.missing_perms + ] + if len(missing) > 2: + fmt = "{}, and {}".format("**, **".join(missing[:-1]), missing[-1]) + else: + fmt = " and ".join(missing) + await ctx.respond( + "[**ERROR 403**] You don't have the correct permission to do that :hammer:, You need {fmt} permission(s) to perform this action", + ephemeral=True, + ) + + +@bot.slash_command( + guild_only=True, + name="whois", + description="Displays all the public info from a specific user", +) +async def whois(ctx, member: discord.Member): + + try: + username, discriminator = str(member).split("#") + isbot = ":white_check_mark:" if member.bot else ":negative_squared_cross_mark:" + descr = f""" + **Nick:** {member.nick} + **Username:** {username} + **Discriminator:** {discriminator} + **Created account at:** {member.created_at} + **Joined server at:** {member.joined_at} + **Is bot:** {isbot} + **User ID:** {member.id} + **Avatar URL:** [Click Here]({member.display_avatar}) + **Top role:** {member.top_role} + **Warns:** {await GetWarnings(member.id, ctx.guild.id)} + """ + embed = Embed(title=f"Who is {member} ?", description=descr) + + embed.set_thumbnail(url=member.display_avatar) + + embed.set_footer( + text=f"Hammer | Command executed by {ctx.author}", + icon_url=hammericon, + ) + await ctx.respond(embed=embed) + except Exception as e: + await ctx.respond(e) + + +@bot.slash_command( + guild_only=True, + name="ban", + description="Keeps out a user permanently, forbidding its entry", +) +@discord.default_permissions( + ban_members=True, ) +async def ban(ctx, member: discord.Member, *, reason=None): + + if member == ctx.author: + await ctx.respond("You cannot ban yourself", ephemeral=True) + return + if reason == None: + reason = "bad behaviour 💥" + message = f"You have been banned from {ctx.guild.name} for {reason}" + + descr = f"The user {member} has been banned for {reason}" + embed = Embed(title=f"{member} has been banned! :hammer_pick:", + description=descr) + embed.set_image(url="https://i.imgflip.com/19zat3.jpg") + embed.set_footer( + text=f"Hammer | Command executed by {ctx.author}", + icon_url=hammericon, + ) + if not debug: + try: + await member.ban(reason=reason) + except: + ctx.respond( + embed=ErrorEmbed( + f"Could not ban the user {member}\n This may be caused because I do not have the permission to do that or the user has a higher role than me." + ), + ephemeral=True, + ) + return + + embed.set_thumbnail(url=member.display_avatar) + await ctx.respond(embed=embed) + await SendMessageTo(ctx, member, message) + + +@bot.slash_command(guild_only=True, + name="kick", + description="Kicks out a member from the server") +@discord.default_permissions( + kick_members=True, ) +async def kick(ctx, member: discord.Member, *, reason=None): + + if member == ctx.author: + await ctx.respond("You cannot kick yourself", ephemeral=True) + return + if reason == None: + reason = "bad behaviour 💥" + message = f"You have been kicked from {ctx.guild.name} for {reason}" + if not debug: + try: + await member.kick(reason=reason) + except: + ctx.respond( + embed=ErrorEmbed( + f"Could not kick the user {member}\n This may be caused because I do not have the permission to do that or the user has a higher role than me." + ), + ephemeral=True, + ) + return + descr = f"The user {member} has been kicked for {reason}" + embed = Embed(title=f"{member} has been kicked! :hammer_pick:", + description=descr) + embed.set_footer( + text=f"Hammer | Command executed by {ctx.author}", + icon_url=hammericon, + ) + embed.set_thumbnail(url=member.display_avatar) + # # embed.image = member.image + await ctx.respond(embed=embed) + await SendMessageTo(ctx, member, message) + + +@bot.slash_command( + guild_only=True, + name="warn", + description="Sets a warning for a user, at 3 warns/strikes they get kicked", +) +@discord.default_permissions( + administrator=True, ) +async def warn(ctx, member: discord.Member, reason=None): + + if member == ctx.author: + await ctx.respond("You cannot warn yourself :(", ephemeral=True) + return + if reason == None: + reason = "bad behaviour 💥" + message = f"You have been warned for {reason}" + + descr = f"The user {member} has been warned for {reason}" + embed = Embed(title=f"{member} has been warned! :hammer_pick:", + description=descr) + embed.set_footer( + text=f"Hammer | Command executed by {ctx.author}", + icon_url=hammericon, + ) + embed.set_thumbnail(url=member.display_avatar) + warn = await AddWarning(member.id, ctx.guild.id, reason) + s = "s" if warn > 1 else "" + embed.add_field( + name="Warn count", + value=f"The user {member} has {warn} warn{s}. Be careful.", + inline=True, + ) + await ctx.respond(embed=embed) + + await SendMessageTo(ctx, member, message) + + +@bot.slash_command( + guild_only=True, + name="seewarns", + description="Displays the warn history of a user in the guild", +) +@discord.default_permissions( + administrator=True, ) +async def seewarns(ctx, member: discord.Member): + allwarns = await getAllWarns(member.id, ctx.guild.id) + if(len(allwarns) == 0): allwarns = ['User had no warns at the moment'] + message = '\n'.join(allwarns) + + c=0 + data=[] + for warn in await GetWarnings(member.id, ctx.guild.id, fullData=True): + _,_,_,_,timestamp =warn + c=c+1 + data.append({'t':str(datetime.datetime.fromtimestamp(int(str(timestamp)[:str(timestamp).find(".")]))),'y':c}) + + qc = QuickChart() + qc.width = 500 + qc.height = 300 + qc.device_pixel_ratio = 2.0 + qc.config = { + "type": "line", + "data": { + "datasets": [ + { + "fill": False, + "label": [f"Warns of {member}"], + "lineTension": 0, + "backgroundColor": "#7289DA", + "borderColor": "#7289DA", + "data": data + } + ] + }, + "options": { + "scales": { + "xAxes": [{ + "type": "time", + "time": { + "parser": "YYYY-MM-DD HH:mm:ss", + "displayFormats": { + "day": "DD/MM/YYYY" + } + } + }] + } + } +} + + uurl = qc.get_url() + + embed = Embed(title=f"**Historic of {member}**", description=message) + embed.set_image(url=uurl) + embed.set_footer( + text=f"Hammer | Command executed by {ctx.author}", + icon_url=hammericon, + ) + return await ctx.respond(embed=embed) + + +@bot.slash_command(guild_only=True, + name="unwarn", + description="Removes a strike from a user") +@discord.default_permissions( + kick_members=True, +) +async def unwarn(ctx, member: discord.Member, id: int=None , *, reason=None): + if(await GetWarnings(member.id, ctx.guild.id) == 0): + return await ctx.respond("This user does not have any warn!") + if id == None: + message = f"""To select a warn to remove, use argument id and specify its value.""" + + embed = Embed(title=f"ERROR! Need to select a warn :hammer_pick:", description=message) + allwarns = await getAllWarns(member.id, ctx.guild.id) + embed.add_field( + name=f"**Historic of {member.name}**:", + value="\n".join(allwarns), + ) + return await ctx.respond(embed=embed) + if reason == None: + reason = "good behaviour ✅" + message = f"You have been unwarned for {reason}" + + descr = f"The user {member} has been unwarned for {reason}" + embed = Embed(title=f"{member} has been unwarned! :hammer_pick:", + description=descr) + embed.set_footer( + text=f"Hammer | Command executed by {ctx.author}", + icon_url=hammericon, + ) + embed.set_thumbnail(url=member.display_avatar) + warn = await Removewarn(member.id, ctx.guild.id, id) + s = "s" if warn > 1 else "" + congrats = "Yey! :tada:" if warn == 0 else "" + embed.add_field( + name="Warn count", + value=f"The user {member} has now {warn} warn{s}. {congrats}", + inline=True, + ) + await ctx.respond(embed=embed) + await SendMessageTo(ctx, member, message) + + +@bot.slash_command(guild_only=True, + name="clearwarns", + description="Removes all strikes from a user") +@discord.default_permissions( + kick_members=True, ) +async def clearwarns(ctx, member: discord.Member, *, reason=None): + + if reason == None: + reason = "good behaviour ✅" + message = f"Your warns have been cleared for {reason}" + + descr = f"The user {member} has 0 warns for {reason}" + embed = Embed( + title=f"The warns of {member} have been removed! :hammer_pick:", + description=descr, + ) + embed.set_footer( + text=f"Hammer | Command executed by {ctx.author}", + icon_url=hammericon, + ) + embed.set_thumbnail(url=member.display_avatar) + warn = await Clearwarns(member.id, ctx.guild.id) + embed.add_field( + name="Warn count", + value=f"The user {member} has now {warn} warns. Yey! :tada:", + inline=True, + ) + await ctx.respond(embed=embed, ephemeral=False) + await SendMessageTo(ctx, member, message) + +@bot.slash_command(guild_only=True, + name="automod", + description="Customizes in this guild Hammer's automod") +@discord.default_permissions( + administrator=True, +) +@option( + "action", + description="Select add/remove", + autocomplete=discord.utils.basic_autocomplete(["add", "remove"]), +) +async def automod(ctx, action: str, word: str): + if(action == "add"): + response = await AddAllowedWord(ctx.guild.id, ctx.author.id, word) + elif (action == "remove"): + response = await AddDeniedWord(ctx.guild.id, ctx.author.id, word) + else: + return await ctx.respond(embed=ErrorEmbed("Wrong syntax, please use /automod add/remove [word]"), ephemeral=True) + if(response): + return await ctx.respond("Word ||"+str(word)+f"|| successfully {action}ed to the database. :tools:", ephemeral=True) + else: + return await ctx.respond(embed=ErrorEmbed( + f"Could not save the word ||{word}|| to the database. Please contact the administrator or bot developer for further information. "), ephemeral=True) + +@bot.slash_command(guild_only=True, guild_ids=[int(SECURITY_GUILD)]) +async def evaluate(ctx, code): + + if str(ctx.author.id) == str(OWNER): + try: + # await respondNotifOwner( + # f"User {ctx.author} used command evaluate | id {ctx.author.id}" + # ) + print("RECIEVED:", code) + # t = ctx.author.id,"used the command eval at", datetime.now() + # print(t) + args = { + "discord": discord, + "sys": sys, + "os": os, + "sqlite3": sqlite3, + "imp": __import__, + "ctx": ctx, + "bot": bot, + } + try: + exec(f"async def func(): return {code}", args) + a = time() + response = await eval("func()", args) + await ctx.respond( + f"```py\n{response}``````{type(response).__name__}``` `| {(time() - a) / 1000} ms`", + ephemeral=True, + ) + except Exception as e: + await ctx.respond( + f"Error occurred:```\n{type(e).__name__}: {str(e)}```", + ephemeral=True, + ) + except Exception as e: + await ctx.respond(e, ephemeral=True) + else: + await ctx.respond("you're not allowed to do that") + + +def restart_bot(): + os.execv(sys.executable, ["python"] + sys.argv) + + +@bot.slash_command(guild_only=True, guild_ids=[int(SECURITY_GUILD)]) +async def restart(ctx): + + if str(ctx.author.id) == str(OWNER): + try: + # await respondNotifOwner( + # f"User {ctx.author} used command evaluate | id {ctx.author.id}" + # ) + print("===== RESTART asked by", ctx.author, "=====") + # t = ctx.author.id,"used the command eval at", datetime.now() + # print(t) + print("CLOSING SESSION") + + await bot.close() + print("FETCHING NEW CHANGES IN GITHUB") + import subprocess + + try: + if not debug: + # Remove any changes done + res = subprocess.check_output(["git", "reset", "--hard"]) + for line in res.splitlines(): + print(line) + # Update files + res = subprocess.check_output(["git", "pull"]) + for line in res.splitlines(): + print(line) + except Exception as e: + await ctx.respond(e, ephemeral=True) + print("===== STARTING BOT AGAIN =====") + try: + restart_bot() + except Exception as e: + print(e) + await ctx.respond("Bot restarted successfully!", ephemeral=True) + except Exception as e: + await ctx.respond(e, ephemeral=True) + else: + await ctx.respond("you're not allowed to do that") + + +@bot.slash_command( + guild_only=True, + name="setdelay", + description= + "Updates the message delay in a channel with a set of custom time interval", +) +@discord.default_permissions( + manage_messages=True, ) +async def setdelay(ctx, seconds: float, reason: str = ""): + + m = "modified" if seconds > 0.0 else "removed" + embed = Embed( + title=f"Delay {m} on #{ctx.channel} :hammer_pick:", + description= + f"This channel now has a delay of **{seconds}** seconds for {reason}" + if reason != None and reason != "" else + f"This channel now has a delay of **{seconds}** seconds", + ) + embed.set_footer( + text=f"Hammer | Command executed by {ctx.author}", + icon_url=hammericon, + ) + + await ctx.channel.edit(slowmode_delay=seconds) + await ctx.respond(embed=embed) + + +# description="Mutes the specified user." +@bot.slash_command( + guild_only=True, + name="mute", + description="Removes the hability to talk or join voice channels to a user", +) +@discord.default_permissions( + manage_messages=True, ) +async def mute(ctx, member: discord.Member, *, reason=None): + + guild = ctx.guild + mutedRole = discord.utils.get(guild.roles, name="Muted") + + if not mutedRole: + mutedRole = await guild.create_role(name="Muted") + + for channel in guild.channels: + await channel.set_permissions( + mutedRole, + speak=False, + respond_messages=False, + read_message_history=True, + read_messages=False, + ) + + if reason == None: + reason = "bad behaviour 💥" + + embed = discord.Embed( + title=f"User Muted: {member}", + description=f"User {member.mention} has been muted for {reason}", + colour=discord.Colour.red(), + ) + await ctx.respond(embed=embed) + await member.add_roles(mutedRole, reason=reason) + + SendMessageTo( + ctx, + member, + f":no_entry: You have been muted from: {ctx.guild.name} for {reason}", + ) + + +# description="Unmutes a specified user." +@bot.slash_command( + guild_only=True, + name="unmute", + description= + "Restores the hability to talk or join voice channels to a user", +) +@discord.default_permissions( + manage_messages=True, ) +async def unmute(ctx, member: discord.Member, *, reason=None): + + mutedRole = discord.utils.get(ctx.guild.roles, name="Muted") + if reason == None: + reason = " " + else: + reason = "for " + reason + await member.remove_roles(mutedRole) + SendMessageTo( + ctx, member, + f":tada: You have been unmuted from: {ctx.guild.name} {reason}") + embed = discord.Embed( + title=f"User Unmuted: {member}", + description=f"User {member.mention} has been unmuted {reason}", + colour=discord.Colour.light_gray(), + ) + await ctx.respond(embed=embed) + + +@discord.default_permissions(manage_channels=True) +@bot.slash_command( + guild_only=True, + name="lock", + description="Blocks a channel from being used as a chat.", +) +async def lock(ctx, channel: discord.TextChannel = None, reason=None): + + channel = channel or ctx.channel + reason = "for " + reason if reason else "" + overwrite = channel.overwrites_for(ctx.guild.default_role) + overwrite.send_messages = False + await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite) + embed = Embed( + title=f"The channel #{ctx.channel} has been locked! :hammer_pick:", + description=f"This channel is now locked {reason}", + ) + embed.set_footer( + text=f"Hammer | Command executed by {ctx.author}", + icon_url=hammericon, + ) + await ctx.respond(embed=embed) + + +@discord.default_permissions(manage_channels=True) +@bot.slash_command( + guild_only=True, + name="unlock", + description= + "Removes the blocking in a channel from not being used as a chat.", +) +async def unlock(ctx, channel: discord.TextChannel = None, reason=None): + + channel = channel or ctx.channel + reason = "for " + reason if reason else "" + overwrite = channel.overwrites_for(ctx.guild.default_role) + overwrite.send_messages = True + await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite) + embed = Embed( + title=f"The channel #{ctx.channel} has been unlocked! :hammer_pick:", + description=f"This channel is now unlocked {reason}", + ) + embed.set_footer( + text=f"Hammer | Command executed by {ctx.author}", + icon_url=hammericon, + ) + await ctx.respond(embed=embed) + + +@bot.slash_command( + name="suggest", + description="Sends a suggestion to the developer of Hammer.", +) +async def suggest(ctx, suggestion: str): + + embed = Embed( + title=f"The user {ctx.author} has posted a suggestion! :hammer_pick:", + description=f"{suggestion}", + ) + embed.set_footer( + text=f"Hammer | Command executed by {ctx.author}", + icon_url=hammericon, + ) + suggestionChannel = bot.get_channel(int(DEV_SUGGESTIONS_CHANNEL)) + await suggestionChannel.send(embed=embed) + await ctx.respond( + "[200 OK] ✅ Your suggestion has been successfully recieved! \n Join our support server to see how does it progress! (in /help you'll find the link)", + ephemeral=True, + ) + + +@bot.slash_command( + name="invite", + description="Returns the bot's invitation link.", +) +async def invite(ctx): + embed = Embed( + title=f"Invite Hammer Bot to your server! :hammer_pick:", + description= + f"[**🔗 Hammer Invite Link**](https://discordapp.com/api/oauth2/authorize?client_id=591633652493058068&permissions=8&scope=bot)", + ) + embed.set_footer( + text=f"Hammer | Command executed by {ctx.author}", + icon_url=hammericon, + ) + await ctx.respond(embed=embed) + + +modules = ["automod"] + + +@discord.default_permissions(administrator=True) +@bot.slash_command(name="settings", + description="Modifies some Hammer config values", + guild_only=True) +@option( + "module", + description="Pick a module to switch!", + autocomplete=discord.utils.basic_autocomplete(modules), +) +@option( + "value", + description="Select on/off", + autocomplete=discord.utils.basic_autocomplete(["on", "off"]), +) +async def settings(ctx, module: str = None, value: str = None): + if module != None and value != None: + if module in modules and value == "on" or value == "off": + value = 1 if value == "on" else 0 + await SaveSetting(ctx.guild.id, module, value) + action = "enabled" if value else "disabled" + await ctx.respond(f"Module {module} {action} successfully!", + ephemeral=True) + return + else: + await ctx.respond("Use: ``/settings module on/off``", + ephemeral=True) + return + embed = Embed( + title=f"Hammer Bot Settings :hammer_pick:", + description=f"Here you can enable or disable some modules", + ) + print("getting settings from discord.Guild.id", ctx.guild.id) + automodStatus = await GetSettings(ctx.guild.id) + automodStatustr = "**✅ ON**" if automodStatus else "**❌ OFF**" + recommendedactivityAutomod = ( + f"Disable it by doing: ``{COMMAND_PREFIX}settings automod off``" + if automodStatus else + f"Enable it by doing ``{COMMAND_PREFIX}settings automod on``") + embed.add_field( + name="AutoMod Services :robot:", + value= + f"Actual status: {automodStatustr}\n {recommendedactivityAutomod}", + inline=True, + ) + embed.set_footer( + text=f"Hammer | Command executed by {ctx.author}", + icon_url=hammericon, + ) + await ctx.respond(embed=embed) + + +bot.run(TOKEN) From f8f4ddcf2359d127198dbe8473652ef4f18e1949 Mon Sep 17 00:00:00 2001 From: EncryptEx Date: Fri, 11 Nov 2022 11:55:48 +0100 Subject: [PATCH 11/16] added a clear message to the response --- bot.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/bot.py b/bot.py index dd98e95..a06f823 100644 --- a/bot.py +++ b/bot.py @@ -799,18 +799,19 @@ async def clearwarns(ctx, member: discord.Member, *, reason=None): ) @option( "action", - description="Select add/remove", + description="Select add/remove word from swear list", autocomplete=discord.utils.basic_autocomplete(["add", "remove"]), ) async def automod(ctx, action: str, word: str): - if(action == "add"): + if(action == "remove"): response = await AddAllowedWord(ctx.guild.id, ctx.author.id, word) - elif (action == "remove"): + elif (action == "add"): response = await AddDeniedWord(ctx.guild.id, ctx.author.id, word) else: return await ctx.respond(embed=ErrorEmbed("Wrong syntax, please use /automod add/remove [word]"), ephemeral=True) if(response): - return await ctx.respond("Word ||"+str(word)+f"|| successfully {action}ed to the database. :tools:", ephemeral=True) + prep = "to" if action == "add" else "from" + return await ctx.respond("Word ||"+str(word)+f"|| successfully {action}ed {prep} the swear word list. :tools:", ephemeral=True) else: return await ctx.respond(embed=ErrorEmbed( f"Could not save the word ||{word}|| to the database. Please contact the administrator or bot developer for further information. "), ephemeral=True) From 742b87703810a31611bd3d2af00dd1a2e3364b68 Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Fri, 11 Nov 2022 11:21:46 +0000 Subject: [PATCH 12/16] Restyled by autopep8 --- bot.py | 161 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 80 insertions(+), 81 deletions(-) diff --git a/bot.py b/bot.py index a06f823..062c619 100644 --- a/bot.py +++ b/bot.py @@ -92,8 +92,7 @@ async def help(ctx): embed.add_field( name="AutoMod Services :robot:", - value= - f"""Swear Word Detector and wuto warn. + value=f"""Swear Word Detector and wuto warn. Using a +880 swear word database Customize it with: @@ -125,8 +124,7 @@ async def help(ctx): embed.add_field( name="""Useful Links: :link:""", - value= - f"""[:classical_building: Hammer Bot Support](https://discord.gg/fMSyQA6) + value=f"""[:classical_building: Hammer Bot Support](https://discord.gg/fMSyQA6) [:link: Hammer Invite Link](https://discordapp.com/api/oauth2/authorize?client_id=591633652493058068&permissions=8&scope=bot) [:newspaper: Vote Hammer](https://top.gg/bot/591633652493058068) """, @@ -159,8 +157,8 @@ async def respondNotifOwner(text): await bot.get_channel(int(SECURITY_CHANNEL)).respond(text) -async def GetWarnings(userid: int, guildid:int, fullData: bool=False): - cur.execute("SELECT * FROM warns WHERE userid=? AND guildid=?", (userid,guildid,)) +async def GetWarnings(userid: int, guildid: int, fullData: bool = False): + cur.execute("SELECT * FROM warns WHERE userid=? AND guildid=?", (userid, guildid,)) rows = cur.fetchall() if not fullData: return len(rows) @@ -170,7 +168,7 @@ async def GetWarnings(userid: int, guildid:int, fullData: bool=False): # Function to add a warning and save it at the database async def AddWarning( - userid: int, guildid:int, reason + userid: int, guildid: int, reason ): warncount = await GetWarnings(userid, guildid) cur.execute( @@ -182,10 +180,11 @@ async def AddWarning( conn.commit() return warncount + 1 + async def Removewarn( - userid: int, guildId:int, relativeWarnId:int + userid: int, guildId: int, relativeWarnId: int ): - c=0 + c = 0 for warn in await GetWarnings(userid, guildId, fullData=True): warnRealId, _, _, SubReason, _ = warn if c == relativeWarnId: @@ -205,11 +204,13 @@ async def Clearwarns(userid: int, guildId: int): (userid, guildId)) conn.commit() return + + async def getAllWarns( - userid: int, guildid:int + userid: int, guildid: int ): allwarns = [] - c=0 + c = 0 for warn in await GetWarnings(userid, guildid, fullData=True): _, _, _, SubReason, timestamp = warn dt = timestamp @@ -218,34 +219,34 @@ async def getAllWarns( else: emojis = str(c) - ddt=int(str(dt)[:str(dt).find(".")]) + ddt = int(str(dt)[:str(dt).find(".")]) allwarns.append(f"- **ID: {emojis}** Reason: ``{SubReason}`` ") - - c=c+1 + + c = c + 1 return allwarns - + + async def GetAutomodCustomWords(guildid: int, mode: str): wtype = 1 if mode == "allow" else 0 cur.execute("SELECT word FROM customWords WHERE guildid = ? AND type = ?", (guildid, wtype)) words = cur.fetchall() - a=[] + a = [] if len(words) > 0: for word in words: a.append(str(word[0])) return a else: - return [] # default is emptys + return [] # default is emptys async def AddAllowedWord( - guildid: int, userid:int, word:str + guildid: int, userid: int, word: str ): # check if user is in blacklist # if(word in await GetAutomodCustomWords(guildid, "deny")): - - try: + try: cur.execute( """DELETE FROM customWords WHERE guildid=? AND word=? AND type=0 """, @@ -259,14 +260,15 @@ async def AddAllowedWord( (guildid, userid, word), ) conn.commit() - except: + except: return False return True + async def AddDeniedWord( - guildid: int, userid:int, word:str + guildid: int, userid: int, word: str ): - try: + try: cur.execute( """DELETE FROM customWords WHERE guildid=? AND word=? AND type=1 """, @@ -280,10 +282,11 @@ async def AddDeniedWord( (guildid, userid, word), ) conn.commit() - except: + except: return False return True + async def GetSettings(guildid: int): cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", (guildid, )) @@ -339,8 +342,7 @@ def ErrorEmbed(error): embed = Embed(title=f":no_entry_sign: Error!", description=error) embed.set_thumbnail( - url= - "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ficonsplace.com%2Fwp-content%2Fuploads%2F_icons%2Fff0000%2F256%2Fpng%2Ferror-icon-14-256.png&f=1&nofb=1" + url="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ficonsplace.com%2Fwp-content%2Fuploads%2F_icons%2Fff0000%2F256%2Fpng%2Ferror-icon-14-256.png&f=1&nofb=1" ) embed.set_footer( @@ -423,8 +425,7 @@ async def on_message(message): s = "s" if warn > 1 else "" embed.add_field( name="Warn count", - value= - f"The user {member} has {warn} warn{s}. Be careful. Run /seewarns @user to check its warnhistory", + value=f"The user {member} has {warn} warn{s}. Be careful. Run /seewarns @user to check its warnhistory", inline=True, ) bannedmessage = ( @@ -664,48 +665,50 @@ async def warn(ctx, member: discord.Member, reason=None): administrator=True, ) async def seewarns(ctx, member: discord.Member): allwarns = await getAllWarns(member.id, ctx.guild.id) - if(len(allwarns) == 0): allwarns = ['User had no warns at the moment'] + if (len(allwarns) == 0): + allwarns = ['User had no warns at the moment'] message = '\n'.join(allwarns) - - c=0 - data=[] + + c = 0 + data = [] for warn in await GetWarnings(member.id, ctx.guild.id, fullData=True): - _,_,_,_,timestamp =warn - c=c+1 - data.append({'t':str(datetime.datetime.fromtimestamp(int(str(timestamp)[:str(timestamp).find(".")]))),'y':c}) + _, _, _, _, timestamp = warn + c = c + 1 + data.append({'t': str(datetime.datetime.fromtimestamp( + int(str(timestamp)[:str(timestamp).find(".")]))), 'y': c}) qc = QuickChart() qc.width = 500 qc.height = 300 qc.device_pixel_ratio = 2.0 qc.config = { - "type": "line", - "data": { - "datasets": [ - { - "fill": False, - "label": [f"Warns of {member}"], - "lineTension": 0, - "backgroundColor": "#7289DA", - "borderColor": "#7289DA", - "data": data - } - ] - }, - "options": { - "scales": { - "xAxes": [{ - "type": "time", - "time": { - "parser": "YYYY-MM-DD HH:mm:ss", - "displayFormats": { - "day": "DD/MM/YYYY" - } + "type": "line", + "data": { + "datasets": [ + { + "fill": False, + "label": [f"Warns of {member}"], + "lineTension": 0, + "backgroundColor": "#7289DA", + "borderColor": "#7289DA", + "data": data + } + ] + }, + "options": { + "scales": { + "xAxes": [{ + "type": "time", + "time": { + "parser": "YYYY-MM-DD HH:mm:ss", + "displayFormats": { + "day": "DD/MM/YYYY" + } + } + }] + } } - }] } - } -} uurl = qc.get_url() @@ -724,12 +727,12 @@ async def seewarns(ctx, member: discord.Member): @discord.default_permissions( kick_members=True, ) -async def unwarn(ctx, member: discord.Member, id: int=None , *, reason=None): - if(await GetWarnings(member.id, ctx.guild.id) == 0): +async def unwarn(ctx, member: discord.Member, id: int = None, *, reason=None): + if (await GetWarnings(member.id, ctx.guild.id) == 0): return await ctx.respond("This user does not have any warn!") if id == None: message = f"""To select a warn to remove, use argument id and specify its value.""" - + embed = Embed(title=f"ERROR! Need to select a warn :hammer_pick:", description=message) allwarns = await getAllWarns(member.id, ctx.guild.id) embed.add_field( @@ -791,6 +794,7 @@ async def clearwarns(ctx, member: discord.Member, *, reason=None): await ctx.respond(embed=embed, ephemeral=False) await SendMessageTo(ctx, member, message) + @bot.slash_command(guild_only=True, name="automod", description="Customizes in this guild Hammer's automod") @@ -803,18 +807,19 @@ async def clearwarns(ctx, member: discord.Member, *, reason=None): autocomplete=discord.utils.basic_autocomplete(["add", "remove"]), ) async def automod(ctx, action: str, word: str): - if(action == "remove"): + if (action == "remove"): response = await AddAllowedWord(ctx.guild.id, ctx.author.id, word) elif (action == "add"): response = await AddDeniedWord(ctx.guild.id, ctx.author.id, word) - else: + else: return await ctx.respond(embed=ErrorEmbed("Wrong syntax, please use /automod add/remove [word]"), ephemeral=True) - if(response): + if (response): prep = "to" if action == "add" else "from" - return await ctx.respond("Word ||"+str(word)+f"|| successfully {action}ed {prep} the swear word list. :tools:", ephemeral=True) - else: + return await ctx.respond("Word ||" + str(word) + f"|| successfully {action}ed {prep} the swear word list. :tools:", ephemeral=True) + else: return await ctx.respond(embed=ErrorEmbed( - f"Could not save the word ||{word}|| to the database. Please contact the administrator or bot developer for further information. "), ephemeral=True) + f"Could not save the word ||{word}|| to the database. Please contact the administrator or bot developer for further information. "), ephemeral=True) + @bot.slash_command(guild_only=True, guild_ids=[int(SECURITY_GUILD)]) async def evaluate(ctx, code): @@ -903,8 +908,7 @@ async def restart(ctx): @bot.slash_command( guild_only=True, name="setdelay", - description= - "Updates the message delay in a channel with a set of custom time interval", + description="Updates the message delay in a channel with a set of custom time interval", ) @discord.default_permissions( manage_messages=True, ) @@ -913,8 +917,7 @@ async def setdelay(ctx, seconds: float, reason: str = ""): m = "modified" if seconds > 0.0 else "removed" embed = Embed( title=f"Delay {m} on #{ctx.channel} :hammer_pick:", - description= - f"This channel now has a delay of **{seconds}** seconds for {reason}" + description=f"This channel now has a delay of **{seconds}** seconds for {reason}" if reason != None and reason != "" else f"This channel now has a delay of **{seconds}** seconds", ) @@ -974,8 +977,7 @@ async def mute(ctx, member: discord.Member, *, reason=None): @bot.slash_command( guild_only=True, name="unmute", - description= - "Restores the hability to talk or join voice channels to a user", + description="Restores the hability to talk or join voice channels to a user", ) @discord.default_permissions( manage_messages=True, ) @@ -1026,8 +1028,7 @@ async def lock(ctx, channel: discord.TextChannel = None, reason=None): @bot.slash_command( guild_only=True, name="unlock", - description= - "Removes the blocking in a channel from not being used as a chat.", + description="Removes the blocking in a channel from not being used as a chat.", ) async def unlock(ctx, channel: discord.TextChannel = None, reason=None): @@ -1076,8 +1077,7 @@ async def suggest(ctx, suggestion: str): async def invite(ctx): embed = Embed( title=f"Invite Hammer Bot to your server! :hammer_pick:", - description= - f"[**🔗 Hammer Invite Link**](https://discordapp.com/api/oauth2/authorize?client_id=591633652493058068&permissions=8&scope=bot)", + description=f"[**🔗 Hammer Invite Link**](https://discordapp.com/api/oauth2/authorize?client_id=591633652493058068&permissions=8&scope=bot)", ) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", @@ -1129,8 +1129,7 @@ async def settings(ctx, module: str = None, value: str = None): f"Enable it by doing ``{COMMAND_PREFIX}settings automod on``") embed.add_field( name="AutoMod Services :robot:", - value= - f"Actual status: {automodStatustr}\n {recommendedactivityAutomod}", + value=f"Actual status: {automodStatustr}\n {recommendedactivityAutomod}", inline=True, ) embed.set_footer( From ee087fae9dc43ce783b4d48192e27a3a409e3961 Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Fri, 11 Nov 2022 11:21:48 +0000 Subject: [PATCH 13/16] Restyled by black --- bot.py | 276 ++++++++++++++++++++++++++++++++------------------------- 1 file changed, 155 insertions(+), 121 deletions(-) diff --git a/bot.py b/bot.py index 062c619..f44b76f 100644 --- a/bot.py +++ b/bot.py @@ -23,28 +23,35 @@ from get_enviroment import SECURITY_GUILD from get_enviroment import SWEAR_WORDS_LIST from get_enviroment import TOKEN + # database import & connection conn = sqlite3.connect("maindatabase1.db") cur = conn.cursor() -cur.execute("""CREATE TABLE IF NOT EXISTS `warns` ( +cur.execute( + """CREATE TABLE IF NOT EXISTS `warns` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `userid` INT(100), `guildid` INT, `reason` TEXT, `timestamp` INT); - """) -cur.execute("""CREATE TABLE IF NOT EXISTS `customWords` ( + """ +) +cur.execute( + """CREATE TABLE IF NOT EXISTS `customWords` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `guildid` INT, `uploaderId`INT, `word` TEXT, `type` INT); - """) -cur.execute("""CREATE TABLE IF NOT EXISTS `settings` ( + """ +) +cur.execute( + """CREATE TABLE IF NOT EXISTS `settings` ( `guildid` INT(100) UNIQUE, `automod` INT); - """) + """ +) hammericon = "https://images-ext-2.discordapp.net/external/OKc8xu6AILGNFY3nSTt7wGbg-Mi1iQZonoLTFg85o-E/%3Fsize%3D1024/https/cdn.discordapp.com/avatars/591633652493058068/e6011129c5169b29ed05a6dc873175cb.png?width=670&height=670" @@ -62,9 +69,9 @@ # -@bot.slash_command(name="help", - description="Displays all the available commands for Hammer" - ) +@bot.slash_command( + name="help", description="Displays all the available commands for Hammer" +) async def help(ctx): # Define each page @@ -73,9 +80,9 @@ async def help(ctx): **Hammer's commands:** """ - embed = Embed(title="Hammer Bot Help", - description=descr, - colour=discord.Colour.lighter_grey()) + embed = Embed( + title="Hammer Bot Help", description=descr, colour=discord.Colour.lighter_grey() + ) embed.add_field( name="Moderation Commands :tools:", @@ -141,8 +148,9 @@ async def help(ctx): inline=True, ) - embed.set_footer(text=f"Hammer | Command executed by {ctx.author}", - icon_url=hammericon) + embed.set_footer( + text=f"Hammer | Command executed by {ctx.author}", icon_url=hammericon + ) await ctx.respond(embed=embed) @@ -158,7 +166,13 @@ async def respondNotifOwner(text): async def GetWarnings(userid: int, guildid: int, fullData: bool = False): - cur.execute("SELECT * FROM warns WHERE userid=? AND guildid=?", (userid, guildid,)) + cur.execute( + "SELECT * FROM warns WHERE userid=? AND guildid=?", + ( + userid, + guildid, + ), + ) rows = cur.fetchall() if not fullData: return len(rows) @@ -167,9 +181,7 @@ async def GetWarnings(userid: int, guildid: int, fullData: bool = False): # Function to add a warning and save it at the database -async def AddWarning( - userid: int, guildid: int, reason -): +async def AddWarning(userid: int, guildid: int, reason): warncount = await GetWarnings(userid, guildid) cur.execute( """INSERT OR IGNORE INTO warns (userid, guildid, reason, timestamp) @@ -181,9 +193,7 @@ async def AddWarning( return warncount + 1 -async def Removewarn( - userid: int, guildId: int, relativeWarnId: int -): +async def Removewarn(userid: int, guildId: int, relativeWarnId: int): c = 0 for warn in await GetWarnings(userid, guildId, fullData=True): warnRealId, _, _, SubReason, _ = warn @@ -200,15 +210,12 @@ async def Removewarn( async def Clearwarns(userid: int, guildId: int): # delete all rows - cur.execute("DELETE FROM warns WHERE userid=? AND guildid=?", - (userid, guildId)) + cur.execute("DELETE FROM warns WHERE userid=? AND guildid=?", (userid, guildId)) conn.commit() return -async def getAllWarns( - userid: int, guildid: int -): +async def getAllWarns(userid: int, guildid: int): allwarns = [] c = 0 for warn in await GetWarnings(userid, guildid, fullData=True): @@ -219,7 +226,7 @@ async def getAllWarns( else: emojis = str(c) - ddt = int(str(dt)[:str(dt).find(".")]) + ddt = int(str(dt)[: str(dt).find(".")]) allwarns.append(f"- **ID: {emojis}** Reason: ``{SubReason}`` ") c = c + 1 @@ -228,8 +235,9 @@ async def getAllWarns( async def GetAutomodCustomWords(guildid: int, mode: str): wtype = 1 if mode == "allow" else 0 - cur.execute("SELECT word FROM customWords WHERE guildid = ? AND type = ?", - (guildid, wtype)) + cur.execute( + "SELECT word FROM customWords WHERE guildid = ? AND type = ?", (guildid, wtype) + ) words = cur.fetchall() a = [] if len(words) > 0: @@ -240,9 +248,7 @@ async def GetAutomodCustomWords(guildid: int, mode: str): return [] # default is emptys -async def AddAllowedWord( - guildid: int, userid: int, word: str -): +async def AddAllowedWord(guildid: int, userid: int, word: str): # check if user is in blacklist # if(word in await GetAutomodCustomWords(guildid, "deny")): @@ -265,9 +271,7 @@ async def AddAllowedWord( return True -async def AddDeniedWord( - guildid: int, userid: int, word: str -): +async def AddDeniedWord(guildid: int, userid: int, word: str): try: cur.execute( """DELETE FROM customWords WHERE guildid=? AND word=? AND type=1 @@ -288,8 +292,7 @@ async def AddDeniedWord( async def GetSettings(guildid: int): - cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", - (guildid, )) + cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", (guildid,)) rows = cur.fetchall() if len(rows) > 0: return rows[0][1] @@ -298,13 +301,10 @@ async def GetSettings(guildid: int): async def SaveSetting(guildid: int, module: str, value: int): - cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", - (guildid, )) + cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", (guildid,)) rows = cur.fetchall() # print(rows) - if len( - rows - ) > 0: # cur.execute('INSERT INTO foo (a,b) values (?,?)', (strA, strB)) + if len(rows) > 0: # cur.execute('INSERT INTO foo (a,b) values (?,?)', (strA, strB)) query = f"""UPDATE settings SET automod = {value} WHERE guildid={guildid} """ @@ -413,15 +413,17 @@ async def on_message(message): descr = ( f"The user {member} has been warned because said a banned swear word" ) - embed = Embed(title=f"{member} has been warned! :hammer_pick:", - description=descr) + embed = Embed( + title=f"{member} has been warned! :hammer_pick:", description=descr + ) embed.set_footer( text=f"Hammer | Automod service", icon_url=hammericon, ) embed.set_thumbnail(url=member.display_avatar) - warn = await AddWarning(member.id, message.guild.id, - "Said a banned swear word") + warn = await AddWarning( + member.id, message.guild.id, "Said a banned swear word" + ) s = "s" if warn > 1 else "" embed.add_field( name="Warn count", @@ -429,9 +431,12 @@ async def on_message(message): inline=True, ) bannedmessage = ( - message.content[:message.content.find(word)] + "~~" + word + - "~~" + - message.content[message.content.find(word) + len(word):]) + message.content[: message.content.find(word)] + + "~~" + + word + + "~~" + + message.content[message.content.find(word) + len(word) :] + ) embed.add_field( name="Message Removed:", value=f"The removed message was \n||{bannedmessage}||", @@ -452,15 +457,17 @@ async def on_message(message): embed = ErrorEmbed( await message.channel.send( f"Could not deliver the message to the user {member}\n This may be caused because the user is a bot, has blocked me or has the DMs turned off. \n\n**But the user is warned** and I have saved it into my beautiful unforgettable database" - ), ) + ), + ) # if(str(message.content).startswith(COMMAND_PREFIX)): # print("command executed", message.content) @bot.event async def on_ready(): - await bot.change_presence(activity=discord.Activity( - type=discord.ActivityType.watching, name="you")) + await bot.change_presence( + activity=discord.Activity(type=discord.ActivityType.watching, name="you") + ) print("HAMMER BOT Ready!", datetime.datetime.now()) botname = await bot.application_info() print("logged in as:", botname.name) @@ -477,9 +484,7 @@ async def on_ready(): debug = False -@bot.slash_command(guild_only=True, - name="hello", - guild_ids=[int(SECURITY_GUILD)]) +@bot.slash_command(guild_only=True, name="hello", guild_ids=[int(SECURITY_GUILD)]) async def hello(ctx): await ctx.respond("Hammer is back!") @@ -548,7 +553,8 @@ async def whois(ctx, member: discord.Member): description="Keeps out a user permanently, forbidding its entry", ) @discord.default_permissions( - ban_members=True, ) + ban_members=True, +) async def ban(ctx, member: discord.Member, *, reason=None): if member == ctx.author: @@ -559,8 +565,7 @@ async def ban(ctx, member: discord.Member, *, reason=None): message = f"You have been banned from {ctx.guild.name} for {reason}" descr = f"The user {member} has been banned for {reason}" - embed = Embed(title=f"{member} has been banned! :hammer_pick:", - description=descr) + embed = Embed(title=f"{member} has been banned! :hammer_pick:", description=descr) embed.set_image(url="https://i.imgflip.com/19zat3.jpg") embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", @@ -583,11 +588,12 @@ async def ban(ctx, member: discord.Member, *, reason=None): await SendMessageTo(ctx, member, message) -@bot.slash_command(guild_only=True, - name="kick", - description="Kicks out a member from the server") +@bot.slash_command( + guild_only=True, name="kick", description="Kicks out a member from the server" +) @discord.default_permissions( - kick_members=True, ) + kick_members=True, +) async def kick(ctx, member: discord.Member, *, reason=None): if member == ctx.author: @@ -608,8 +614,7 @@ async def kick(ctx, member: discord.Member, *, reason=None): ) return descr = f"The user {member} has been kicked for {reason}" - embed = Embed(title=f"{member} has been kicked! :hammer_pick:", - description=descr) + embed = Embed(title=f"{member} has been kicked! :hammer_pick:", description=descr) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", icon_url=hammericon, @@ -626,7 +631,8 @@ async def kick(ctx, member: discord.Member, *, reason=None): description="Sets a warning for a user, at 3 warns/strikes they get kicked", ) @discord.default_permissions( - administrator=True, ) + administrator=True, +) async def warn(ctx, member: discord.Member, reason=None): if member == ctx.author: @@ -637,8 +643,7 @@ async def warn(ctx, member: discord.Member, reason=None): message = f"You have been warned for {reason}" descr = f"The user {member} has been warned for {reason}" - embed = Embed(title=f"{member} has been warned! :hammer_pick:", - description=descr) + embed = Embed(title=f"{member} has been warned! :hammer_pick:", description=descr) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", icon_url=hammericon, @@ -662,20 +667,29 @@ async def warn(ctx, member: discord.Member, reason=None): description="Displays the warn history of a user in the guild", ) @discord.default_permissions( - administrator=True, ) + administrator=True, +) async def seewarns(ctx, member: discord.Member): allwarns = await getAllWarns(member.id, ctx.guild.id) - if (len(allwarns) == 0): - allwarns = ['User had no warns at the moment'] - message = '\n'.join(allwarns) + if len(allwarns) == 0: + allwarns = ["User had no warns at the moment"] + message = "\n".join(allwarns) c = 0 data = [] for warn in await GetWarnings(member.id, ctx.guild.id, fullData=True): _, _, _, _, timestamp = warn c = c + 1 - data.append({'t': str(datetime.datetime.fromtimestamp( - int(str(timestamp)[:str(timestamp).find(".")]))), 'y': c}) + data.append( + { + "t": str( + datetime.datetime.fromtimestamp( + int(str(timestamp)[: str(timestamp).find(".")]) + ) + ), + "y": c, + } + ) qc = QuickChart() qc.width = 500 @@ -691,23 +705,23 @@ async def seewarns(ctx, member: discord.Member): "lineTension": 0, "backgroundColor": "#7289DA", "borderColor": "#7289DA", - "data": data + "data": data, } ] }, "options": { "scales": { - "xAxes": [{ - "type": "time", - "time": { - "parser": "YYYY-MM-DD HH:mm:ss", - "displayFormats": { - "day": "DD/MM/YYYY" - } + "xAxes": [ + { + "type": "time", + "time": { + "parser": "YYYY-MM-DD HH:mm:ss", + "displayFormats": {"day": "DD/MM/YYYY"}, + }, } - }] + ] } - } + }, } uurl = qc.get_url() @@ -721,19 +735,23 @@ async def seewarns(ctx, member: discord.Member): return await ctx.respond(embed=embed) -@bot.slash_command(guild_only=True, - name="unwarn", - description="Removes a strike from a user") +@bot.slash_command( + guild_only=True, name="unwarn", description="Removes a strike from a user" +) @discord.default_permissions( kick_members=True, ) async def unwarn(ctx, member: discord.Member, id: int = None, *, reason=None): - if (await GetWarnings(member.id, ctx.guild.id) == 0): + if await GetWarnings(member.id, ctx.guild.id) == 0: return await ctx.respond("This user does not have any warn!") if id == None: - message = f"""To select a warn to remove, use argument id and specify its value.""" + message = ( + f"""To select a warn to remove, use argument id and specify its value.""" + ) - embed = Embed(title=f"ERROR! Need to select a warn :hammer_pick:", description=message) + embed = Embed( + title=f"ERROR! Need to select a warn :hammer_pick:", description=message + ) allwarns = await getAllWarns(member.id, ctx.guild.id) embed.add_field( name=f"**Historic of {member.name}**:", @@ -745,8 +763,7 @@ async def unwarn(ctx, member: discord.Member, id: int = None, *, reason=None): message = f"You have been unwarned for {reason}" descr = f"The user {member} has been unwarned for {reason}" - embed = Embed(title=f"{member} has been unwarned! :hammer_pick:", - description=descr) + embed = Embed(title=f"{member} has been unwarned! :hammer_pick:", description=descr) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", icon_url=hammericon, @@ -764,11 +781,12 @@ async def unwarn(ctx, member: discord.Member, id: int = None, *, reason=None): await SendMessageTo(ctx, member, message) -@bot.slash_command(guild_only=True, - name="clearwarns", - description="Removes all strikes from a user") +@bot.slash_command( + guild_only=True, name="clearwarns", description="Removes all strikes from a user" +) @discord.default_permissions( - kick_members=True, ) + kick_members=True, +) async def clearwarns(ctx, member: discord.Member, *, reason=None): if reason == None: @@ -795,9 +813,11 @@ async def clearwarns(ctx, member: discord.Member, *, reason=None): await SendMessageTo(ctx, member, message) -@bot.slash_command(guild_only=True, - name="automod", - description="Customizes in this guild Hammer's automod") +@bot.slash_command( + guild_only=True, + name="automod", + description="Customizes in this guild Hammer's automod", +) @discord.default_permissions( administrator=True, ) @@ -807,18 +827,30 @@ async def clearwarns(ctx, member: discord.Member, *, reason=None): autocomplete=discord.utils.basic_autocomplete(["add", "remove"]), ) async def automod(ctx, action: str, word: str): - if (action == "remove"): + if action == "remove": response = await AddAllowedWord(ctx.guild.id, ctx.author.id, word) - elif (action == "add"): + elif action == "add": response = await AddDeniedWord(ctx.guild.id, ctx.author.id, word) else: - return await ctx.respond(embed=ErrorEmbed("Wrong syntax, please use /automod add/remove [word]"), ephemeral=True) - if (response): + return await ctx.respond( + embed=ErrorEmbed("Wrong syntax, please use /automod add/remove [word]"), + ephemeral=True, + ) + if response: prep = "to" if action == "add" else "from" - return await ctx.respond("Word ||" + str(word) + f"|| successfully {action}ed {prep} the swear word list. :tools:", ephemeral=True) + return await ctx.respond( + "Word ||" + + str(word) + + f"|| successfully {action}ed {prep} the swear word list. :tools:", + ephemeral=True, + ) else: - return await ctx.respond(embed=ErrorEmbed( - f"Could not save the word ||{word}|| to the database. Please contact the administrator or bot developer for further information. "), ephemeral=True) + return await ctx.respond( + embed=ErrorEmbed( + f"Could not save the word ||{word}|| to the database. Please contact the administrator or bot developer for further information. " + ), + ephemeral=True, + ) @bot.slash_command(guild_only=True, guild_ids=[int(SECURITY_GUILD)]) @@ -911,15 +943,16 @@ async def restart(ctx): description="Updates the message delay in a channel with a set of custom time interval", ) @discord.default_permissions( - manage_messages=True, ) + manage_messages=True, +) async def setdelay(ctx, seconds: float, reason: str = ""): m = "modified" if seconds > 0.0 else "removed" embed = Embed( title=f"Delay {m} on #{ctx.channel} :hammer_pick:", description=f"This channel now has a delay of **{seconds}** seconds for {reason}" - if reason != None and reason != "" else - f"This channel now has a delay of **{seconds}** seconds", + if reason != None and reason != "" + else f"This channel now has a delay of **{seconds}** seconds", ) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", @@ -937,7 +970,8 @@ async def setdelay(ctx, seconds: float, reason: str = ""): description="Removes the hability to talk or join voice channels to a user", ) @discord.default_permissions( - manage_messages=True, ) + manage_messages=True, +) async def mute(ctx, member: discord.Member, *, reason=None): guild = ctx.guild @@ -980,7 +1014,8 @@ async def mute(ctx, member: discord.Member, *, reason=None): description="Restores the hability to talk or join voice channels to a user", ) @discord.default_permissions( - manage_messages=True, ) + manage_messages=True, +) async def unmute(ctx, member: discord.Member, *, reason=None): mutedRole = discord.utils.get(ctx.guild.roles, name="Muted") @@ -990,8 +1025,8 @@ async def unmute(ctx, member: discord.Member, *, reason=None): reason = "for " + reason await member.remove_roles(mutedRole) SendMessageTo( - ctx, member, - f":tada: You have been unmuted from: {ctx.guild.name} {reason}") + ctx, member, f":tada: You have been unmuted from: {ctx.guild.name} {reason}" + ) embed = discord.Embed( title=f"User Unmuted: {member}", description=f"User {member.mention} has been unmuted {reason}", @@ -1090,9 +1125,9 @@ async def invite(ctx): @discord.default_permissions(administrator=True) -@bot.slash_command(name="settings", - description="Modifies some Hammer config values", - guild_only=True) +@bot.slash_command( + name="settings", description="Modifies some Hammer config values", guild_only=True +) @option( "module", description="Pick a module to switch!", @@ -1109,12 +1144,10 @@ async def settings(ctx, module: str = None, value: str = None): value = 1 if value == "on" else 0 await SaveSetting(ctx.guild.id, module, value) action = "enabled" if value else "disabled" - await ctx.respond(f"Module {module} {action} successfully!", - ephemeral=True) + await ctx.respond(f"Module {module} {action} successfully!", ephemeral=True) return else: - await ctx.respond("Use: ``/settings module on/off``", - ephemeral=True) + await ctx.respond("Use: ``/settings module on/off``", ephemeral=True) return embed = Embed( title=f"Hammer Bot Settings :hammer_pick:", @@ -1125,8 +1158,9 @@ async def settings(ctx, module: str = None, value: str = None): automodStatustr = "**✅ ON**" if automodStatus else "**❌ OFF**" recommendedactivityAutomod = ( f"Disable it by doing: ``{COMMAND_PREFIX}settings automod off``" - if automodStatus else - f"Enable it by doing ``{COMMAND_PREFIX}settings automod on``") + if automodStatus + else f"Enable it by doing ``{COMMAND_PREFIX}settings automod on``" + ) embed.add_field( name="AutoMod Services :robot:", value=f"Actual status: {automodStatustr}\n {recommendedactivityAutomod}", From 7ea8991f5101128b3f52df6428f28dcacd9e06a1 Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Fri, 11 Nov 2022 11:21:49 +0000 Subject: [PATCH 14/16] Restyled by isort --- bot.py | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/bot.py b/bot.py index f44b76f..43fe855 100644 --- a/bot.py +++ b/bot.py @@ -2,27 +2,21 @@ import os import sqlite3 import sys +import urllib from email import message from pydoc import describe from time import time -from quickchart import QuickChart -import urllib import discord -from discord import Embed -from discord import guild_only +from discord import Embed, guild_only from discord.commands import option from discord.ext import commands from discord.ext.commands.core import command +from quickchart import QuickChart -from get_enviroment import ANNOUNCEMENTS_CHANNEL -from get_enviroment import COMMAND_PREFIX -from get_enviroment import DEV_SUGGESTIONS_CHANNEL -from get_enviroment import OWNER -from get_enviroment import SECURITY_CHANNEL -from get_enviroment import SECURITY_GUILD -from get_enviroment import SWEAR_WORDS_LIST -from get_enviroment import TOKEN +from get_enviroment import (ANNOUNCEMENTS_CHANNEL, COMMAND_PREFIX, + DEV_SUGGESTIONS_CHANNEL, OWNER, SECURITY_CHANNEL, + SECURITY_GUILD, SWEAR_WORDS_LIST, TOKEN) # database import & connection From 3b1cc9e8cfeae5cfe55e533085d3d62b1623baa0 Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Fri, 11 Nov 2022 11:21:50 +0000 Subject: [PATCH 15/16] Restyled by reorder-python-imports --- bot.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/bot.py b/bot.py index 43fe855..92b4726 100644 --- a/bot.py +++ b/bot.py @@ -8,15 +8,21 @@ from time import time import discord -from discord import Embed, guild_only +from discord import Embed +from discord import guild_only from discord.commands import option from discord.ext import commands from discord.ext.commands.core import command from quickchart import QuickChart -from get_enviroment import (ANNOUNCEMENTS_CHANNEL, COMMAND_PREFIX, - DEV_SUGGESTIONS_CHANNEL, OWNER, SECURITY_CHANNEL, - SECURITY_GUILD, SWEAR_WORDS_LIST, TOKEN) +from get_enviroment import ANNOUNCEMENTS_CHANNEL +from get_enviroment import COMMAND_PREFIX +from get_enviroment import DEV_SUGGESTIONS_CHANNEL +from get_enviroment import OWNER +from get_enviroment import SECURITY_CHANNEL +from get_enviroment import SECURITY_GUILD +from get_enviroment import SWEAR_WORDS_LIST +from get_enviroment import TOKEN # database import & connection From 456172b7277855c80391f747d9785915dbfe3eb7 Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Fri, 11 Nov 2022 11:21:52 +0000 Subject: [PATCH 16/16] Restyled by yapf --- bot.py | 275 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 135 insertions(+), 140 deletions(-) diff --git a/bot.py b/bot.py index 92b4726..17deb54 100644 --- a/bot.py +++ b/bot.py @@ -28,30 +28,24 @@ conn = sqlite3.connect("maindatabase1.db") cur = conn.cursor() -cur.execute( - """CREATE TABLE IF NOT EXISTS `warns` ( +cur.execute("""CREATE TABLE IF NOT EXISTS `warns` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `userid` INT(100), `guildid` INT, `reason` TEXT, `timestamp` INT); - """ -) -cur.execute( - """CREATE TABLE IF NOT EXISTS `customWords` ( + """) +cur.execute("""CREATE TABLE IF NOT EXISTS `customWords` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `guildid` INT, `uploaderId`INT, `word` TEXT, `type` INT); - """ -) -cur.execute( - """CREATE TABLE IF NOT EXISTS `settings` ( + """) +cur.execute("""CREATE TABLE IF NOT EXISTS `settings` ( `guildid` INT(100) UNIQUE, `automod` INT); - """ -) + """) hammericon = "https://images-ext-2.discordapp.net/external/OKc8xu6AILGNFY3nSTt7wGbg-Mi1iQZonoLTFg85o-E/%3Fsize%3D1024/https/cdn.discordapp.com/avatars/591633652493058068/e6011129c5169b29ed05a6dc873175cb.png?width=670&height=670" @@ -69,9 +63,9 @@ # -@bot.slash_command( - name="help", description="Displays all the available commands for Hammer" -) +@bot.slash_command(name="help", + description="Displays all the available commands for Hammer" + ) async def help(ctx): # Define each page @@ -80,9 +74,9 @@ async def help(ctx): **Hammer's commands:** """ - embed = Embed( - title="Hammer Bot Help", description=descr, colour=discord.Colour.lighter_grey() - ) + embed = Embed(title="Hammer Bot Help", + description=descr, + colour=discord.Colour.lighter_grey()) embed.add_field( name="Moderation Commands :tools:", @@ -131,7 +125,8 @@ async def help(ctx): embed.add_field( name="""Useful Links: :link:""", - value=f"""[:classical_building: Hammer Bot Support](https://discord.gg/fMSyQA6) + value= + f"""[:classical_building: Hammer Bot Support](https://discord.gg/fMSyQA6) [:link: Hammer Invite Link](https://discordapp.com/api/oauth2/authorize?client_id=591633652493058068&permissions=8&scope=bot) [:newspaper: Vote Hammer](https://top.gg/bot/591633652493058068) """, @@ -148,9 +143,8 @@ async def help(ctx): inline=True, ) - embed.set_footer( - text=f"Hammer | Command executed by {ctx.author}", icon_url=hammericon - ) + embed.set_footer(text=f"Hammer | Command executed by {ctx.author}", + icon_url=hammericon) await ctx.respond(embed=embed) @@ -210,7 +204,8 @@ async def Removewarn(userid: int, guildId: int, relativeWarnId: int): async def Clearwarns(userid: int, guildId: int): # delete all rows - cur.execute("DELETE FROM warns WHERE userid=? AND guildid=?", (userid, guildId)) + cur.execute("DELETE FROM warns WHERE userid=? AND guildid=?", + (userid, guildId)) conn.commit() return @@ -226,8 +221,9 @@ async def getAllWarns(userid: int, guildid: int): else: emojis = str(c) - ddt = int(str(dt)[: str(dt).find(".")]) - allwarns.append(f"- **ID: {emojis}** Reason: ``{SubReason}`` ") + ddt = int(str(dt)[:str(dt).find(".")]) + allwarns.append( + f"- **ID: {emojis}** Reason: ``{SubReason}`` ") c = c + 1 return allwarns @@ -235,9 +231,8 @@ async def getAllWarns(userid: int, guildid: int): async def GetAutomodCustomWords(guildid: int, mode: str): wtype = 1 if mode == "allow" else 0 - cur.execute( - "SELECT word FROM customWords WHERE guildid = ? AND type = ?", (guildid, wtype) - ) + cur.execute("SELECT word FROM customWords WHERE guildid = ? AND type = ?", + (guildid, wtype)) words = cur.fetchall() a = [] if len(words) > 0: @@ -292,7 +287,8 @@ async def AddDeniedWord(guildid: int, userid: int, word: str): async def GetSettings(guildid: int): - cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", (guildid,)) + cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", + (guildid, )) rows = cur.fetchall() if len(rows) > 0: return rows[0][1] @@ -301,10 +297,13 @@ async def GetSettings(guildid: int): async def SaveSetting(guildid: int, module: str, value: int): - cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", (guildid,)) + cur.execute("SELECT * FROM settings WHERE guildid = ? LIMIT 1", + (guildid, )) rows = cur.fetchall() # print(rows) - if len(rows) > 0: # cur.execute('INSERT INTO foo (a,b) values (?,?)', (strA, strB)) + if len( + rows + ) > 0: # cur.execute('INSERT INTO foo (a,b) values (?,?)', (strA, strB)) query = f"""UPDATE settings SET automod = {value} WHERE guildid={guildid} """ @@ -342,7 +341,8 @@ def ErrorEmbed(error): embed = Embed(title=f":no_entry_sign: Error!", description=error) embed.set_thumbnail( - url="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ficonsplace.com%2Fwp-content%2Fuploads%2F_icons%2Fff0000%2F256%2Fpng%2Ferror-icon-14-256.png&f=1&nofb=1" + url= + "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ficonsplace.com%2Fwp-content%2Fuploads%2F_icons%2Fff0000%2F256%2Fpng%2Ferror-icon-14-256.png&f=1&nofb=1" ) embed.set_footer( @@ -395,8 +395,10 @@ async def on_message(message): if int(await GetSettings(message.guild.id)) != 1: return # user has disabled Automod words = message.content.split() - allowed_words_guild_list = await GetAutomodCustomWords(message.guild.id, "allow") - denied_words_guild_list = await GetAutomodCustomWords(message.guild.id, "deny") + allowed_words_guild_list = await GetAutomodCustomWords( + message.guild.id, "allow") + denied_words_guild_list = await GetAutomodCustomWords( + message.guild.id, "deny") print("scanned: ", message.content) for word in words: # print("scanning word:",word) @@ -413,30 +415,26 @@ async def on_message(message): descr = ( f"The user {member} has been warned because said a banned swear word" ) - embed = Embed( - title=f"{member} has been warned! :hammer_pick:", description=descr - ) + embed = Embed(title=f"{member} has been warned! :hammer_pick:", + description=descr) embed.set_footer( text=f"Hammer | Automod service", icon_url=hammericon, ) embed.set_thumbnail(url=member.display_avatar) - warn = await AddWarning( - member.id, message.guild.id, "Said a banned swear word" - ) + warn = await AddWarning(member.id, message.guild.id, + "Said a banned swear word") s = "s" if warn > 1 else "" embed.add_field( name="Warn count", - value=f"The user {member} has {warn} warn{s}. Be careful. Run /seewarns @user to check its warnhistory", + value= + f"The user {member} has {warn} warn{s}. Be careful. Run /seewarns @user to check its warnhistory", inline=True, ) bannedmessage = ( - message.content[: message.content.find(word)] - + "~~" - + word - + "~~" - + message.content[message.content.find(word) + len(word) :] - ) + message.content[:message.content.find(word)] + "~~" + word + + "~~" + + message.content[message.content.find(word) + len(word):]) embed.add_field( name="Message Removed:", value=f"The removed message was \n||{bannedmessage}||", @@ -444,7 +442,8 @@ async def on_message(message): ) embed.add_field( name="Not happy with this?", - value=f"Disable this feature with ``/settings automod off`` or simply ``/suggest`` a new change", + value= + f"Disable this feature with ``/settings automod off`` or simply ``/suggest`` a new change", inline=False, ) await message.channel.send(embed=embed) @@ -457,17 +456,15 @@ async def on_message(message): embed = ErrorEmbed( await message.channel.send( f"Could not deliver the message to the user {member}\n This may be caused because the user is a bot, has blocked me or has the DMs turned off. \n\n**But the user is warned** and I have saved it into my beautiful unforgettable database" - ), - ) + ), ) # if(str(message.content).startswith(COMMAND_PREFIX)): # print("command executed", message.content) @bot.event async def on_ready(): - await bot.change_presence( - activity=discord.Activity(type=discord.ActivityType.watching, name="you") - ) + await bot.change_presence(activity=discord.Activity( + type=discord.ActivityType.watching, name="you")) print("HAMMER BOT Ready!", datetime.datetime.now()) botname = await bot.application_info() print("logged in as:", botname.name) @@ -484,7 +481,9 @@ async def on_ready(): debug = False -@bot.slash_command(guild_only=True, name="hello", guild_ids=[int(SECURITY_GUILD)]) +@bot.slash_command(guild_only=True, + name="hello", + guild_ids=[int(SECURITY_GUILD)]) async def hello(ctx): await ctx.respond("Hammer is back!") @@ -553,8 +552,7 @@ async def whois(ctx, member: discord.Member): description="Keeps out a user permanently, forbidding its entry", ) @discord.default_permissions( - ban_members=True, -) + ban_members=True, ) async def ban(ctx, member: discord.Member, *, reason=None): if member == ctx.author: @@ -565,7 +563,8 @@ async def ban(ctx, member: discord.Member, *, reason=None): message = f"You have been banned from {ctx.guild.name} for {reason}" descr = f"The user {member} has been banned for {reason}" - embed = Embed(title=f"{member} has been banned! :hammer_pick:", description=descr) + embed = Embed(title=f"{member} has been banned! :hammer_pick:", + description=descr) embed.set_image(url="https://i.imgflip.com/19zat3.jpg") embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", @@ -588,12 +587,11 @@ async def ban(ctx, member: discord.Member, *, reason=None): await SendMessageTo(ctx, member, message) -@bot.slash_command( - guild_only=True, name="kick", description="Kicks out a member from the server" -) +@bot.slash_command(guild_only=True, + name="kick", + description="Kicks out a member from the server") @discord.default_permissions( - kick_members=True, -) + kick_members=True, ) async def kick(ctx, member: discord.Member, *, reason=None): if member == ctx.author: @@ -614,7 +612,8 @@ async def kick(ctx, member: discord.Member, *, reason=None): ) return descr = f"The user {member} has been kicked for {reason}" - embed = Embed(title=f"{member} has been kicked! :hammer_pick:", description=descr) + embed = Embed(title=f"{member} has been kicked! :hammer_pick:", + description=descr) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", icon_url=hammericon, @@ -631,8 +630,7 @@ async def kick(ctx, member: discord.Member, *, reason=None): description="Sets a warning for a user, at 3 warns/strikes they get kicked", ) @discord.default_permissions( - administrator=True, -) + administrator=True, ) async def warn(ctx, member: discord.Member, reason=None): if member == ctx.author: @@ -643,7 +641,8 @@ async def warn(ctx, member: discord.Member, reason=None): message = f"You have been warned for {reason}" descr = f"The user {member} has been warned for {reason}" - embed = Embed(title=f"{member} has been warned! :hammer_pick:", description=descr) + embed = Embed(title=f"{member} has been warned! :hammer_pick:", + description=descr) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", icon_url=hammericon, @@ -667,8 +666,7 @@ async def warn(ctx, member: discord.Member, reason=None): description="Displays the warn history of a user in the guild", ) @discord.default_permissions( - administrator=True, -) + administrator=True, ) async def seewarns(ctx, member: discord.Member): allwarns = await getAllWarns(member.id, ctx.guild.id) if len(allwarns) == 0: @@ -680,16 +678,14 @@ async def seewarns(ctx, member: discord.Member): for warn in await GetWarnings(member.id, ctx.guild.id, fullData=True): _, _, _, _, timestamp = warn c = c + 1 - data.append( - { - "t": str( - datetime.datetime.fromtimestamp( - int(str(timestamp)[: str(timestamp).find(".")]) - ) - ), - "y": c, - } - ) + data.append({ + "t": + str( + datetime.datetime.fromtimestamp( + int(str(timestamp)[:str(timestamp).find(".")]))), + "y": + c, + }) qc = QuickChart() qc.width = 500 @@ -698,28 +694,26 @@ async def seewarns(ctx, member: discord.Member): qc.config = { "type": "line", "data": { - "datasets": [ - { - "fill": False, - "label": [f"Warns of {member}"], - "lineTension": 0, - "backgroundColor": "#7289DA", - "borderColor": "#7289DA", - "data": data, - } - ] + "datasets": [{ + "fill": False, + "label": [f"Warns of {member}"], + "lineTension": 0, + "backgroundColor": "#7289DA", + "borderColor": "#7289DA", + "data": data, + }] }, "options": { "scales": { - "xAxes": [ - { - "type": "time", - "time": { - "parser": "YYYY-MM-DD HH:mm:ss", - "displayFormats": {"day": "DD/MM/YYYY"}, + "xAxes": [{ + "type": "time", + "time": { + "parser": "YYYY-MM-DD HH:mm:ss", + "displayFormats": { + "day": "DD/MM/YYYY" }, - } - ] + }, + }] } }, } @@ -735,12 +729,11 @@ async def seewarns(ctx, member: discord.Member): return await ctx.respond(embed=embed) -@bot.slash_command( - guild_only=True, name="unwarn", description="Removes a strike from a user" -) +@bot.slash_command(guild_only=True, + name="unwarn", + description="Removes a strike from a user") @discord.default_permissions( - kick_members=True, -) + kick_members=True, ) async def unwarn(ctx, member: discord.Member, id: int = None, *, reason=None): if await GetWarnings(member.id, ctx.guild.id) == 0: return await ctx.respond("This user does not have any warn!") @@ -749,9 +742,8 @@ async def unwarn(ctx, member: discord.Member, id: int = None, *, reason=None): f"""To select a warn to remove, use argument id and specify its value.""" ) - embed = Embed( - title=f"ERROR! Need to select a warn :hammer_pick:", description=message - ) + embed = Embed(title=f"ERROR! Need to select a warn :hammer_pick:", + description=message) allwarns = await getAllWarns(member.id, ctx.guild.id) embed.add_field( name=f"**Historic of {member.name}**:", @@ -763,7 +755,8 @@ async def unwarn(ctx, member: discord.Member, id: int = None, *, reason=None): message = f"You have been unwarned for {reason}" descr = f"The user {member} has been unwarned for {reason}" - embed = Embed(title=f"{member} has been unwarned! :hammer_pick:", description=descr) + embed = Embed(title=f"{member} has been unwarned! :hammer_pick:", + description=descr) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", icon_url=hammericon, @@ -781,12 +774,11 @@ async def unwarn(ctx, member: discord.Member, id: int = None, *, reason=None): await SendMessageTo(ctx, member, message) -@bot.slash_command( - guild_only=True, name="clearwarns", description="Removes all strikes from a user" -) +@bot.slash_command(guild_only=True, + name="clearwarns", + description="Removes all strikes from a user") @discord.default_permissions( - kick_members=True, -) + kick_members=True, ) async def clearwarns(ctx, member: discord.Member, *, reason=None): if reason == None: @@ -819,8 +811,7 @@ async def clearwarns(ctx, member: discord.Member, *, reason=None): description="Customizes in this guild Hammer's automod", ) @discord.default_permissions( - administrator=True, -) + administrator=True, ) @option( "action", description="Select add/remove word from swear list", @@ -833,15 +824,15 @@ async def automod(ctx, action: str, word: str): response = await AddDeniedWord(ctx.guild.id, ctx.author.id, word) else: return await ctx.respond( - embed=ErrorEmbed("Wrong syntax, please use /automod add/remove [word]"), + embed=ErrorEmbed( + "Wrong syntax, please use /automod add/remove [word]"), ephemeral=True, ) if response: prep = "to" if action == "add" else "from" return await ctx.respond( - "Word ||" - + str(word) - + f"|| successfully {action}ed {prep} the swear word list. :tools:", + "Word ||" + str(word) + + f"|| successfully {action}ed {prep} the swear word list. :tools:", ephemeral=True, ) else: @@ -940,19 +931,20 @@ async def restart(ctx): @bot.slash_command( guild_only=True, name="setdelay", - description="Updates the message delay in a channel with a set of custom time interval", + description= + "Updates the message delay in a channel with a set of custom time interval", ) @discord.default_permissions( - manage_messages=True, -) + manage_messages=True, ) async def setdelay(ctx, seconds: float, reason: str = ""): m = "modified" if seconds > 0.0 else "removed" embed = Embed( title=f"Delay {m} on #{ctx.channel} :hammer_pick:", - description=f"This channel now has a delay of **{seconds}** seconds for {reason}" - if reason != None and reason != "" - else f"This channel now has a delay of **{seconds}** seconds", + description= + f"This channel now has a delay of **{seconds}** seconds for {reason}" + if reason != None and reason != "" else + f"This channel now has a delay of **{seconds}** seconds", ) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", @@ -970,8 +962,7 @@ async def setdelay(ctx, seconds: float, reason: str = ""): description="Removes the hability to talk or join voice channels to a user", ) @discord.default_permissions( - manage_messages=True, -) + manage_messages=True, ) async def mute(ctx, member: discord.Member, *, reason=None): guild = ctx.guild @@ -1011,11 +1002,11 @@ async def mute(ctx, member: discord.Member, *, reason=None): @bot.slash_command( guild_only=True, name="unmute", - description="Restores the hability to talk or join voice channels to a user", + description= + "Restores the hability to talk or join voice channels to a user", ) @discord.default_permissions( - manage_messages=True, -) + manage_messages=True, ) async def unmute(ctx, member: discord.Member, *, reason=None): mutedRole = discord.utils.get(ctx.guild.roles, name="Muted") @@ -1025,8 +1016,8 @@ async def unmute(ctx, member: discord.Member, *, reason=None): reason = "for " + reason await member.remove_roles(mutedRole) SendMessageTo( - ctx, member, f":tada: You have been unmuted from: {ctx.guild.name} {reason}" - ) + ctx, member, + f":tada: You have been unmuted from: {ctx.guild.name} {reason}") embed = discord.Embed( title=f"User Unmuted: {member}", description=f"User {member.mention} has been unmuted {reason}", @@ -1063,7 +1054,8 @@ async def lock(ctx, channel: discord.TextChannel = None, reason=None): @bot.slash_command( guild_only=True, name="unlock", - description="Removes the blocking in a channel from not being used as a chat.", + description= + "Removes the blocking in a channel from not being used as a chat.", ) async def unlock(ctx, channel: discord.TextChannel = None, reason=None): @@ -1112,7 +1104,8 @@ async def suggest(ctx, suggestion: str): async def invite(ctx): embed = Embed( title=f"Invite Hammer Bot to your server! :hammer_pick:", - description=f"[**🔗 Hammer Invite Link**](https://discordapp.com/api/oauth2/authorize?client_id=591633652493058068&permissions=8&scope=bot)", + description= + f"[**🔗 Hammer Invite Link**](https://discordapp.com/api/oauth2/authorize?client_id=591633652493058068&permissions=8&scope=bot)", ) embed.set_footer( text=f"Hammer | Command executed by {ctx.author}", @@ -1125,9 +1118,9 @@ async def invite(ctx): @discord.default_permissions(administrator=True) -@bot.slash_command( - name="settings", description="Modifies some Hammer config values", guild_only=True -) +@bot.slash_command(name="settings", + description="Modifies some Hammer config values", + guild_only=True) @option( "module", description="Pick a module to switch!", @@ -1144,10 +1137,12 @@ async def settings(ctx, module: str = None, value: str = None): value = 1 if value == "on" else 0 await SaveSetting(ctx.guild.id, module, value) action = "enabled" if value else "disabled" - await ctx.respond(f"Module {module} {action} successfully!", ephemeral=True) + await ctx.respond(f"Module {module} {action} successfully!", + ephemeral=True) return else: - await ctx.respond("Use: ``/settings module on/off``", ephemeral=True) + await ctx.respond("Use: ``/settings module on/off``", + ephemeral=True) return embed = Embed( title=f"Hammer Bot Settings :hammer_pick:", @@ -1158,12 +1153,12 @@ async def settings(ctx, module: str = None, value: str = None): automodStatustr = "**✅ ON**" if automodStatus else "**❌ OFF**" recommendedactivityAutomod = ( f"Disable it by doing: ``{COMMAND_PREFIX}settings automod off``" - if automodStatus - else f"Enable it by doing ``{COMMAND_PREFIX}settings automod on``" - ) + if automodStatus else + f"Enable it by doing ``{COMMAND_PREFIX}settings automod on``") embed.add_field( name="AutoMod Services :robot:", - value=f"Actual status: {automodStatustr}\n {recommendedactivityAutomod}", + value= + f"Actual status: {automodStatustr}\n {recommendedactivityAutomod}", inline=True, ) embed.set_footer(