2023-10-04 09:11:49 -04:00
import logging
2023-10-04 11:04:36 -04:00
import time
2023-10-04 13:11:18 -04:00
from datetime import datetime , timedelta , timezone
2023-09-24 23:55:21 -04:00
import discord
2023-10-04 13:11:18 -04:00
import humanize
2023-10-04 09:11:49 -04:00
import mysql . connector
2023-10-04 11:04:36 -04:00
from pytimeparse2 import disable_dateutil , parse
2023-10-04 16:44:07 -04:00
from redbot . core import Config , checks , commands
2023-10-04 09:11:49 -04:00
2023-10-04 13:11:18 -04:00
2023-09-24 23:55:21 -04:00
class Moderation ( commands . Cog ) :
2023-09-27 13:24:57 -04:00
""" Custom cog moderation cog, meant to copy GalacticBot.
2023-09-24 23:55:21 -04:00
Developed by SeaswimmerTheFsh . """
def __init__ ( self , bot ) :
self . bot = bot
self . config = Config . get_conf ( self , identifier = 481923957134912 )
self . config . register_global (
mysql_address = " " ,
mysql_database = " " ,
2023-10-04 09:47:57 -04:00
mysql_username = " " ,
2023-10-04 11:57:21 -04:00
mysql_password = " " ,
ignore_other_bots = True
2023-09-24 23:55:21 -04:00
)
2023-10-04 09:11:49 -04:00
disable_dateutil ( )
async def cog_load ( self ) :
""" This method prepares the database schema for all of the guilds the bot is currently in. """
2023-10-04 09:29:49 -04:00
conf = await self . check_conf ( [
' mysql_address ' ,
' mysql_database ' ,
2023-10-04 09:47:57 -04:00
' mysql_username ' ,
2023-10-04 09:29:49 -04:00
' mysql_password '
] )
if conf :
logging . fatal ( " Failed to create tables, due to MySQL connection configuration being unset. " )
return
2023-10-04 09:11:49 -04:00
guilds : list [ discord . Guild ] = self . bot . guilds
2023-10-04 09:42:22 -04:00
try :
for guild in guilds :
await self . create_guild_table ( guild )
except ConnectionRefusedError :
return
2023-10-04 09:11:49 -04:00
@commands.Cog.listener ( ' on_guild_join ' )
async def db_generate_guild_join ( self , guild : discord . Guild ) :
""" This method prepares the database schema whenever the bot joins a guild. """
2023-10-04 09:29:49 -04:00
conf = await self . check_conf ( [
' mysql_address ' ,
' mysql_database ' ,
2023-10-04 09:47:57 -04:00
' mysql_username ' ,
2023-10-04 09:29:49 -04:00
' mysql_password '
] )
if conf :
2023-10-04 17:08:42 -04:00
logging . error ( " Failed to create a table for %s , due to MySQL connection configuration being unset. " , guild . id )
2023-10-04 09:29:49 -04:00
return
2023-10-04 09:42:22 -04:00
try :
await self . create_guild_table ( guild )
except ConnectionRefusedError :
return
2023-09-24 23:55:21 -04:00
2023-10-04 11:32:25 -04:00
@commands.Cog.listener ( ' on_audit_log_entry_create ' )
2023-10-04 11:31:21 -04:00
async def autologger ( self , entry : discord . AuditLogEntry ) :
""" This method automatically logs moderations done by users manually ( " right clicks " ). """
2023-10-04 12:44:21 -04:00
if await self . config . ignore_other_bots ( ) is True :
if entry . user . bot or entry . target . bot :
return
2023-10-04 21:32:33 -04:00
else :
if entry . user . id == self . bot . user . id :
return
2023-10-04 11:31:21 -04:00
duration = " NULL "
2023-10-04 11:35:49 -04:00
if entry . reason :
reason = entry . reason + " (This action was performed without the bot.) "
else :
reason = " This action was performed without the bot. "
2023-10-04 11:31:21 -04:00
if entry . action == discord . AuditLogAction . kick :
moderation_type = ' KICK '
elif entry . action == discord . AuditLogAction . ban :
moderation_type = ' BAN '
elif entry . action == discord . AuditLogAction . unban :
moderation_type = ' UNBAN '
elif entry . action == discord . AuditLogAction . member_update :
2023-10-04 12:01:54 -04:00
if entry . after . timed_out_until is not None :
2023-10-04 12:22:21 -04:00
timed_out_until_aware = entry . after . timed_out_until . replace ( tzinfo = timezone . utc )
2023-10-04 12:24:13 -04:00
duration_datetime = timed_out_until_aware - datetime . now ( tz = timezone . utc )
2023-10-04 12:19:46 -04:00
minutes = round ( duration_datetime . total_seconds ( ) / 60 )
duration = timedelta ( minutes = minutes )
2023-10-04 12:45:29 -04:00
moderation_type = ' MUTE '
2023-10-04 12:01:54 -04:00
else :
2023-10-04 12:45:29 -04:00
moderation_type = ' UNMUTE '
2023-10-04 11:31:21 -04:00
else :
return
await self . mysql_log ( entry . guild . id , entry . user . id , moderation_type , entry . target . id , duration , reason )
2023-09-24 23:55:21 -04:00
async def connect ( self ) :
2023-10-04 09:11:49 -04:00
""" Connects to the MySQL database, and returns a connection object. """
conf = await self . check_conf ( [
' mysql_address ' ,
' mysql_database ' ,
2023-10-04 10:33:22 -04:00
' mysql_username ' ,
2023-10-04 09:11:49 -04:00
' mysql_password '
] )
if conf :
2023-10-04 09:29:49 -04:00
raise LookupError ( " MySQL connection details not set properly! " )
2023-10-04 09:20:39 -04:00
try :
connection = mysql . connector . connect (
2023-10-04 10:35:36 -04:00
host = await self . config . mysql_address ( ) ,
user = await self . config . mysql_username ( ) ,
password = await self . config . mysql_password ( ) ,
database = await self . config . mysql_database ( )
2023-10-04 09:20:39 -04:00
)
return connection
except mysql . connector . ProgrammingError as e :
2023-10-04 09:23:32 -04:00
logging . fatal ( " Unable to access the MySQL database! \n Error: \n %s " , e . msg )
2023-10-04 11:06:06 -04:00
raise ConnectionRefusedError ( f " Unable to access the MySQL Database! \n { e . msg } " ) from e
2023-10-04 09:11:49 -04:00
async def create_guild_table ( self , guild : discord . Guild ) :
database = await self . connect ( )
cursor = database . cursor ( )
try :
2023-10-04 16:37:59 -04:00
cursor . execute ( f " SELECT * FROM `moderation_ { guild . id } ` " )
2023-10-04 09:15:49 -04:00
logging . info ( " MySQL Table exists for server %s ( %s ) " , guild . name , guild . id )
2023-10-04 09:11:49 -04:00
except mysql . connector . errors . ProgrammingError :
query = f """
2023-10-04 16:37:59 -04:00
CREATE TABLE ` moderation_ { guild . id } ` (
2023-10-04 09:11:49 -04:00
moderation_id INT UNIQUE PRIMARY KEY NOT NULL ,
timestamp INT NOT NULL ,
moderation_type LONGTEXT NOT NULL ,
target_id LONGTEXT NOT NULL ,
moderator_id LONGTEXT NOT NULL ,
duration LONGTEXT ,
end_timestamp INT ,
reason LONGTEXT ,
resolved BOOL NOT NULL ,
resolve_reason LONGTEXT ,
expired BOOL NOT NULL
)
"""
cursor . execute ( query )
insert_query = f """
2023-10-04 16:37:59 -04:00
INSERT INTO ` moderation_ { guild . id } `
2023-10-04 09:11:49 -04:00
( moderation_id , timestamp , moderation_type , target_id , moderator_id , duration , end_timestamp , reason , resolved , resolve_reason , expired )
VALUES ( % s , % s , % s , % s , % s , % s , % s , % s , % s , % s , % s )
"""
insert_values = ( 0 , 0 , " NULL " , 0 , 0 , " NULL " , 0 , " NULL " , 0 , " NULL " , 0 )
cursor . execute ( insert_query , insert_values )
database . commit ( )
database . close ( )
2023-10-04 16:51:09 -04:00
logging . info ( " MySQL Table (moderation_ %s ) created for %s ( %s ) " , guild . id , guild . name , guild . id )
2023-10-04 09:11:49 -04:00
else :
database . close ( )
return
2023-09-24 23:55:21 -04:00
async def check_conf ( self , config : list ) :
""" Checks if any required config options are not set. """
not_found_list = [ ]
for item in config :
if await self . config . item ( ) == " " :
not_found_list . append ( item )
return not_found_list
2023-10-04 11:31:21 -04:00
async def mysql_log ( self , guild_id : str , author_id : str , moderation_type : str , target_id : int , duration , reason : str ) :
2023-10-04 11:04:36 -04:00
timestamp = int ( time . time ( ) )
if duration != " NULL " :
end_timedelta = datetime . fromtimestamp ( timestamp ) + duration
end_timestamp = int ( end_timedelta . timestamp ( ) )
else :
end_timestamp = 0
database = await self . connect ( )
cursor = database . cursor ( )
2023-10-04 16:37:59 -04:00
cursor . execute ( f " SELECT moderation_id FROM `moderation_ { guild_id } ` ORDER BY moderation_id DESC LIMIT 1 " )
2023-10-04 11:04:36 -04:00
moderation_id = cursor . fetchone ( ) [ 0 ] + 1
2023-10-04 16:37:59 -04:00
sql = f " INSERT INTO `moderation_ { guild_id } ` (moderation_id, timestamp, moderation_type, target_id, moderator_id, duration, end_timestamp, reason, resolved, resolve_reason, expired) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) "
2023-10-04 11:31:21 -04:00
val = ( moderation_id , timestamp , moderation_type , target_id , author_id , duration , end_timestamp , f " { reason } " , 0 , " NULL " , 0 )
2023-10-04 11:04:36 -04:00
cursor . execute ( sql , val )
database . commit ( )
database . close ( )
2023-10-04 16:37:59 -04:00
logging . debug ( " MySQL row inserted into moderation_ %s ! \n %s , %s , %s , %s , %s , %s , %s , %s , 0, NULL " , guild_id , moderation_id , timestamp , moderation_type , target_id , author_id , duration , end_timestamp , reason )
2023-10-04 11:04:36 -04:00
2023-10-04 16:39:58 -04:00
@commands.hybrid_command ( name = " warn " )
@commands.mod ( )
async def warn ( self , ctx : commands . Context , target : discord . Member , * , reason : str ) :
""" Warn a user. """
response = await ctx . send ( content = f " { target . mention } has been warned! \n **Reason** - ` { reason } ` " )
try :
embed = discord . Embed ( title = " Warned " , description = f " You have been warned in [ { ctx . guild . name } ]( { response . jump_url } ). " , color = await self . bot . get_embed_color ( None ) )
embed . add_field ( name = ' Reason ' , value = f " ` { reason } ` " )
await target . send ( embed = embed )
except discord . errors . HTTPException :
await response . edit ( content = f " { response . content } \n *Failed to send DM, user likely has the bot blocked.* " )
await self . mysql_log ( ctx . guild . id , ctx . author . id , ' WARN ' , target . id , ' NULL ' , reason )
@commands.hybrid_command ( name = " mute " , aliases = [ ' timeout ' , ' tm ' ] )
2023-10-04 12:46:48 -04:00
@commands.mod ( )
2023-10-04 13:16:03 -04:00
async def mute ( self , ctx : commands . Context , target : discord . Member , duration : str , * , reason : str ) :
2023-10-04 12:44:21 -04:00
""" Mute a user. """
2023-10-04 13:16:03 -04:00
if target . is_timed_out ( ) is True :
2023-10-04 13:18:44 -04:00
await ctx . send ( f " { target . mention } is already muted! " , allowed_mentions = discord . AllowedMentions ( users = False ) )
2023-10-04 13:16:03 -04:00
return
2023-10-04 12:44:21 -04:00
try :
parsed_time = parse ( sval = duration , as_timedelta = True , raise_exception = True )
except ValueError :
2023-10-04 21:42:15 -04:00
await ctx . send ( f " Please provide a valid duration! \n See ` { ctx . prefix } tdc` " )
2023-10-04 12:44:21 -04:00
return
2023-10-04 21:49:24 -04:00
if parsed_time . total_seconds ( ) / 1000 > = 2419200000 :
2023-10-04 21:39:36 -04:00
await ctx . send ( " Please provide a duration that is less than 28 days. " )
return
2023-10-04 12:44:21 -04:00
await target . timeout ( parsed_time )
2023-10-04 13:11:18 -04:00
response = await ctx . send ( content = f " { target . mention } has been muted for { humanize . precisedelta ( parsed_time ) } ! \n **Reason** - ` { reason } ` " )
2023-10-04 12:44:21 -04:00
try :
2023-10-04 13:16:03 -04:00
embed = discord . Embed ( title = " Muted " , description = f " You have been muted for { humanize . precisedelta ( parsed_time ) } in [ { ctx . guild . name } ]( { response . jump_url } ). " , color = await self . bot . get_embed_color ( None ) )
2023-10-04 12:44:21 -04:00
embed . add_field ( name = ' Reason ' , value = f " ` { reason } ` " )
await target . send ( embed = embed )
except discord . errors . HTTPException :
await response . edit ( content = f " { response . content } \n *Failed to send DM, user likely has the bot blocked.* " )
2023-10-04 12:59:26 -04:00
await self . mysql_log ( ctx . guild . id , ctx . author . id , ' MUTE ' , target . id , parsed_time , reason )
2023-10-04 12:44:21 -04:00
2023-10-04 16:43:15 -04:00
@commands.hybrid_command ( name = " unmute " , aliases = [ ' untimeout ' , ' utm ' ] )
@commands.mod ( )
async def unmute ( self , ctx : commands . Context , target : discord . Member , * , reason : str = None ) :
""" Unmute a user. """
if target . is_timed_out ( ) is False :
await ctx . send ( f " { target . mention } is not muted! " , allowed_mentions = discord . AllowedMentions ( users = False ) )
return
await target . timeout ( None )
if reason is None :
reason = " No reason given. "
response = await ctx . send ( content = f " { target . mention } has been unmuted! \n **Reason** - ` { reason } ` " )
try :
embed = discord . Embed ( title = " Unmuted " , description = f " You have been unmuted in [ { ctx . guild . name } ]( { response . jump_url } ). " , color = await self . bot . get_embed_color ( None ) )
embed . add_field ( name = ' Reason ' , value = f " ` { reason } ` " )
await target . send ( embed = embed )
except discord . errors . HTTPException :
await response . edit ( content = f " { response . content } \n *Failed to send DM, user likely has the bot blocked.* " )
await self . mysql_log ( ctx . guild . id , ctx . author . id , ' UNMUTE ' , target . id , ' NULL ' , reason )
2023-09-24 23:55:21 -04:00
@commands.group ( autohelp = True )
2023-09-24 23:57:39 -04:00
@checks.admin ( )
2023-09-24 23:55:21 -04:00
async def moderationset ( self , ctx : commands . Context ) :
""" Manage moderation commands. """
2023-10-04 11:57:21 -04:00
@moderationset.command ( name = " ignorebots " )
@checks.admin ( )
async def moderationset_ignorebots ( self , ctx : commands . Context ) :
await self . config . ignore_other_bots . set ( not await self . config . ignore_other_bots ( ) )
await ctx . send ( f " Ignore bots setting set to { await self . config . ignore_other_bots ( ) } " )
2023-09-24 23:55:21 -04:00
@moderationset.command ( name = " mysql " )
2023-09-24 23:57:39 -04:00
@checks.is_owner ( )
2023-09-24 23:55:21 -04:00
async def moderationset_mysql ( self , ctx : commands . Context ) :
""" Configure MySQL connection details. """
2023-09-25 00:06:13 -04:00
await ctx . message . add_reaction ( " ✅ " )
await ctx . author . send ( content = " Click the button below to configure your MySQL connection details. " , view = self . ConfigButtons ( 60 ) )
2023-09-24 23:55:21 -04:00
class ConfigButtons ( discord . ui . View ) :
def __init__ ( self , timeout ) :
super ( ) . __init__ ( )
self . config = Config . get_conf ( None , cog_name = ' Moderation ' , identifier = 481923957134912 )
@discord.ui.button ( label = " Edit " , style = discord . ButtonStyle . success )
async def config_button ( self , interaction : discord . Interaction , button : discord . ui . Button ) : # pylint: disable=unused-argument
await interaction . response . send_modal ( Moderation . MySQLConfigModal ( self . config ) )
class MySQLConfigModal ( discord . ui . Modal , title = " MySQL Database Configuration " ) :
def __init__ ( self , config ) :
super ( ) . __init__ ( )
self . config = config
address = discord . ui . TextInput (
label = " Address " ,
placeholder = " Input your MySQL address here. " ,
2023-09-25 00:02:57 -04:00
style = discord . TextStyle . short ,
2023-09-24 23:55:21 -04:00
required = False ,
max_length = 300
)
database = discord . ui . TextInput (
label = " Database " ,
placeholder = " Input the name of your database here. " ,
style = discord . TextStyle . short ,
required = False ,
max_length = 300
)
username = discord . ui . TextInput (
label = " Username " ,
placeholder = " Input your MySQL username here. " ,
style = discord . TextStyle . short ,
required = False ,
max_length = 300
)
password = discord . ui . TextInput (
label = " Password " ,
placeholder = " Input your MySQL password here. " ,
style = discord . TextStyle . short ,
required = False ,
max_length = 300
)
async def on_submit ( self , interaction : discord . Interaction ) :
message = " "
if self . address . value != " " :
await self . config . mysql_address . set ( self . address . value )
message + = f " - Address set to \n - ` { self . address . value } ` \n "
if self . database . value != " " :
await self . config . mysql_database . set ( self . database . value )
message + = f " - Database set to \n - ` { self . database . value } ` \n "
if self . username . value != " " :
await self . config . mysql_username . set ( self . username . value )
message + = f " - Username set to \n - ` { self . username . value } ` \n "
if self . password . value != " " :
await self . config . mysql_password . set ( self . password . value )
trimmed_password = self . password . value [ : 8 ]
message + = f " - Password set to \n - ` { trimmed_password } ` - Trimmed for security \n "
if message == " " :
trimmed_password = str ( await self . config . mysql_password ( ) ) [ : 8 ]
2023-09-25 00:02:57 -04:00
send = f " No changes were made. \n Current configuration: \n - Address: \n - ` { await self . config . mysql_address ( ) } ` \n - Database: \n - ` { await self . config . mysql_database ( ) } ` \n - Username: \n - ` { await self . config . mysql_username ( ) } ` \n - Password: \n - ` { trimmed_password } ` - Trimmed for security "
2023-09-24 23:55:21 -04:00
else :
send = f " Configuration changed: \n { message } "
await interaction . response . send_message ( send , ephemeral = True )
2023-10-04 21:32:33 -04:00
@commands.command ( aliases = [ " tdc " ] )
async def timedeltaconvert ( self , ctx : commands . Context , * , duration : str = None ) :
if not duration :
embed = discord . Embed ( description = f " ## timedeltaconvert \n This command converts a duration to a `timedelta` Python object. \n ### Example Usage \n ` { ctx . prefix } timedeltaconvert 1 day 15hr 82 minutes 52 s` \n ### Output \n `1 day, 16:22:52` " , color = await self . bot . get_embed_color ( None ) )
await ctx . send ( embed = embed )
else :
try :
parsed_time = parse ( duration , as_timedelta = True , raise_exception = True )
await ctx . send ( f " ` { str ( parsed_time ) } ` " )
except ValueError :
await ctx . send ( " Please provide a convertible value! " )