diff --git a/.env.example b/.env.example index cc6e6a4..ffd9839 100644 --- a/.env.example +++ b/.env.example @@ -1,4 +1,9 @@ TOKEN=token-goes-here PREFIX=! # Only change the API URL if you're using a selfhosted Revolt instance. -API_URL=https://api.revolt.chat \ No newline at end of file +API_URL=https://api.revolt.chat +# Moderation Database +DB_HOST=localhost +DB_USER=yourusername +DB_PASSWORD=yourpassword +DB=yourdatabase diff --git a/.github/workflows/pylint.yml b/.github/workflows/pylint.yml index 963c846..82bebc0 100644 --- a/.github/workflows/pylint.yml +++ b/.github/workflows/pylint.yml @@ -18,8 +18,7 @@ jobs: run: | python -m pip install --upgrade pip pip install pylint - pip install revolt.py - pip install python-dotenv + pip install python-dotenv revolt.py mysql-connector-python pytimeparse2 - name: Analysing the code with pylint run: | pylint $(git ls-files '*.py') diff --git a/main.py b/main.py index 5565361..35255da 100644 --- a/main.py +++ b/main.py @@ -22,21 +22,21 @@ class Client(commands.CommandsClient): return prefix return input - async def on_message(self, message: revolt.Message): - if 'PREFIX' not in os.environ or prefix is None: - if message.author == self.user.owner: - await message.channel.send("You have started the bot without setting the `prefix` environment variable!\nIt has been set to `temp!` automatically, please change it using `temp!prefix `.") - print("ERROR: prefix_env_var check failed! Prefix set to 'temp!'.") - new_prefix = "temp!" - await Client.prefix_change(self=self, message=message, new_prefix=new_prefix, silent=True) - else: - print("ERROR: prefix_env_var check failed!") - else: - if isinstance(message.author, revolt.Member): - print(f"{message.author.name}#{message.author.discriminator} ({message.author.id}): {message.content}\n ⤷ Sent from {message.server.name} ({message.server.id})") - else: - print(f"{message.author.name}#{message.author.discriminator} ({message.author.id}): {message.content}\n ⤷ Sent in Direct Messages") - await Client.process_commands(self, message) + # async def on_message(self, message: revolt.Message): + # if 'PREFIX' not in os.environ or prefix is None: + # if message.author == self.user.owner: + # await message.channel.send("You have started the bot without setting the `prefix` environment variable!\nIt has been set to `temp!` automatically, please change it using `temp!prefix `.") + # print("ERROR: prefix_env_var check failed! Prefix set to 'temp!'.") + # new_prefix = "temp!" + # await Client.prefix_change(self=self, message=message, new_prefix=new_prefix, silent=True) + # else: + # print("ERROR: prefix_env_var check failed!") + # else: + # if isinstance(message.author, revolt.Member): + # print(f"{message.author.name}#{message.author.discriminator} ({message.author.id}): {message.content}\n ⤷ Sent from {message.server.name} ({message.server.id})") + # else: + # print(f"{message.author.name}#{message.author.discriminator} ({message.author.id}): {message.content}\n ⤷ Sent in Direct Messages") + # await Client.process_commands(self, message) @commands.command() async def ping(self, ctx: commands.Context): @@ -74,6 +74,12 @@ class Client(commands.CommandsClient): else: await ctx.message.reply(f"The prefix is currently set to `{prefix}`.") + @commands.command() + async def temptimeout(self, ctx: commands.Context): + target = Client.get_server(self, "01G9FHH3F20QHBERQ6FT3RT5Y2").get_member("01H37XQF4WMV6HRGYTA03YMSDZ") + duration = Moderation.parse_timedelta(self, "1 minute") + await target.timeout(duration) + async def main(): # This function logs into the bot user. async with aiohttp.ClientSession() as session: diff --git a/moderation.py b/moderation.py index 2c9fd2c..4356c9c 100644 --- a/moderation.py +++ b/moderation.py @@ -1,42 +1,62 @@ +import os from datetime import timedelta +import dotenv +import mysql.connector import revolt +from dotenv import load_dotenv +from pytimeparse2 import disable_dateutil, parse from revolt.ext import commands +# This code reads the variables set in the bot's '.env' file. +env = dotenv.find_dotenv() +load_dotenv(env) +prefix = os.getenv('PREFIX') +db_host = os.getenv('DB_HOST') +db_user = os.getenv('DB_USER') +db_password = os.getenv('DB_PASSWORD') +db = os.getenv('DB') + +moddb = mysql.connector.connect( +host=db_host, +user=db_user, +password=db_password, +database=db +) +cursor = moddb.cursor() + class Moderation(commands.Cog): def __init__(self, bot): self.bot = bot + disable_dateutil() - def parse_timedelta(self, input_str): - # Split the string into its components (e.g., "1 day 3 hours" becomes ["1", "day", "3", "hours"]) - components = input_str.split() - - # Define a dictionary to map time units to their corresponding `timedelta` attribute - units = {"days": "days", "hours": "hours", "minutes": "minutes", "seconds": "seconds", "day": "days", "hour": "hours", "minute": "minutes", "second": "seconds", "d": "days", "h": "hours", "m": "minutes", "s": "seconds"} - - # Iterate over the components, taking pairs of values and units - values_units = zip(components[::2], components[1::2]) - - # Initialize a dictionary to store the values for each unit - values = {} - - # Parse the values and units into the dictionary - for value, unit in values_units: - # Convert the value to an integer - value = int(value) - # Map the unit to the corresponding `timedelta` attribute and store the value - values[units[unit]] = value - - # Create and return the `timedelta` object - return timedelta(**values) - - - @commands.command(name="mute", aliases="timeout") - async def mute(self, ctx, target: revolt.Member, duration: str = "1 hour"): - parsed_time = Moderation.parse_timedelta(self, duration) + @commands.command(name="mute", aliases=["timeout"]) + async def mute(self, ctx: commands.Context, target: commands.MemberConverter, *, duration: str = "1 hour"): + try: + parsed_time = parse(duration, as_timedelta=True, raise_exception=True) + except ValueError: + await ctx.message.reply(f"Please provide a valid duration!\nSee `{prefix}tdc`") + return await target.timeout(parsed_time) await ctx.message.reply(f"{target.mention} has been timed out for {str(parsed_time)}!") + embeds = [revolt.SendableEmbed(title="Timed Out", description=f"You have been timed out for {str(parsed_time)}.", colour="#5d82d1")] + await target.send(embeds=embeds) + # latest_id = cursor.execute("SELECT * FROM mod ORDER BY moderation_id DESC LIMIT 1;") + # sql = "INSERT INTO mod (moderation_id, moderation_type, target_id, duration, reason) VALUES (%s, %s, %s, %s, %s)" + # val = (latest_id, "Timeout", target.id, parsed_time, "Testing") + # cursor.execute(sql, val) - @commands.command() - async def timedeltaconvert(self, ctx, *, duration: str = "1 hour"): - parsed_time = Moderation.parse_timedelta(self, duration) - await ctx.send(str(parsed_time)) + # moddb.commit() + + # print(moddb.rowcount, "record inserted.") + + @commands.command(aliases=["tdc"]) + async def timedeltaconvert(self, ctx, *, duration): + if not duration: + embeds = [revolt.SendableEmbed(description=f"## timedeltaconvert\nThis command converts a duration to a `timedelta` Python object.\n### Example Usage\n`{prefix}timedeltaconvert 1 day 15hr 82 minutes 52 s`\n### Output\n`1 day, 16:22:52`", colour="#5d82d1")] + await ctx.message.reply(embeds=embeds) + else: + try: + parsed_time = parse(duration, as_timedelta=True, raise_exception=True) + await ctx.message.reply(f"`{str(parsed_time)}`") + except ValueError: + await ctx.message.reply("Please provide a convertible value!")