2023-10-04 09:11:49 -04:00
import logging
2023-12-13 15:35:17 -05:00
import json
2023-10-04 11:04:36 -04:00
import time
2023-12-13 15:35:17 -05:00
import os
2023-10-04 13:11:18 -04:00
from datetime import datetime , timedelta , timezone
2023-10-22 13:55:54 -04:00
from typing import Union
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-05 13:48:11 -04:00
from discord . ext import tasks
2023-10-04 11:04:36 -04:00
from pytimeparse2 import disable_dateutil , parse
2023-12-13 15:38:40 -05:00
from redbot . core import app_commands , checks , Config , commands , data_manager
2023-10-05 11:09:39 -04:00
from redbot . core . app_commands import Choice
2023-10-04 09:11:49 -04:00
2023-09-24 23:55:21 -04:00
class Moderation ( commands . Cog ) :
2023-10-22 13:28:50 -04:00
""" Custom moderation cog.
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-05 20:09:42 -04:00
mysql_password = " "
)
self . config . register_guild (
2023-10-05 20:06:07 -04:00
ignore_other_bots = True ,
2023-10-23 20:09:17 -04:00
dm_users = True ,
log_channel = " "
2023-09-24 23:55:21 -04:00
)
2023-10-04 09:11:49 -04:00
disable_dateutil ( )
2023-10-05 16:55:18 -04:00
self . handle_expiry . start ( ) # pylint: disable=no-member
2023-10-06 10:25:13 -04:00
self . logger = logging . getLogger ( ' red.seaswimmerthefsh.moderation ' )
2023-10-04 09:11:49 -04:00
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 '
] )
2023-12-14 16:05:47 -05:00
2023-10-04 09:29:49 -04:00
if conf :
2023-10-06 10:25:13 -04:00
self . logger . fatal ( " Failed to create tables, due to MySQL connection configuration being unset. " )
2023-10-04 09:29:49 -04:00
return
2023-12-14 16:05:47 -05:00
2023-10-04 09:11:49 -04:00
guilds : list [ discord . Guild ] = self . bot . guilds
2023-12-14 16:05:47 -05:00
2023-10-04 09:42:22 -04:00
try :
for guild in guilds :
2023-10-22 13:28:50 -04:00
if not await self . bot . cog_disabled_in_guild ( self , guild ) :
await self . create_guild_table ( guild )
2023-12-14 16:05:47 -05:00
2023-10-04 09:42:22 -04:00
except ConnectionRefusedError :
return
2023-10-04 09:11:49 -04:00
2023-10-05 16:44:54 -04:00
async def cog_unload ( self ) :
2023-10-05 16:55:18 -04:00
self . handle_expiry . cancel ( ) # pylint: disable=no-member
2023-10-05 13:51:17 -04:00
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-22 13:28:50 -04:00
if not await self . bot . cog_disabled_in_guild ( self , guild ) :
conf = await self . check_conf ( [
' mysql_address ' ,
' mysql_database ' ,
' mysql_username ' ,
' mysql_password '
2023-12-14 16:05:47 -05:00
2023-10-22 13:28:50 -04:00
] )
if conf :
self . logger . error ( " Failed to create a table for %s , due to MySQL connection configuration being unset. " , guild . id )
return
2023-12-14 16:05:47 -05:00
2023-10-22 13:28:50 -04:00
try :
await self . create_guild_table ( guild )
2023-12-14 16:05:47 -05:00
2023-10-22 13:28:50 -04:00
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-22 13:28:50 -04:00
if not await self . bot . cog_disabled_in_guild ( self , entry . guild ) :
if await self . config . guild ( entry . guild . id ) . ignore_other_bots ( ) is True :
if entry . user . bot or entry . target . bot :
return
2023-10-04 12:01:54 -04:00
else :
2023-10-22 13:28:50 -04:00
if entry . user . id == self . bot . user . id :
return
2023-12-14 16:05:47 -05:00
2023-10-22 13:28:50 -04:00
duration = " NULL "
2023-12-14 16:05:47 -05:00
2023-10-22 13:28:50 -04:00
if entry . reason :
reason = entry . reason + " (This action was performed without the bot.) "
2023-12-14 16:05:47 -05:00
2023-10-22 13:28:50 -04:00
else :
reason = " This action was performed without the bot. "
2023-12-14 16:05:47 -05:00
2023-10-22 13:28:50 -04:00
if entry . action == discord . AuditLogAction . kick :
moderation_type = ' KICK '
2023-12-14 16:05:47 -05:00
2023-10-22 13:28:50 -04:00
elif entry . action == discord . AuditLogAction . ban :
moderation_type = ' BAN '
2023-12-14 16:05:47 -05:00
2023-10-22 13:28:50 -04:00
elif entry . action == discord . AuditLogAction . unban :
moderation_type = ' UNBAN '
2023-12-14 16:05:47 -05:00
2023-10-22 13:28:50 -04:00
elif entry . action == discord . AuditLogAction . member_update :
if entry . after . timed_out_until is not None :
timed_out_until_aware = entry . after . timed_out_until . replace ( tzinfo = timezone . utc )
duration_datetime = timed_out_until_aware - datetime . now ( tz = timezone . utc )
minutes = round ( duration_datetime . total_seconds ( ) / 60 )
duration = timedelta ( minutes = minutes )
moderation_type = ' MUTE '
else :
moderation_type = ' UNMUTE '
else :
return
2023-12-14 16:05:47 -05:00
2023-12-13 15:15:30 -05:00
await self . mysql_log ( entry . guild . id , entry . user . id , moderation_type , entry . target . id , 0 , duration , reason )
2023-10-04 11:31:21 -04:00
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 '
] )
2023-12-14 16:05:47 -05:00
2023-10-04 09:11:49 -04:00
if conf :
2023-10-04 09:29:49 -04:00
raise LookupError ( " MySQL connection details not set properly! " )
2023-12-14 16:05:47 -05:00
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
)
2023-12-14 16:05:47 -05:00
2023-10-04 09:20:39 -04:00
return connection
2023-12-14 16:05:47 -05:00
2023-10-04 09:20:39 -04:00
except mysql . connector . ProgrammingError as e :
2023-10-06 10:25:13 -04:00
self . logger . 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 ( )
2023-12-14 16:05:47 -05:00
2023-10-04 09:11:49 -04:00
try :
2023-10-04 16:37:59 -04:00
cursor . execute ( f " SELECT * FROM `moderation_ { guild . id } ` " )
2023-10-06 10:25:13 -04:00
self . logger . info ( " MySQL Table exists for server %s ( %s ) " , guild . name , guild . id )
2023-12-14 16:05:47 -05:00
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 ,
2023-12-13 03:06:26 -05:00
role_id LONGTEXT ,
2023-10-04 09:11:49 -04:00
duration LONGTEXT ,
end_timestamp INT ,
reason LONGTEXT ,
resolved BOOL NOT NULL ,
2023-10-06 10:07:52 -04:00
resolved_by LONGTEXT ,
2023-10-04 09:11:49 -04:00
resolve_reason LONGTEXT ,
2023-12-14 15:50:48 -05:00
expired BOOL NOT NULL ,
2023-12-14 16:51:57 -05:00
changes JSON NOT NULL
2023-10-04 09:11:49 -04:00
)
"""
cursor . execute ( query )
2023-12-14 16:05:47 -05:00
2023-10-06 16:17:26 -04:00
index_query_1 = " CREATE INDEX idx_target_id ON moderation_ %s (target_id(25)); "
2023-10-06 16:18:15 -04:00
cursor . execute ( index_query_1 , ( guild . id , ) )
2023-10-06 16:17:26 -04:00
index_query_2 = " CREATE INDEX idx_moderator_id ON moderation_ %s (moderator_id(25)); "
2023-10-06 16:18:15 -04:00
cursor . execute ( index_query_2 , ( guild . id , ) )
2023-10-06 16:17:26 -04:00
index_query_3 = " CREATE INDEX idx_moderation_id ON moderation_ %s (moderation_id); "
2023-10-06 16:18:15 -04:00
cursor . execute ( index_query_3 , ( guild . id , ) )
2023-12-14 16:05:47 -05:00
2023-10-04 09:11:49 -04:00
insert_query = f """
2023-10-04 16:37:59 -04:00
INSERT INTO ` moderation_ { guild . id } `
2023-12-14 15:50:48 -05:00
( moderation_id , timestamp , moderation_type , target_id , moderator_id , role_id , duration , end_timestamp , reason , resolved , resolved_by , resolve_reason , expired , changes )
VALUES ( % s , % s , % s , % s , % s , % s , % s , % s , % s , % s , % s , % s , % s , % s )
2023-10-04 09:11:49 -04:00
"""
2023-12-14 16:54:58 -05:00
insert_values = ( 0 , 0 , " NULL " , 0 , 0 , 0 , " NULL " , 0 , " NULL " , 0 , " NULL " , " NULL " , 0 , json . dumps ( [ ] ) )
2023-10-04 09:11:49 -04:00
cursor . execute ( insert_query , insert_values )
2023-12-14 16:05:47 -05:00
2023-10-04 09:11:49 -04:00
database . commit ( )
2023-12-14 16:05:47 -05:00
2023-10-06 10:25:13 -04:00
self . logger . info ( " MySQL Table (moderation_ %s ) created for %s ( %s ) " , guild . id , guild . name , guild . id )
2023-12-14 16:05:47 -05:00
2023-10-06 16:17:26 -04:00
database . close ( )
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 = [ ]
2023-12-14 16:05:47 -05:00
2023-09-24 23:55:21 -04:00
for item in config :
if await self . config . item ( ) == " " :
not_found_list . append ( item )
2023-12-14 16:05:47 -05:00
2023-09-24 23:55:21 -04:00
return not_found_list
2023-10-22 14:11:16 -04:00
def check_permissions ( self , user : discord . User , permissions : list , ctx : Union [ commands . Context , discord . Interaction ] = None , guild : discord . Guild = None ) :
2023-10-22 19:29:51 -04:00
""" Checks if a user has a specific permission (or a list of permissions) in a channel. """
2023-10-22 13:55:54 -04:00
if ctx :
2023-10-22 14:10:13 -04:00
member = ctx . guild . get_member ( user . id )
2023-10-22 13:55:54 -04:00
resolved_permissions = ctx . channel . permissions_for ( member )
2023-12-14 16:05:47 -05:00
2023-10-22 14:10:13 -04:00
elif guild :
member = guild . get_member ( user . id )
2023-10-22 13:55:54 -04:00
resolved_permissions = member . guild_permissions
2023-12-14 16:05:47 -05:00
2023-10-22 14:10:13 -04:00
else :
raise ( KeyError )
2023-12-14 16:05:47 -05:00
2023-10-22 13:55:54 -04:00
for permission in permissions :
if not getattr ( resolved_permissions , permission , False ) and not resolved_permissions . administrator is True :
return permission
2023-12-14 16:05:47 -05:00
2023-10-22 13:55:54 -04:00
return False
2023-12-13 03:06:26 -05:00
async def mysql_log ( self , guild_id : str , author_id : str , moderation_type : str , target_id : int , role_id : int , duration , reason : str ) :
2023-10-04 11:04:36 -04:00
timestamp = int ( time . time ( ) )
2023-12-14 16:05:47 -05:00
2023-10-04 11:04:36 -04:00
if duration != " NULL " :
end_timedelta = datetime . fromtimestamp ( timestamp ) + duration
end_timestamp = int ( end_timedelta . timestamp ( ) )
else :
end_timestamp = 0
2023-12-14 16:05:47 -05:00
2023-10-04 11:04:36 -04:00
database = await self . connect ( )
cursor = database . cursor ( )
2023-12-14 16:05:47 -05:00
2023-10-05 09:23:54 -04:00
moderation_id = await self . get_next_case_number ( guild_id = guild_id , cursor = cursor )
2023-12-14 16:05:47 -05:00
2023-12-14 15:50:48 -05:00
sql = f " INSERT INTO `moderation_ { guild_id } ` (moderation_id, timestamp, moderation_type, target_id, moderator_id, role_id, duration, end_timestamp, reason, resolved, resolved_by, resolve_reason, expired, changes) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) "
val = ( moderation_id , timestamp , moderation_type , target_id , author_id , role_id , duration , end_timestamp , f " { reason } " , 0 , " NULL " , " NULL " , 0 , [ ] )
2023-10-04 11:04:36 -04:00
cursor . execute ( sql , val )
2023-12-14 16:05:47 -05:00
2023-10-04 11:04:36 -04:00
database . commit ( )
database . close ( )
2023-12-14 16:05:47 -05:00
2023-12-14 15:50:48 -05:00
self . logger . debug ( " MySQL row inserted into moderation_ %s ! \n %s , %s , %s , %s , %s , %s , %s , %s , %s , 0, NULL, NULL, 0, [] " , guild_id , moderation_id , timestamp , moderation_type , target_id , author_id , role_id , duration , end_timestamp , reason )
2023-12-14 16:05:47 -05:00
2023-10-23 20:09:17 -04:00
return moderation_id
2023-10-04 11:04:36 -04:00
2023-10-05 09:23:54 -04:00
async def get_next_case_number ( self , guild_id : str , cursor = None ) :
2023-10-05 08:42:20 -04:00
""" This method returns the next case number from the MySQL table for a specific guild. """
2023-10-05 09:23:54 -04:00
if not cursor :
database = await self . connect ( )
cursor = database . cursor ( )
2023-10-05 08:42:20 -04:00
cursor . execute ( f " SELECT moderation_id FROM `moderation_ { guild_id } ` ORDER BY moderation_id DESC LIMIT 1 " )
return cursor . fetchone ( ) [ 0 ] + 1
2023-10-06 13:22:30 -04:00
def generate_dict ( self , result ) :
case : dict = {
" moderation_id " : result [ 0 ] ,
" timestamp " : result [ 1 ] ,
" moderation_type " : result [ 2 ] ,
" target_id " : result [ 3 ] ,
" moderator_id " : result [ 4 ] ,
2023-12-13 03:06:26 -05:00
" role_id " : result [ 5 ] ,
" duration " : result [ 6 ] ,
" end_timestamp " : result [ 7 ] ,
" reason " : result [ 8 ] ,
" resolved " : result [ 9 ] ,
" resolved_by " : result [ 10 ] ,
" resolve_reason " : result [ 11 ] ,
2023-12-14 15:50:48 -05:00
" expired " : result [ 12 ] ,
2023-12-14 16:54:58 -05:00
" changes " : json . loads ( result [ 13 ] )
2023-10-06 13:22:30 -04:00
}
return case
2023-10-06 09:45:32 -04:00
async def fetch_user_dict ( self , interaction : discord . Interaction , user_id : str ) :
""" This method returns a dictionary containing either user information or a standard deleted user template. """
try :
2023-12-14 14:24:00 -05:00
user = interaction . client . get_user ( user_id )
if user is None :
user = await interaction . client . fetch_user ( user_id )
2023-12-14 16:05:47 -05:00
2023-10-06 09:45:32 -04:00
user_dict = {
' id ' : user . id ,
' name ' : user . name ,
' discriminator ' : user . discriminator
}
2023-12-14 16:05:47 -05:00
2023-10-06 09:45:32 -04:00
except discord . errors . NotFound :
user_dict = {
' id ' : user_id ,
' name ' : ' Deleted User ' ,
' discriminator ' : ' 0 '
}
2023-12-14 16:05:47 -05:00
2023-10-06 09:45:32 -04:00
return user_dict
2023-12-13 15:07:04 -05:00
async def fetch_role_dict ( self , interaction : discord . Interaction , role_id : str ) :
""" This method returns a dictionary containing either role information or a standard deleted role template. """
try :
role = interaction . guild . get_role ( role_id )
2023-12-14 16:05:47 -05:00
2023-12-13 15:07:04 -05:00
role_dict = {
' id ' : role . id ,
' name ' : role . name
}
2023-12-14 16:05:47 -05:00
2023-12-13 15:07:04 -05:00
except discord . errors . NotFound :
role_dict = {
' id ' : role_id ,
' name ' : ' Deleted Role '
}
2023-12-14 16:05:47 -05:00
2023-12-13 15:07:04 -05:00
return role_dict
2023-10-23 20:09:17 -04:00
async def embed_factory ( self , embed_type : str , / , interaction : discord . Interaction = None , case_dict : dict = None , guild : discord . Guild = None , reason : str = None , moderation_type : str = None , response : discord . InteractionMessage = None , duration : timedelta = None , resolved : bool = False ) :
2023-10-05 09:21:40 -04:00
""" This method creates an embed from set parameters, meant for either moderation logging or contacting the moderated user.
2023-10-05 09:47:53 -04:00
Valid arguments for ' embed_type ' :
2023-10-05 09:21:40 -04:00
- ' message '
2023-10-23 20:09:17 -04:00
- ' log ' - WIP
2023-10-06 09:34:30 -04:00
- ' case '
Required arguments for ' message ' :
- guild
- reason
- moderation_type
- response
- duration ( optional )
2023-10-23 20:09:17 -04:00
Required arguments for ' log ' :
- interaction
- case_dict
- resolved ( optional )
2023-10-06 09:34:30 -04:00
Required arguments for ' case ' :
- interaction
- case_dict """
2023-10-05 09:47:53 -04:00
if embed_type == ' message ' :
2023-12-14 16:05:47 -05:00
2023-10-05 11:09:39 -04:00
if moderation_type in [ " kicked " , " banned " , " tempbanned " , " unbanned " ] :
2023-10-05 09:21:40 -04:00
guild_name = guild . name
else :
2023-10-05 09:28:42 -04:00
guild_name = f " [ { guild . name } ]( { response . jump_url } ) "
2023-12-14 16:05:47 -05:00
2023-10-05 09:21:40 -04:00
if moderation_type in [ " tempbanned " , " muted " ] and duration :
embed_duration = f " for { humanize . precisedelta ( duration ) } "
else :
embed_duration = " "
2023-12-14 16:05:47 -05:00
2023-10-05 10:46:52 -04:00
if moderation_type == " note " :
2023-12-14 16:05:47 -05:00
embed_desc = " received a "
2023-10-05 10:46:52 -04:00
else :
embed_desc = " been "
2023-12-14 16:05:47 -05:00
2023-10-05 10:46:52 -04:00
embed = discord . Embed ( title = str . title ( moderation_type ) , description = f " You have { embed_desc } { moderation_type } { embed_duration } in { guild_name } . " , color = await self . bot . get_embed_color ( None ) , timestamp = datetime . now ( ) )
2023-10-05 09:21:40 -04:00
embed . add_field ( name = ' Reason ' , value = f " ` { reason } ` " )
embed . set_author ( name = guild . name , icon_url = guild . icon . url )
embed . set_footer ( text = f " Case # { await self . get_next_case_number ( guild . id ) } " , icon_url = " https://cdn.discordapp.com/attachments/1070822161389994054/1159469476773904414/arrow-right-circle-icon-512x512-2p1e2aaw.png?ex=65312319&is=651eae19&hm=3cebdd28e805c13a79ec48ef87c32ca532ffa6b9ede2e48d0cf8e5e81f3a6818& " )
2023-12-14 16:05:47 -05:00
2023-10-05 09:21:40 -04:00
return embed
2023-10-06 09:45:32 -04:00
2023-10-06 09:34:30 -04:00
if embed_type == ' case ' :
2023-10-06 09:45:32 -04:00
target_user = await self . fetch_user_dict ( interaction , case_dict [ ' target_id ' ] )
moderator_user = await self . fetch_user_dict ( interaction , case_dict [ ' moderator_id ' ] )
2023-12-14 16:05:47 -05:00
2023-10-06 10:50:59 -04:00
target_name = f " ` { target_user [ ' name ' ] } ` " if target_user [ ' discriminator ' ] == " 0 " else f " ` { target_user [ ' name ' ] } # { target_user [ ' discriminator ' ] } ` "
2023-12-13 03:06:26 -05:00
moderator_name = f " ` { moderator_user [ ' name ' ] } ` " if moderator_user [ ' discriminator ' ] == " 0 " else f " ` { moderator_user [ ' name ' ] } # { moderator_user [ ' discriminator ' ] } ` "
2023-12-14 16:05:47 -05:00
2023-10-06 09:34:30 -04:00
embed = discord . Embed ( title = f " 📕 Case # { case_dict [ ' moderation_id ' ] } " , color = await self . bot . get_embed_color ( None ) )
embed . description = f " **Type:** { str . title ( case_dict [ ' moderation_type ' ] ) } \n **Target:** { target_name } ( { target_user [ ' id ' ] } ) \n **Moderator:** { moderator_name } ( { moderator_user [ ' id ' ] } ) \n **Resolved:** { bool ( case_dict [ ' resolved ' ] ) } \n **Timestamp:** <t: { case_dict [ ' timestamp ' ] } > | <t: { case_dict [ ' timestamp ' ] } :R> "
2023-12-14 16:05:47 -05:00
2023-10-06 09:34:30 -04:00
if case_dict [ ' duration ' ] != ' NULL ' :
td = timedelta ( * * { unit : int ( val ) for unit , val in zip ( [ " hours " , " minutes " , " seconds " ] , case_dict [ " duration " ] . split ( " : " ) ) } )
2023-12-13 15:07:04 -05:00
duration_embed = f " { humanize . precisedelta ( td ) } | <t: { case_dict [ ' end_timestamp ' ] } :R> " if bool ( case_dict [ ' expired ' ] ) is False else str ( humanize . precisedelta ( td ) )
2023-10-06 09:34:30 -04:00
embed . description = embed . description + f " \n **Duration:** { duration_embed } \n **Expired:** { bool ( case_dict [ ' expired ' ] ) } "
2023-12-14 16:05:47 -05:00
2023-10-06 09:34:30 -04:00
embed . add_field ( name = ' Reason ' , value = f " ``` { case_dict [ ' reason ' ] } ``` " , inline = False )
2023-12-14 16:05:47 -05:00
2023-10-06 09:34:30 -04:00
if case_dict [ ' resolved ' ] == 1 :
2023-10-06 10:07:52 -04:00
resolved_user = await self . fetch_user_dict ( interaction , case_dict [ ' resolved_by ' ] )
2023-12-13 03:06:26 -05:00
resolved_name = f " ` { resolved_user [ ' name ' ] } ` " if resolved_user [ ' discriminator ' ] == " 0 " else f " ` { resolved_user [ ' name ' ] } # { resolved_user [ ' discriminator ' ] } ` "
2023-10-06 10:07:52 -04:00
embed . add_field ( name = ' Resolve Reason ' , value = f " Resolved by { resolved_name } ( { resolved_user [ ' id ' ] } ) for: \n ``` { case_dict [ ' resolve_reason ' ] } ``` " , inline = False )
2023-12-14 16:05:47 -05:00
2023-10-06 09:34:30 -04:00
return embed
2023-10-06 09:45:32 -04:00
2023-10-23 20:09:17 -04:00
if embed_type == ' log ' :
if resolved :
target_user = await self . fetch_user_dict ( interaction , case_dict [ ' target_id ' ] )
moderator_user = await self . fetch_user_dict ( interaction , case_dict [ ' moderator_id ' ] )
2023-12-14 16:05:47 -05:00
2023-10-23 20:09:17 -04:00
target_name = f " ` { target_user [ ' name ' ] } ` " if target_user [ ' discriminator ' ] == " 0 " else f " ` { target_user [ ' name ' ] } # { target_user [ ' discriminator ' ] } ` "
moderator_name = moderator_user [ ' name ' ] if moderator_user [ ' discriminator ' ] == " 0 " else f " { moderator_user [ ' name ' ] } # { moderator_user [ ' discriminator ' ] } "
2023-12-14 16:05:47 -05:00
2023-10-23 20:09:17 -04:00
embed = discord . Embed ( title = f " 📕 Case # { case_dict [ ' moderation_id ' ] } Resolved " , color = await self . bot . get_embed_color ( None ) )
2023-12-14 16:05:47 -05:00
2023-10-23 20:09:17 -04:00
embed . description = f " **Type:** { str . title ( case_dict [ ' moderation_type ' ] ) } \n **Target:** { target_name } ( { target_user [ ' id ' ] } ) \n **Moderator:** { moderator_name } ( { moderator_user [ ' id ' ] } ) \n **Timestamp:** <t: { case_dict [ ' timestamp ' ] } > | <t: { case_dict [ ' timestamp ' ] } :R> "
2023-12-14 16:05:47 -05:00
2023-10-23 20:09:17 -04:00
if case_dict [ ' duration ' ] != ' NULL ' :
td = timedelta ( * * { unit : int ( val ) for unit , val in zip ( [ " hours " , " minutes " , " seconds " ] , case_dict [ " duration " ] . split ( " : " ) ) } )
duration_embed = f " { humanize . precisedelta ( td ) } | <t: { case_dict [ ' end_timestamp ' ] } :R> " if case_dict [ " expired " ] == ' 0 ' else str ( humanize . precisedelta ( td ) )
embed . description = embed . description + f " \n **Duration:** { duration_embed } \n **Expired:** { bool ( case_dict [ ' expired ' ] ) } "
2023-12-14 16:05:47 -05:00
2023-10-23 20:09:17 -04:00
embed . add_field ( name = ' Reason ' , value = f " ``` { case_dict [ ' reason ' ] } ``` " , inline = False )
2023-12-14 16:05:47 -05:00
2023-10-23 20:09:17 -04:00
resolved_user = await self . fetch_user_dict ( interaction , case_dict [ ' resolved_by ' ] )
resolved_name = resolved_user [ ' name ' ] if resolved_user [ ' discriminator ' ] == " 0 " else f " { resolved_user [ ' name ' ] } # { resolved_user [ ' discriminator ' ] } "
embed . add_field ( name = ' Resolve Reason ' , value = f " Resolved by { resolved_name } ( { resolved_user [ ' id ' ] } ) for: \n ``` { case_dict [ ' resolve_reason ' ] } ``` " , inline = False )
else :
target_user = await self . fetch_user_dict ( interaction , case_dict [ ' target_id ' ] )
moderator_user = await self . fetch_user_dict ( interaction , case_dict [ ' moderator_id ' ] )
2023-12-14 16:05:47 -05:00
2023-10-23 20:09:17 -04:00
target_name = f " ` { target_user [ ' name ' ] } ` " if target_user [ ' discriminator ' ] == " 0 " else f " ` { target_user [ ' name ' ] } # { target_user [ ' discriminator ' ] } ` "
moderator_name = moderator_user [ ' name ' ] if moderator_user [ ' discriminator ' ] == " 0 " else f " { moderator_user [ ' name ' ] } # { moderator_user [ ' discriminator ' ] } "
2023-12-14 16:05:47 -05:00
2023-10-23 20:09:17 -04:00
embed = discord . Embed ( title = f " 📕 Case # { case_dict [ ' moderation_id ' ] } " , color = await self . bot . get_embed_color ( None ) )
embed . description = f " **Type:** { str . title ( case_dict [ ' moderation_type ' ] ) } \n **Target:** { target_name } ( { target_user [ ' id ' ] } ) \n **Moderator:** { moderator_name } ( { moderator_user [ ' id ' ] } ) \n **Timestamp:** <t: { case_dict [ ' timestamp ' ] } > | <t: { case_dict [ ' timestamp ' ] } :R> "
2023-12-14 16:05:47 -05:00
2023-10-23 20:09:17 -04:00
if case_dict [ ' duration ' ] != ' NULL ' :
td = timedelta ( * * { unit : int ( val ) for unit , val in zip ( [ " hours " , " minutes " , " seconds " ] , case_dict [ " duration " ] . split ( " : " ) ) } )
embed . description = embed . description + f " \n **Duration:** { humanize . precisedelta ( td ) } | <t: { case_dict [ ' end_timestamp ' ] } :R> "
2023-12-14 16:05:47 -05:00
2023-10-23 20:09:17 -04:00
embed . add_field ( name = ' Reason ' , value = f " ``` { case_dict [ ' reason ' ] } ``` " , inline = False )
2023-10-24 00:41:29 -04:00
return embed
2023-10-23 20:09:17 -04:00
2023-10-05 09:47:53 -04:00
raise ( TypeError ( " ' type ' argument is invalid! " ) )
2023-10-05 09:21:40 -04:00
2023-10-23 20:09:17 -04:00
async def fetch_case ( self , moderation_id : int , guild_id : str ) :
""" This method fetches a case from the database and returns the case ' s dictionary. """
database = await self . connect ( )
cursor = database . cursor ( )
2023-12-14 16:05:47 -05:00
2023-10-23 20:09:17 -04:00
query = " SELECT * FROM moderation_ %s WHERE moderation_id = %s ; "
cursor . execute ( query , ( guild_id , moderation_id ) )
result = cursor . fetchone ( )
2023-12-14 16:05:47 -05:00
2023-10-23 20:09:17 -04:00
cursor . close ( )
database . close ( )
2023-12-14 16:05:47 -05:00
2023-10-23 20:09:17 -04:00
return self . generate_dict ( result )
async def log ( self , interaction : discord . Interaction , moderation_id : int , resolved : bool = False ) :
""" This method sends a message to the guild ' s configured logging channel when an infraction takes place. """
2023-10-23 20:25:31 -04:00
logging_channel_id = await self . config . guild ( interaction . guild ) . log_channel ( )
2023-10-23 20:09:17 -04:00
if logging_channel_id != " " :
logging_channel = interaction . guild . get_channel ( logging_channel_id )
2023-12-14 16:05:47 -05:00
2023-10-23 20:09:17 -04:00
case = await self . fetch_case ( moderation_id , interaction . guild . id )
if case :
embed = await self . embed_factory ( ' log ' , interaction = interaction , case_dict = case , resolved = resolved )
try :
await logging_channel . send ( embed = embed )
except discord . errors . Forbidden :
return
2023-12-14 14:24:00 -05:00
#######################################################################################################################
### COMMANDS
#######################################################################################################################
2023-10-05 10:46:52 -04:00
@app_commands.command ( name = " note " )
2023-10-06 23:09:55 -04:00
async def note ( self , interaction : discord . Interaction , target : discord . User , reason : str , silent : bool = None ) :
""" Add a note to a user.
Parameters
- - - - - - - - - - -
target : discord . User
Who are you noting ?
reason : str
Why are you noting this user ?
silent : bool
Should the user be messaged ? """
2023-10-22 14:04:06 -04:00
if interaction . guild . get_member ( target . id ) :
target_member = interaction . guild . get_member ( target . id )
if interaction . guild . get_member ( interaction . client . user . id ) . top_role < = target_member . top_role :
await interaction . response . send_message ( content = " You cannot moderate members with a role higher than the bot! " , ephemeral = True )
return
if interaction . user . top_role < = target_member . top_role :
await interaction . response . send_message ( content = " You cannot moderate members with a higher role than you! " , ephemeral = True )
return
2023-12-14 16:05:47 -05:00
2023-12-13 16:59:36 -05:00
await interaction . response . send_message ( content = f " { target . mention } has recieved a note! \n **Reason** - ` { reason } ` " )
2023-12-14 16:05:47 -05:00
2023-10-05 20:06:07 -04:00
if silent is None :
2023-10-05 20:12:00 -04:00
silent = not await self . config . guild ( interaction . guild ) . dm_users ( )
2023-10-05 20:06:07 -04:00
if silent is False :
try :
2023-10-06 09:34:30 -04:00
embed = await self . embed_factory ( ' message ' , guild = interaction . guild , reason = reason , moderation_type = ' note ' , response = await interaction . original_response ( ) )
2023-10-05 20:06:07 -04:00
await target . send ( embed = embed )
except discord . errors . HTTPException :
pass
2023-12-14 16:05:47 -05:00
2023-12-13 03:06:26 -05:00
moderation_id = await self . mysql_log ( interaction . guild . id , interaction . user . id , ' NOTE ' , target . id , 0 , ' NULL ' , reason )
2023-12-13 16:59:36 -05:00
await interaction . edit_original_response ( content = f " { target . mention } has received a note! (Case `# { moderation_id } `) \n **Reason** - ` { reason } ` " )
2023-10-23 20:09:17 -04:00
await self . log ( interaction , moderation_id )
2023-10-05 10:46:52 -04:00
2023-10-05 08:42:20 -04:00
@app_commands.command ( name = " warn " )
2023-10-05 20:06:07 -04:00
async def warn ( self , interaction : discord . Interaction , target : discord . Member , reason : str , silent : bool = None ) :
2023-10-06 23:09:55 -04:00
""" Warn a user.
Parameters
- - - - - - - - - - -
target : discord . Member
Who are you warning ?
reason : str
Why are you warning this user ?
silent : bool
Should the user be messaged ? """
2023-10-22 14:04:06 -04:00
if interaction . guild . get_member ( target . id ) :
target_member = interaction . guild . get_member ( target . id )
if interaction . guild . get_member ( interaction . client . user . id ) . top_role < = target_member . top_role :
await interaction . response . send_message ( content = " You cannot moderate members with a role higher than the bot! " , ephemeral = True )
return
if interaction . user . top_role < = target_member . top_role :
await interaction . response . send_message ( content = " You cannot moderate members with a higher role than you! " , ephemeral = True )
return
2023-12-14 16:05:47 -05:00
2023-12-13 16:59:36 -05:00
await interaction . response . send_message ( content = f " { target . mention } has been warned! \n **Reason** - ` { reason } ` " )
2023-12-14 16:05:47 -05:00
2023-10-05 20:06:07 -04:00
if silent is None :
2023-10-05 20:12:00 -04:00
silent = not await self . config . guild ( interaction . guild ) . dm_users ( )
2023-10-05 20:06:07 -04:00
if silent is False :
try :
2023-10-06 09:34:30 -04:00
embed = await self . embed_factory ( ' message ' , guild = interaction . guild , reason = reason , moderation_type = ' warned ' , response = await interaction . original_response ( ) )
2023-10-05 20:06:07 -04:00
await target . send ( embed = embed )
except discord . errors . HTTPException :
pass
2023-12-14 16:05:47 -05:00
2023-12-13 03:06:26 -05:00
moderation_id = await self . mysql_log ( interaction . guild . id , interaction . user . id , ' WARN ' , target . id , 0 , ' NULL ' , reason )
2023-12-13 16:59:36 -05:00
await interaction . edit_original_response ( content = f " { target . mention } has been warned! (Case `# { moderation_id } `) \n **Reason** - ` { reason } ` " )
2023-10-23 20:09:17 -04:00
await self . log ( interaction , moderation_id )
2023-10-04 16:39:58 -04:00
2023-10-05 08:43:11 -04:00
@app_commands.command ( name = " mute " )
2023-10-05 20:06:07 -04:00
async def mute ( self , interaction : discord . Interaction , target : discord . Member , duration : str , reason : str , silent : bool = None ) :
2023-10-06 23:09:55 -04:00
""" Mute a user.
Parameters
- - - - - - - - - - -
target : discord . Member
Who are you unbanning ?
duration : str
How long are you muting this user for ?
reason : str
Why are you unbanning this user ?
silent : bool
Should the user be messaged ? """
2023-10-22 14:04:06 -04:00
if interaction . guild . get_member ( target . id ) :
target_member = interaction . guild . get_member ( target . id )
if interaction . guild . get_member ( interaction . client . user . id ) . top_role < = target_member . top_role :
await interaction . response . send_message ( content = " You cannot moderate members with a role higher than the bot! " , ephemeral = True )
return
if interaction . user . top_role < = target_member . top_role :
await interaction . response . send_message ( content = " You cannot moderate members with a higher role than you! " , ephemeral = True )
return
2023-12-14 16:05:47 -05:00
2023-10-22 13:55:54 -04:00
permissions = self . check_permissions ( interaction . client . user , [ ' moderate_members ' ] , interaction )
if permissions :
await interaction . response . send_message ( f " I do not have the ` { permissions } ` permission, required for this action. " , ephemeral = True )
return
2023-10-04 13:16:03 -04:00
if target . is_timed_out ( ) is True :
2023-10-05 08:42:20 -04:00
await interaction . response . send_message ( f " { target . mention } is already muted! " , allowed_mentions = discord . AllowedMentions ( users = False ) , ephemeral = True )
2023-10-04 13:16:03 -04:00
return
2023-12-14 16:05:47 -05:00
2023-10-04 12:44:21 -04:00
try :
parsed_time = parse ( sval = duration , as_timedelta = True , raise_exception = True )
except ValueError :
2023-10-05 09:47:53 -04:00
await interaction . response . send_message ( " Please provide a valid duration! " , ephemeral = True )
2023-10-04 12:44:21 -04:00
return
2023-12-14 16:05:47 -05:00
2023-10-04 21:51:54 -04:00
if parsed_time . total_seconds ( ) / 1000 > 2419200000 :
2023-10-05 08:42:20 -04:00
await interaction . response . send_message ( " Please provide a duration that is less than 28 days. " )
2023-10-04 21:39:36 -04:00
return
2023-12-14 16:05:47 -05:00
2023-10-05 09:40:41 -04:00
await target . timeout ( parsed_time , reason = f " Muted by { interaction . user . id } for: { reason } " )
2023-12-14 16:05:47 -05:00
2023-12-13 16:59:36 -05:00
await interaction . response . send_message ( content = f " { target . mention } has been muted for { humanize . precisedelta ( parsed_time ) } ! \n **Reason** - ` { reason } ` " )
2023-12-14 16:05:47 -05:00
2023-10-05 20:06:07 -04:00
if silent is None :
2023-10-05 20:12:00 -04:00
silent = not await self . config . guild ( interaction . guild ) . dm_users ( )
2023-10-05 20:06:07 -04:00
if silent is False :
try :
2023-10-06 09:34:30 -04:00
embed = await self . embed_factory ( ' message ' , guild = interaction . guild , reason = reason , moderation_type = ' muted ' , response = await interaction . original_response ( ) , duration = parsed_time )
2023-10-05 20:06:07 -04:00
await target . send ( embed = embed )
except discord . errors . HTTPException :
pass
2023-12-14 16:05:47 -05:00
2023-12-13 03:06:26 -05:00
moderation_id = await self . mysql_log ( interaction . guild . id , interaction . user . id , ' MUTE ' , target . id , 0 , parsed_time , reason )
2023-12-14 14:26:37 -05:00
await interaction . edit_original_response ( content = f " { target . mention } has been muted for { humanize . precisedelta ( parsed_time ) } ! (Case `# { moderation_id } `) \n **Reason** - ` { reason } ` " )
2023-10-23 20:09:17 -04:00
await self . log ( interaction , moderation_id )
2023-10-04 12:44:21 -04:00
2023-10-05 08:43:11 -04:00
@app_commands.command ( name = " unmute " )
2023-10-05 20:06:07 -04:00
async def unmute ( self , interaction : discord . Interaction , target : discord . Member , reason : str = None , silent : bool = None ) :
2023-10-06 23:09:55 -04:00
""" Unmute a user.
Parameters
- - - - - - - - - - -
target : discord . user
Who are you unmuting ?
reason : str
Why are you unmuting this user ?
silent : bool
Should the user be messaged ? """
2023-10-22 14:04:06 -04:00
if interaction . guild . get_member ( target . id ) :
target_member = interaction . guild . get_member ( target . id )
if interaction . guild . get_member ( interaction . client . user . id ) . top_role < = target_member . top_role :
await interaction . response . send_message ( content = " You cannot moderate members with a role higher than the bot! " , ephemeral = True )
return
if interaction . user . top_role < = target_member . top_role :
await interaction . response . send_message ( content = " You cannot moderate members with a higher role than you! " , ephemeral = True )
return
2023-12-14 16:05:47 -05:00
2023-10-22 13:55:54 -04:00
permissions = self . check_permissions ( interaction . client . user , [ ' moderate_members ' ] , interaction )
if permissions :
await interaction . response . send_message ( f " I do not have the ` { permissions } ` permission, required for this action. " , ephemeral = True )
return
2023-10-04 16:43:15 -04:00
if target . is_timed_out ( ) is False :
2023-10-05 08:42:20 -04:00
await interaction . response . send_message ( f " { target . mention } is not muted! " , allowed_mentions = discord . AllowedMentions ( users = False ) , ephemeral = True )
2023-10-04 16:43:15 -04:00
return
2023-10-05 08:42:20 -04:00
if reason :
await target . timeout ( None , reason = f " Unmuted by { interaction . user . id } for: { reason } " )
else :
2023-10-05 11:09:39 -04:00
await target . timeout ( None , reason = f " Unbanned by { interaction . user . id } " )
2023-10-04 16:43:15 -04:00
reason = " No reason given. "
2023-12-14 16:05:47 -05:00
2023-12-13 16:59:36 -05:00
await interaction . response . send_message ( content = f " { target . mention } has been unmuted! \n **Reason** - ` { reason } ` " )
2023-12-14 16:05:47 -05:00
2023-10-05 20:06:07 -04:00
if silent is None :
2023-10-05 20:12:00 -04:00
silent = not await self . config . guild ( interaction . guild ) . dm_users ( )
2023-10-05 20:06:07 -04:00
if silent is False :
try :
2023-10-06 09:34:30 -04:00
embed = await self . embed_factory ( ' message ' , guild = interaction . guild , reason = reason , moderation_type = ' unmuted ' , response = await interaction . original_response ( ) )
2023-10-05 20:06:07 -04:00
await target . send ( embed = embed )
except discord . errors . HTTPException :
pass
2023-12-14 16:05:47 -05:00
2023-12-13 03:06:26 -05:00
moderation_id = await self . mysql_log ( interaction . guild . id , interaction . user . id , ' UNMUTE ' , target . id , 0 , ' NULL ' , reason )
2023-12-13 16:59:36 -05:00
await interaction . edit_original_response ( content = f " { target . mention } has been unmuted! (Case `# { moderation_id } `) \n **Reason** - ` { reason } ` " )
2023-10-23 20:09:17 -04:00
await self . log ( interaction , moderation_id )
2023-10-05 08:42:20 -04:00
@app_commands.command ( name = " kick " )
2023-10-05 20:06:07 -04:00
async def kick ( self , interaction : discord . Interaction , target : discord . Member , reason : str , silent : bool = None ) :
2023-10-06 23:09:55 -04:00
""" Kick a user.
Parameters
- - - - - - - - - - -
target : discord . user
Who are you kicking ?
reason : str
Why are you kicking this user ?
silent : bool
Should the user be messaged ? """
2023-10-22 14:04:06 -04:00
if interaction . guild . get_member ( target . id ) :
target_member = interaction . guild . get_member ( target . id )
if interaction . guild . get_member ( interaction . client . user . id ) . top_role < = target_member . top_role :
await interaction . response . send_message ( content = " You cannot moderate members with a role higher than the bot! " , ephemeral = True )
return
if interaction . user . top_role < = target_member . top_role :
await interaction . response . send_message ( content = " You cannot moderate members with a higher role than you! " , ephemeral = True )
return
2023-12-14 16:05:47 -05:00
2023-10-22 13:55:54 -04:00
permissions = self . check_permissions ( interaction . client . user , [ ' kick_members ' ] , interaction )
if permissions :
await interaction . response . send_message ( f " I do not have the ` { permissions } ` permission, required for this action. " , ephemeral = True )
return
2023-12-14 16:05:47 -05:00
2023-12-13 16:59:36 -05:00
await interaction . response . send_message ( content = f " { target . mention } has been kicked! \n **Reason** - ` { reason } ` " )
2023-12-14 16:05:47 -05:00
2023-10-05 20:06:07 -04:00
if silent is None :
2023-10-05 20:12:00 -04:00
silent = not await self . config . guild ( interaction . guild ) . dm_users ( )
2023-10-05 20:06:07 -04:00
if silent is False :
try :
2023-10-06 09:34:30 -04:00
embed = await self . embed_factory ( ' message ' , guild = interaction . guild , reason = reason , moderation_type = ' kicked ' , response = await interaction . original_response ( ) )
2023-10-05 20:06:07 -04:00
await target . send ( embed = embed )
except discord . errors . HTTPException :
pass
2023-12-14 16:05:47 -05:00
2023-10-05 08:42:20 -04:00
await target . kick ( f " Kicked by { interaction . user . id } for: { reason } " )
2023-12-14 16:05:47 -05:00
2023-12-13 03:06:26 -05:00
moderation_id = await self . mysql_log ( interaction . guild . id , interaction . user . id , ' KICK ' , target . id , 0 , ' NULL ' , reason )
2023-12-13 16:59:36 -05:00
await interaction . edit_original_response ( content = f " { target . mention } has been kicked! (Case `# { moderation_id } `) \n **Reason** - ` { reason } ` " )
2023-10-23 20:09:17 -04:00
await self . log ( interaction , moderation_id )
2023-10-04 16:43:15 -04:00
2023-10-05 11:09:39 -04:00
@app_commands.command ( name = " ban " )
2023-10-05 11:12:21 -04:00
@app_commands.choices ( delete_messages = [
2023-10-05 11:09:39 -04:00
Choice ( name = " None " , value = 0 ) ,
Choice ( name = ' 1 Hour ' , value = 3600 ) ,
Choice ( name = ' 12 Hours ' , value = 43200 ) ,
Choice ( name = ' 1 Day ' , value = 86400 ) ,
Choice ( name = ' 3 Days ' , value = 259200 ) ,
Choice ( name = ' 7 Days ' , value = 604800 ) ,
] )
2023-10-06 23:09:55 -04:00
async def ban ( self , interaction : discord . Interaction , target : discord . User , reason : str , duration : str = None , delete_messages : Choice [ int ] = 0 , silent : bool = None ) :
""" Ban a user.
Parameters
- - - - - - - - - - -
target : discord . user
Who are you banning ?
duration : str
How long are you banning this user for ?
reason : str
Why are you banning this user ?
delete_messages : Choices [ int ]
How many days of messages to delete ?
silent : bool
Should the user be messaged ? """
2023-10-22 14:04:06 -04:00
if interaction . guild . get_member ( target . id ) :
target_member = interaction . guild . get_member ( target . id )
if interaction . guild . get_member ( interaction . client . user . id ) . top_role < = target_member . top_role :
await interaction . response . send_message ( content = " You cannot moderate members with a role higher than the bot! " , ephemeral = True )
return
if interaction . user . top_role < = target_member . top_role :
await interaction . response . send_message ( content = " You cannot moderate members with a higher role than you! " , ephemeral = True )
return
2023-12-14 16:05:47 -05:00
2023-10-22 13:55:54 -04:00
permissions = self . check_permissions ( interaction . client . user , [ ' ban_members ' ] , interaction )
2023-12-14 16:05:47 -05:00
2023-10-22 13:55:54 -04:00
if permissions :
await interaction . response . send_message ( f " I do not have the ` { permissions } ` permission, required for this action. " , ephemeral = True )
return
2023-10-05 11:09:39 -04:00
try :
2023-10-05 11:16:21 -04:00
await interaction . guild . fetch_ban ( target )
2023-10-05 11:09:39 -04:00
await interaction . response . send_message ( content = f " { target . mention } is already banned! " , ephemeral = True )
return
except discord . errors . NotFound :
pass
2023-12-14 16:05:47 -05:00
2023-10-05 11:09:39 -04:00
if duration :
try :
parsed_time = parse ( sval = duration , as_timedelta = True , raise_exception = True )
except ValueError :
await interaction . response . send_message ( " Please provide a valid duration! " , ephemeral = True )
return
2023-12-14 16:05:47 -05:00
2023-12-13 16:59:36 -05:00
await interaction . response . send_message ( content = f " { target . mention } has been banned for { humanize . precisedelta ( parsed_time ) } ! \n **Reason** - ` { reason } ` " )
2023-12-14 16:05:47 -05:00
2023-10-05 11:09:39 -04:00
try :
2023-10-06 09:34:30 -04:00
embed = await self . embed_factory ( ' message ' , guild = interaction . guild , reason = reason , moderation_type = ' tempbanned ' , response = await interaction . original_response ( ) , duration = parsed_time )
2023-10-05 11:09:39 -04:00
await target . send ( embed = embed )
except discord . errors . HTTPException :
pass
2023-12-14 16:05:47 -05:00
2023-10-05 16:19:01 -04:00
await interaction . guild . ban ( target , reason = f " Tempbanned by { interaction . user . id } for: { reason } (Duration: { parsed_time } ) " , delete_message_seconds = delete_messages )
2023-12-14 16:05:47 -05:00
2023-12-13 16:54:25 -05:00
moderation_id = await self . mysql_log ( interaction . guild . id , interaction . user . id , ' TEMPBAN ' , target . id , 0 , parsed_time , reason )
2023-12-13 16:59:36 -05:00
await interaction . edit_original_response ( content = f " { target . mention } has been banned for { humanize . precisedelta ( parsed_time ) } ! (Case `# { moderation_id } `) \n **Reason** - ` { reason } ` " )
2023-12-13 16:54:25 -05:00
await self . log ( interaction , moderation_id )
2023-10-05 11:09:39 -04:00
else :
2023-12-13 16:59:36 -05:00
await interaction . response . send_message ( content = f " { target . mention } has been banned! \n **Reason** - ` { reason } ` " )
2023-12-14 16:05:47 -05:00
2023-10-05 20:06:07 -04:00
if silent is None :
2023-10-05 20:12:00 -04:00
silent = not await self . config . guild ( interaction . guild ) . dm_users ( )
2023-10-05 20:06:07 -04:00
if silent is False :
try :
2023-10-06 09:34:30 -04:00
embed = embed = await self . embed_factory ( ' message ' , guild = interaction . guild , reason = reason , moderation_type = ' banned ' , response = await interaction . original_response ( ) )
2023-10-05 20:06:07 -04:00
await target . send ( embed = embed )
except discord . errors . HTTPException :
pass
2023-12-14 16:05:47 -05:00
2023-10-05 11:22:35 -04:00
await interaction . guild . ban ( target , reason = f " Banned by { interaction . user . id } for: { reason } " , delete_message_seconds = delete_messages )
2023-12-14 16:05:47 -05:00
2023-12-13 03:06:26 -05:00
moderation_id = await self . mysql_log ( interaction . guild . id , interaction . user . id , ' BAN ' , target . id , 0 , ' NULL ' , reason )
2023-12-13 16:59:36 -05:00
await interaction . edit_original_response ( content = f " { target . mention } has been banned! (Case `# { moderation_id } `) \n **Reason** - ` { reason } ` " )
2023-10-23 20:09:17 -04:00
await self . log ( interaction , moderation_id )
2023-10-05 11:09:39 -04:00
@app_commands.command ( name = " unban " )
2023-10-06 23:09:55 -04:00
async def unban ( self , interaction : discord . Interaction , target : discord . User , reason : str = None , silent : bool = None ) :
""" Unban a user.
Parameters
- - - - - - - - - - -
target : discord . user
Who are you unbanning ?
reason : str
Why are you unbanning this user ?
silent : bool
Should the user be messaged ? """
2023-10-22 14:04:06 -04:00
if interaction . guild . get_member ( target . id ) :
target_member = interaction . guild . get_member ( target . id )
if interaction . guild . get_member ( interaction . client . user . id ) . top_role < = target_member . top_role :
await interaction . response . send_message ( content = " You cannot moderate members with a role higher than the bot! " , ephemeral = True )
return
if interaction . user . top_role < = target_member . top_role :
await interaction . response . send_message ( content = " You cannot moderate members with a higher role than you! " , ephemeral = True )
return
2023-12-14 16:05:47 -05:00
2023-10-22 14:15:03 -04:00
permissions = self . check_permissions ( interaction . client . user , [ ' ban_members ' ] , interaction )
2023-10-22 13:55:54 -04:00
if permissions :
await interaction . response . send_message ( f " I do not have the ` { permissions } ` permission, required for this action. " , ephemeral = True )
return
2023-10-05 11:17:41 -04:00
try :
await interaction . guild . fetch_ban ( target )
except discord . errors . NotFound :
await interaction . response . send_message ( content = f " { target . mention } is not banned! " , ephemeral = True )
return
2023-12-14 16:05:47 -05:00
2023-10-05 11:09:39 -04:00
if reason :
2023-10-05 11:22:35 -04:00
await interaction . guild . unban ( target , reason = f " Unbanned by { interaction . user . id } for: { reason } " )
2023-10-05 11:09:39 -04:00
else :
2023-10-05 11:22:35 -04:00
await interaction . guild . unban ( target , reason = f " Unbanned by { interaction . user . id } " )
2023-10-05 11:09:39 -04:00
reason = " No reason given. "
2023-12-14 16:05:47 -05:00
2023-12-13 16:59:36 -05:00
await interaction . response . send_message ( content = f " { target . mention } has been unbanned! \n **Reason** - ` { reason } ` " )
2023-12-14 16:05:47 -05:00
2023-10-05 20:06:07 -04:00
if silent is None :
2023-10-05 20:12:00 -04:00
silent = not await self . config . guild ( interaction . guild ) . dm_users ( )
2023-10-05 20:06:07 -04:00
if silent is False :
try :
2023-10-06 09:34:30 -04:00
embed = await self . embed_factory ( ' message ' , guild = interaction . guild , reason = reason , moderation_type = ' unbanned ' , response = await interaction . original_response ( ) )
2023-10-05 20:06:07 -04:00
await target . send ( embed = embed )
except discord . errors . HTTPException :
pass
2023-12-14 16:05:47 -05:00
2023-12-13 03:06:26 -05:00
moderation_id = await self . mysql_log ( interaction . guild . id , interaction . user . id , ' UNBAN ' , target . id , 0 , ' NULL ' , reason )
2023-12-13 16:59:36 -05:00
await interaction . edit_original_response ( content = f " { target . mention } has been unbanned! (Case `# { moderation_id } `) \n **Reason** - ` { reason } ` " )
2023-10-23 20:09:17 -04:00
await self . log ( interaction , moderation_id )
2023-10-05 11:09:39 -04:00
2023-10-06 13:22:30 -04:00
@app_commands.command ( name = " history " )
2023-12-14 17:05:21 -05:00
async def history ( self , interaction : discord . Interaction , target : discord . User = None , moderator : discord . User = None , pagesize : app_commands . Range [ int , 1 , 25 ] = None , page : int = 1 , ephemeral : bool = False , inline : bool = False , export : bool = False ) :
2023-10-06 23:09:55 -04:00
""" List previous infractions.
Parameters
- - - - - - - - - - -
target : discord . User
User whose infractions to query , overrides moderator if both are given
moderator : discord . User
Query by moderator
pagesize : app_commands . Range [ int , 1 , 25 ]
Amount of infractions to list per page
page : int
Page to select
2023-12-13 15:42:28 -05:00
ephemeral : bool
2023-12-13 15:35:17 -05:00
Hide the command response
2023-12-14 17:02:51 -05:00
inline : bool
Display infractions in a grid arrangement ( does not look very good )
2023-12-13 15:35:17 -05:00
export : bool
Exports the server ' s entire moderation history to a JSON file " " "
2023-12-13 14:48:44 -05:00
await interaction . response . defer ( ephemeral = ephemeral )
2023-12-14 16:05:47 -05:00
2023-10-22 13:55:54 -04:00
permissions = self . check_permissions ( interaction . client . user , [ ' embed_links ' ] , interaction )
if permissions :
2023-12-13 14:48:44 -05:00
await interaction . followup . send ( f " I do not have the ` { permissions } ` permission, required for this action. " , ephemeral = True )
2023-10-22 13:55:54 -04:00
return
2023-12-14 16:05:47 -05:00
2023-10-06 13:22:30 -04:00
database = await self . connect ( )
cursor = database . cursor ( )
2023-12-14 16:05:47 -05:00
2023-12-14 17:05:21 -05:00
if pagesize is None :
if inline is True :
pagesize = 6
else :
pagesize = 5
2023-10-06 13:22:30 -04:00
if target :
2023-10-06 13:39:51 -04:00
query = """ SELECT *
FROM moderation_ % s
WHERE target_id = % s
ORDER BY moderation_id DESC ; """
cursor . execute ( query , ( interaction . guild . id , target . id ) )
elif moderator :
2023-10-06 13:27:54 -04:00
query = """ SELECT *
2023-10-06 13:52:49 -04:00
FROM moderation_ % s
WHERE moderator_id = % s
ORDER BY moderation_id DESC ; """
2023-10-06 13:39:51 -04:00
cursor . execute ( query , ( interaction . guild . id , moderator . id ) )
2023-10-06 22:55:07 -04:00
else :
query = """ SELECT *
FROM moderation_ % s
ORDER BY moderation_id DESC ; """
2023-10-06 22:56:47 -04:00
cursor . execute ( query , ( interaction . guild . id , ) )
2023-12-14 16:05:47 -05:00
2023-10-06 13:40:57 -04:00
results = cursor . fetchall ( )
result_dict_list = [ ]
2023-12-14 16:05:47 -05:00
2023-10-06 13:40:57 -04:00
for result in results :
case_dict = self . generate_dict ( result )
2023-12-13 16:01:42 -05:00
if case_dict [ ' moderation_id ' ] == 0 :
continue
2023-10-06 13:40:57 -04:00
result_dict_list . append ( case_dict )
2023-12-14 16:05:47 -05:00
2023-12-13 15:35:17 -05:00
if export :
try :
2023-12-13 15:41:55 -05:00
filename = str ( data_manager . cog_data_path ( cog_instance = self ) ) + str ( os . sep ) + f " moderation_ { interaction . guild . id } .json "
2023-12-14 16:05:47 -05:00
2023-12-13 15:53:08 -05:00
with open ( filename , " w " , encoding = " utf-8 " ) as f :
2023-12-13 15:46:28 -05:00
json . dump ( result_dict_list , f , indent = 2 )
2023-12-14 16:05:47 -05:00
2023-12-13 15:45:00 -05:00
await interaction . followup . send ( file = discord . File ( filename , f " moderation_ { interaction . guild . id } .json " ) , ephemeral = ephemeral )
2023-12-14 16:05:47 -05:00
2023-12-13 15:35:17 -05:00
os . remove ( filename )
return
except json . JSONDecodeError as e :
await interaction . followup . send ( content = f " An error occured while exporting the moderation history. \n Error: \n ``` { e } ``` " , ephemeral = ephemeral )
return
2023-12-14 16:05:47 -05:00
2023-12-13 16:01:42 -05:00
case_quantity = len ( result_dict_list )
2023-10-06 13:40:57 -04:00
page_quantity = round ( case_quantity / pagesize )
start_index = ( page - 1 ) * pagesize
end_index = page * pagesize
2023-12-14 16:05:47 -05:00
2023-10-06 13:43:50 -04:00
embed = discord . Embed ( color = await self . bot . get_embed_color ( None ) )
embed . set_author ( icon_url = interaction . guild . icon . url , name = ' Infraction History ' )
2023-10-06 13:40:57 -04:00
embed . set_footer ( text = f " Page { page } / { page_quantity } | { case_quantity } Results " )
2023-12-14 16:05:47 -05:00
2023-12-14 14:41:38 -05:00
memory_dict = { }
2023-12-14 16:05:47 -05:00
2023-10-06 13:40:57 -04:00
for case in result_dict_list [ start_index : end_index ] :
2023-12-14 14:41:38 -05:00
if case [ ' target_id ' ] not in memory_dict :
memory_dict [ str ( case [ ' target_id ' ] ) ] = await self . fetch_user_dict ( interaction , case [ ' target_id ' ] )
target_user = memory_dict [ str ( case [ ' target_id ' ] ) ]
2023-12-14 16:05:47 -05:00
2023-12-14 14:41:38 -05:00
if case [ ' moderator_id ' ] not in memory_dict :
memory_dict [ str ( case [ ' moderator_id ' ] ) ] = await self . fetch_user_dict ( interaction , case [ ' moderator_id ' ] )
moderator_user = memory_dict [ str ( case [ ' moderator_id ' ] ) ]
2023-12-14 16:05:47 -05:00
2023-12-14 14:24:00 -05:00
target_name = target_user [ ' name ' ] if target_user [ ' discriminator ' ] == " 0 " else f " { target_user [ ' name ' ] } # { target_user [ ' discriminator ' ] } "
2023-10-06 13:40:57 -04:00
moderator_name = moderator_user [ ' name ' ] if moderator_user [ ' discriminator ' ] == " 0 " else f " { moderator_user [ ' name ' ] } # { moderator_user [ ' discriminator ' ] } "
2023-12-14 16:05:47 -05:00
2023-10-06 13:40:57 -04:00
field_name = f " Case # { case [ ' moderation_id ' ] } ( { str . title ( case [ ' moderation_type ' ] ) } ) "
2023-12-14 14:57:28 -05:00
field_value = f " **Target:** ` { target_name } ` ( { target_user [ ' id ' ] } ) \n **Moderator:** ` { moderator_name } ` ( { moderator_user [ ' id ' ] } ) "
2023-12-14 16:05:47 -05:00
2023-12-14 14:57:28 -05:00
if len ( case [ ' reason ' ] ) > 150 :
field_value + = f " \n **Reason:** ` { str ( case [ ' reason ' ] ) [ : 150 ] } ...` "
else :
field_value + = f " \n **Reason:** ` { str ( case [ ' reason ' ] ) } ` "
2023-12-14 16:05:47 -05:00
2023-10-06 13:40:57 -04:00
if case [ ' duration ' ] != ' NULL ' :
td = timedelta ( * * { unit : int ( val ) for unit , val in zip ( [ " hours " , " minutes " , " seconds " ] , case [ " duration " ] . split ( " : " ) ) } )
2023-12-13 15:07:04 -05:00
duration_embed = f " { humanize . precisedelta ( td ) } | <t: { case [ ' end_timestamp ' ] } :R> " if bool ( case [ ' expired ' ] ) is False else f " { humanize . precisedelta ( td ) } | Expired "
2023-12-14 16:50:01 -05:00
field_value + = f " \n **Duration:** { duration_embed } "
field_value + = f " \n **Timestamp:** <t: { case [ ' timestamp ' ] } > | <t: { case [ ' timestamp ' ] } :R> "
2023-12-14 16:05:47 -05:00
2023-10-06 13:40:57 -04:00
if bool ( case [ ' resolved ' ] ) :
2023-12-14 16:50:01 -05:00
field_value + = " \n **Resolved:** True "
2023-12-14 16:05:47 -05:00
2023-12-14 17:01:02 -05:00
embed . add_field ( name = field_name , value = field_value , inline = inline )
2023-12-14 16:05:47 -05:00
2023-12-13 15:00:36 -05:00
await interaction . followup . send ( embed = embed , ephemeral = ephemeral )
2023-10-06 13:22:30 -04:00
2023-10-05 17:09:55 -04:00
@app_commands.command ( name = " resolve " )
async def resolve ( self , interaction : discord . Interaction , case_number : int , reason : str = None ) :
2023-10-06 23:09:55 -04:00
""" Resolve a specific case.
Parameters
- - - - - - - - - - -
case_number : int
Case number of the case you ' re trying to resolve
reason : str
Reason for resolving case """
2023-10-22 14:17:09 -04:00
permissions = self . check_permissions ( interaction . client . user , [ ' embed_links ' , ' moderate_members ' , ' ban_members ' ] , interaction )
2023-10-22 13:55:54 -04:00
if permissions :
await interaction . response . send_message ( f " I do not have the ` { permissions } ` permission, required for this action. " , ephemeral = True )
return
2023-12-14 16:05:47 -05:00
2023-10-06 09:11:22 -04:00
conf = await self . check_conf ( [ ' mysql_database ' ] )
if conf :
raise ( LookupError )
2023-12-14 16:05:47 -05:00
2023-10-05 17:09:55 -04:00
database = await self . connect ( )
cursor = database . cursor ( )
2023-10-06 09:11:22 -04:00
db = await self . config . mysql_database ( )
2023-12-14 16:05:47 -05:00
2023-10-05 17:09:55 -04:00
query_1 = " SELECT * FROM moderation_ %s WHERE moderation_id = %s ; "
cursor . execute ( query_1 , ( interaction . guild . id , case_number ) )
result_1 = cursor . fetchone ( )
2023-10-06 23:51:42 -04:00
if result_1 is None or case_number == 0 :
2023-10-05 17:14:04 -04:00
await interaction . response . send_message ( content = f " There is no moderation with a case number of { case_number } . " , ephemeral = True )
2023-10-05 17:09:55 -04:00
return
2023-12-14 16:05:47 -05:00
2023-10-05 17:09:55 -04:00
query_2 = " SELECT * FROM moderation_ %s WHERE moderation_id = %s AND resolved = 0; "
cursor . execute ( query_2 , ( interaction . guild . id , case_number ) )
result_2 = cursor . fetchone ( )
if result_2 is None :
await interaction . response . send_message ( content = f " This moderation has already been resolved! \n Use `/case { case_number } ` for more information. " , ephemeral = True )
return
2023-12-14 16:05:47 -05:00
2023-10-05 22:36:42 -04:00
case = self . generate_dict ( result_2 )
2023-10-05 17:09:55 -04:00
if reason is None :
reason = " No reason given. "
2023-12-14 16:05:47 -05:00
2023-10-06 12:46:51 -04:00
if case [ ' moderation_type ' ] in [ ' UNMUTE ' , ' UNBAN ' ] :
await interaction . response . send_message ( content = " You cannot resolve this type of moderation! " , ephemeral = True )
2023-12-14 16:05:47 -05:00
2023-10-06 12:46:51 -04:00
if case [ ' moderation_type ' ] in [ ' MUTE ' , ' TEMPBAN ' , ' BAN ' ] :
2023-10-06 10:46:06 -04:00
if case [ ' moderation_type ' ] == ' MUTE ' :
2023-10-05 22:36:42 -04:00
try :
member = await interaction . guild . fetch_member ( case [ ' target_id ' ] )
2023-12-14 16:05:47 -05:00
2023-10-05 22:36:42 -04:00
await member . timeout ( None , reason = f " Case # { case_number } resolved by { interaction . user . id } " )
2023-10-06 09:04:02 -04:00
except discord . NotFound :
2023-10-05 22:36:42 -04:00
pass
2023-12-14 16:05:47 -05:00
2023-10-06 12:46:51 -04:00
if case [ ' moderation_type ' ] in [ ' TEMPBAN ' , ' BAN ' ] :
2023-10-05 22:36:42 -04:00
try :
user = await interaction . client . fetch_user ( case [ ' target_id ' ] )
2023-12-14 16:05:47 -05:00
2023-10-05 22:36:42 -04:00
await interaction . guild . unban ( user , reason = f " Case # { case_number } resolved by { interaction . user . id } " )
2023-10-06 09:04:02 -04:00
except discord . NotFound :
2023-10-05 22:36:42 -04:00
pass
2023-12-14 16:05:47 -05:00
2023-10-06 10:49:05 -04:00
resolve_query = f " UPDATE ` { db } `.`moderation_ { interaction . guild . id } ` SET resolved = 1, expired = 1, resolved_by = %s, resolve_reason = %s WHERE moderation_id = %s "
2023-10-05 22:36:42 -04:00
else :
2023-10-06 10:07:52 -04:00
resolve_query = f " UPDATE ` { db } `.`moderation_ { interaction . guild . id } ` SET resolved = 1, resolved_by = %s, resolve_reason = %s WHERE moderation_id = %s "
2023-12-14 16:05:47 -05:00
2023-10-06 10:07:52 -04:00
cursor . execute ( resolve_query , ( interaction . user . id , reason , case_number ) )
2023-10-06 09:53:59 -04:00
database . commit ( )
2023-12-14 16:05:47 -05:00
2023-10-06 09:34:30 -04:00
response_query = " SELECT * FROM moderation_ %s WHERE moderation_id = %s ; "
cursor . execute ( response_query , ( interaction . guild . id , case_number ) )
result = cursor . fetchone ( )
case_dict = self . generate_dict ( result )
2023-12-14 16:05:47 -05:00
2023-10-06 09:36:23 -04:00
embed = await self . embed_factory ( ' case ' , interaction = interaction , case_dict = case_dict )
2023-10-06 09:34:30 -04:00
await interaction . response . send_message ( content = f " ✅ Moderation # { case_number } resolved! " , embed = embed )
2023-10-23 20:09:17 -04:00
await self . log ( interaction , case_number , True )
2023-12-14 16:05:47 -05:00
2023-10-06 09:53:59 -04:00
cursor . close ( )
database . close ( )
2023-10-05 17:09:55 -04:00
2023-10-05 12:58:57 -04:00
@app_commands.command ( name = " case " )
async def case ( self , interaction : discord . Interaction , case_number : int , ephemeral : bool = False ) :
2023-10-06 23:09:55 -04:00
""" Check the details of a specific case.
Parameters
- - - - - - - - - - -
case_number : int
What case are you looking up ?
ephemeral : bool
Hide the command response """
2023-10-22 13:55:54 -04:00
permissions = self . check_permissions ( interaction . client . user , [ ' embed_links ' ] , interaction )
if permissions :
await interaction . response . send_message ( f " I do not have the ` { permissions } ` permission, required for this action. " , ephemeral = True )
return
2023-12-14 16:05:47 -05:00
2023-10-23 20:09:17 -04:00
if case_number != 0 :
case = await self . fetch_case ( case_number , interaction . guild . id )
if case :
embed = await self . embed_factory ( ' case ' , interaction = interaction , case_dict = case )
await interaction . response . send_message ( embed = embed , ephemeral = ephemeral )
return
await interaction . response . send_message ( content = f " No case with case number ` { case_number } ` found. " , ephemeral = True )
2023-10-05 12:58:57 -04:00
2023-10-05 13:48:11 -04:00
@tasks.loop ( minutes = 1 )
async def handle_expiry ( self ) :
conf = await self . check_conf ( [ ' mysql_database ' ] )
if conf :
2023-10-05 16:15:16 -04:00
raise ( LookupError )
2023-12-14 16:05:47 -05:00
2023-10-05 13:48:11 -04:00
database = await self . connect ( )
cursor = database . cursor ( )
2023-10-05 13:56:31 -04:00
db = await self . config . mysql_database ( )
2023-12-14 16:05:47 -05:00
2023-10-05 13:56:31 -04:00
guilds : list [ discord . Guild ] = self . bot . guilds
for guild in guilds :
2023-10-22 13:28:50 -04:00
if not await self . bot . cog_disabled_in_guild ( self , guild ) :
2023-12-14 16:05:47 -05:00
2023-10-22 13:28:50 -04:00
tempban_query = f " SELECT target_id, moderation_id FROM moderation_ { guild . id } WHERE end_timestamp != 0 AND end_timestamp <= %s AND moderation_type = ' TEMPBAN ' AND expired = 0 "
2023-12-14 16:05:47 -05:00
2023-10-05 16:26:45 -04:00
try :
2023-10-22 13:28:50 -04:00
cursor . execute ( tempban_query , ( time . time ( ) , ) )
result = cursor . fetchall ( )
except mysql . connector . errors . ProgrammingError :
continue
2023-12-14 16:05:47 -05:00
2023-10-22 13:28:50 -04:00
target_ids = [ row [ 0 ] for row in result ]
moderation_ids = [ row [ 1 ] for row in result ]
2023-12-14 16:05:47 -05:00
2023-10-22 13:28:50 -04:00
for target_id , moderation_id in zip ( target_ids , moderation_ids ) :
user : discord . User = await self . bot . fetch_user ( target_id )
try :
2023-12-13 14:48:44 -05:00
await guild . unban ( user , reason = f " Automatic unban from case # { moderation_id } " )
2023-12-14 16:05:47 -05:00
2023-12-13 14:48:44 -05:00
embed = await self . embed_factory ( ' message ' , guild , f ' Automatic unban from case # { moderation_id } ' , ' unbanned ' )
2023-12-14 16:05:47 -05:00
2023-12-13 14:48:44 -05:00
try :
await user . send ( embed = embed )
except discord . errors . HTTPException :
pass
except [ discord . errors . NotFound , discord . errors . Forbidden , discord . errors . HTTPException ] as e :
print ( f " Failed to unban { user . name } # { user . discriminator } ( { user . id } ) from { guild . name } ( { guild . id } ) \n { e } " )
2023-12-14 16:05:47 -05:00
2023-12-13 14:48:44 -05:00
expiry_query = f " UPDATE ` { db } `.`moderation_ { guild . id } ` SET expired = 1 WHERE (end_timestamp != 0 AND end_timestamp <= %s AND expired = 0 AND moderation_type != ' BLACKLIST ' ) OR (expired = 0 AND resolved = 1 AND moderation_type != ' BLACKLIST ' ) "
2023-10-22 13:28:50 -04:00
cursor . execute ( expiry_query , ( time . time ( ) , ) )
2023-12-14 16:05:47 -05:00
2023-12-13 14:48:44 -05:00
blacklist_query = f " SELECT target_id, moderation_id, role_id FROM moderation_ { guild . id } WHERE end_timestamp != 0 AND end_timestamp <= %s AND moderation_type = ' BLACKLIST ' AND expired = 0 "
try :
cursor . execute ( blacklist_query , ( time . time ( ) , ) )
result = cursor . fetchall ( )
except mysql . connector . errors . ProgrammingError :
2023-12-14 16:05:47 -05:00
2023-12-13 14:48:44 -05:00
continue
target_ids = [ row [ 0 ] for row in result ]
moderation_ids = [ row [ 1 ] for row in result ]
role_ids = [ row [ 2 ] for row in result ]
2023-12-14 16:05:47 -05:00
2023-12-13 14:48:44 -05:00
for target_id , moderation_id , role_id in zip ( target_ids , moderation_ids , role_ids ) :
try :
member : discord . Member = await guild . fetch_member ( target_id )
2023-12-14 16:05:47 -05:00
2023-12-13 14:48:44 -05:00
role : discord . Role = guild . get_role ( role_id )
if role is None :
raise discord . errors . NotFound
except [ discord . errors . NotFound , discord . errors . Forbidden , discord . errors . HTTPException ] :
continue
2023-12-14 16:05:47 -05:00
2023-10-05 13:48:11 -04:00
database . commit ( )
cursor . close ( )
database . close ( )
2023-10-05 12:58:57 -04:00
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 ) :
2023-10-05 20:06:07 -04:00
""" Toggle if the cog should ignore other bots ' moderations. """
2023-10-05 20:12:00 -04:00
await self . config . guild ( ctx . guild ) . ignore_other_bots . set ( not await self . config . guild ( ctx . guild ) . ignore_other_bots ( ) )
await ctx . send ( f " Ignore bots setting set to { await self . config . guild ( ctx . guild ) . ignore_other_bots ( ) } " )
2023-10-04 11:57:21 -04:00
2023-10-05 20:06:07 -04:00
@moderationset.command ( name = " dm " )
@checks.admin ( )
async def moderationset_dm ( self , ctx : commands . Context ) :
""" Toggle automatically messaging moderated users.
This option can be overridden by specifying the ` silent ` argument in any moderation command . """
2023-10-05 20:12:00 -04:00
await self . config . guild ( ctx . guild ) . dm_users . set ( not await self . config . guild ( ctx . guild ) . dm_users ( ) )
await ctx . send ( f " DM users setting set to { await self . config . guild ( ctx . guild ) . dm_users ( ) } " )
2023-10-05 20:06:07 -04:00
2023-10-23 20:09:17 -04:00
@moderationset.command ( name = " logchannel " )
@checks.admin ( )
async def moderationset_logchannel ( self , ctx : commands . Context , channel : discord . TextChannel = None ) :
""" Set a channel to log infractions to. """
if channel :
await self . config . guild ( ctx . guild ) . log_channel . set ( channel . id )
await ctx . send ( f " Logging channel set to { channel . mention } . " )
else :
await self . config . guild ( ctx . guild ) . log_channel . set ( " " )
2023-10-24 00:41:29 -04:00
await ctx . send ( " Logging channel disabled. " )
2023-10-23 20:09:17 -04:00
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 = " "
2023-12-14 16:05:47 -05:00
2023-09-24 23:55:21 -04:00
if self . address . value != " " :
await self . config . mysql_address . set ( self . address . value )
message + = f " - Address set to \n - ` { self . address . value } ` \n "
2023-12-14 16:05:47 -05:00
2023-09-24 23:55:21 -04:00
if self . database . value != " " :
await self . config . mysql_database . set ( self . database . value )
message + = f " - Database set to \n - ` { self . database . value } ` \n "
2023-12-14 16:05:47 -05:00
2023-09-24 23:55:21 -04:00
if self . username . value != " " :
await self . config . mysql_username . set ( self . username . value )
message + = f " - Username set to \n - ` { self . username . value } ` \n "
2023-12-14 16:05:47 -05:00
2023-09-24 23:55:21 -04:00
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 "
2023-12-14 16:05:47 -05:00
2023-09-24 23:55:21 -04:00
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-12-14 16:05:47 -05:00
2023-09-24 23:55:21 -04:00
else :
send = f " Configuration changed: \n { message } "
2023-12-14 16:05:47 -05:00
2023-09-24 23:55:21 -04:00
await interaction . response . send_message ( send , ephemeral = True )
2023-10-04 21:32:33 -04:00
2023-12-13 03:06:26 -05:00
@moderationset.group ( autohelp = True )
@checks.admin ( )
async def moderationset_import ( self , ctx : commands . Context ) :
""" Import moderations from other bots. """
@moderationset_import.command ( name = " galacticbot " )
@checks.admin ( )
async def moderationset_import_galacticbot ( self , ctx : commands . Context ) :
""" Import moderations from GalacticBot. **UNFINISHED!** """
await ctx . send ( " Are you sure you want to import GalacticBot moderations? This will overwrite any moderations that already exist in the database. " , view = self . GalacticBotImportButtons ( 60 ) )
class GalacticBotImportButtons ( discord . ui . View ) :
def __init__ ( self , timeout ) :
super ( ) . __init__ ( )
self . config = Config . get_conf ( None , cog_name = ' Moderation ' , identifier = 481923957134912 )
@discord.ui.button ( label = " Yes " , style = discord . ButtonStyle . success )
2023-12-13 15:15:30 -05:00
async def import_button_y ( self , interaction : discord . Interaction , button : discord . ui . Button ) : # pylint: disable=unused-argument
2023-12-13 03:06:26 -05:00
await interaction . response . send_modal ( Moderation . MySQLConfigModal ( self . config ) )
@discord.ui.button ( label = " No " , style = discord . ButtonStyle . danger )
2023-12-13 15:15:30 -05:00
async def import_button_n ( self , interaction : discord . Interaction , button : discord . ui . Button ) : # pylint: disable=unused-argument
2023-12-13 03:06:26 -05:00
await interaction . response . send_modal ( Moderation . MySQLConfigModal ( self . config ) )
2023-10-04 21:32:33 -04:00
@commands.command ( aliases = [ " tdc " ] )
2023-10-05 09:57:14 -04:00
async def timedeltaconvert ( self , ctx : commands . Context , * , duration : str ) :
""" This command converts a duration to a [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) Python object.
2023-10-05 09:55:22 -04:00
2023-10-05 09:57:14 -04:00
* * Example usage * *
2023-10-05 09:58:52 -04:00
` [ p ] timedeltaconvert 1 day 15 hr 82 minutes 52 s `
2023-10-05 09:57:14 -04:00
* * Output * *
` 1 day , 16 : 22 : 52 ` """
2023-10-05 09:55:22 -04:00
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! " )