Compare commits

..

21 commits

Author SHA1 Message Date
ece4cc74f6
fix(aurora): update the docstring for slowmode's interval argument
Some checks failed
Actions / Build Documentation (MkDocs) (pull_request) Failing after 22s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 43s
2025-02-18 15:25:38 -06:00
f5023b7643
fix(aurora): oops
Some checks failed
Actions / Build Documentation (MkDocs) (pull_request) Failing after 0s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 43s
2025-02-18 15:24:19 -06:00
865ec8c9b9
fix(aurora): fix slowmode text
Some checks failed
Actions / Build Documentation (MkDocs) (pull_request) Failing after 0s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 47s
2025-02-18 15:23:31 -06:00
49fa229727
Merge branch 'main' into aurora/v3
Some checks failed
Actions / Build Documentation (MkDocs) (pull_request) Failing after 0s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 41s
2025-02-18 15:21:08 -06:00
0a0bd10075
fix(aurora): fix slowmode erroring when no reason is provided
Some checks failed
Actions / Build Documentation (MkDocs) (pull_request) Failing after 0s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 44s
2025-02-18 15:12:37 -06:00
ab29c8f6ad
fix(aurora): use timedelta still
Some checks failed
Actions / Build Documentation (MkDocs) (pull_request) Failing after 21s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 43s
2025-02-18 15:08:52 -06:00
44108774e1
fix(aurora): make Shortmute.handler() take an int for interval instead of str
Some checks failed
Actions / Build Documentation (MkDocs) (pull_request) Failing after 22s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 43s
2025-02-18 15:06:40 -06:00
6977647758
fix(aurora): pass duration in /shortmute
Some checks failed
Actions / Build Documentation (MkDocs) (pull_request) Failing after 1s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 46s
2025-02-18 15:03:40 -06:00
248e5d046d
fix(aurora): fix slowmode
Some checks failed
Actions / Build Documentation (MkDocs) (pull_request) Failing after 21s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 47s
2025-02-18 14:59:54 -06:00
ba0e19cab9
Merge branch 'aurora/v3' of c.csw.im:cswimr/SeaCogs into aurora/v3
Some checks failed
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 47s
Actions / Build Documentation (MkDocs) (pull_request) Failing after 21s
2025-02-17 16:23:52 -06:00
7448097773
Merge branch 'main' into aurora/v3 2025-02-17 16:23:36 -06:00
ec5978350f
Merge branch 'main' into aurora/v3
Some checks failed
Actions / Build Documentation (MkDocs) (pull_request) Successful in 43s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 52s
2025-01-26 09:17:06 -05:00
b6d77a593b
Merge branch 'main' into aurora/v3
Some checks failed
Actions / Build Documentation (MkDocs) (pull_request) Successful in 36s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 43s
2025-01-25 20:41:49 -05:00
f3d80d1071
Merge branch 'main' into aurora/v3
Some checks failed
Actions / Build Documentation (MkDocs) (pull_request) Successful in 37s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 46s
2025-01-25 19:43:14 -05:00
a563a42d2e
Merge branch 'main' into aurora/v3
Some checks failed
Actions / Build Documentation (MkDocs) (push) Has been skipped
Actions / Build Documentation (MkDocs) (pull_request) Has been skipped
Actions / Lint Code (Ruff & Pylint) (push) Failing after 43s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 43s
2025-01-25 19:40:55 -05:00
850ddf15a6
fix(aurora): improve typehints in the Type model
Some checks failed
Actions / Build Documentation (MkDocs) (push) Has been skipped
Actions / Build Documentation (MkDocs) (pull_request) Has been skipped
Actions / Lint Code (Ruff & Pylint) (push) Failing after 44s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 44s
2025-01-25 22:11:37 +00:00
db125187c9
fix(aurora): add missing __init__.py file 2025-01-25 22:09:08 +00:00
e79dfd6b94
chore(deps): update phx-class-registry
Some checks failed
Actions / Build Documentation (MkDocs) (push) Has been skipped
Actions / Build Documentation (MkDocs) (pull_request) Has been skipped
Actions / Lint Code (Ruff & Pylint) (push) Failing after 43s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 44s
2025-01-25 22:01:00 +00:00
4bfb92e937
chore(deps): update phx-class-registry
Some checks failed
Actions / Build Documentation (MkDocs) (push) Has been skipped
Actions / Build Documentation (MkDocs) (pull_request) Has been skipped
Actions / Lint Code (Ruff & Pylint) (push) Failing after 43s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 43s
2025-01-25 21:57:21 +00:00
f71a85092b misc(aurora): transition to rc naming for indev versions
Some checks failed
Actions / Build Documentation (MkDocs) (push) Has been skipped
Actions / Build Documentation (MkDocs) (pull_request) Has been skipped
Actions / Lint Code (Ruff & Pylint) (push) Failing after 47s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 46s
2025-01-25 16:50:57 -05:00
ba7a427dad feat(aurora): v3 2025-01-25 16:50:57 -05:00
36 changed files with 3842 additions and 2507 deletions

38
.devcontainer/Dockerfile Normal file
View file

@ -0,0 +1,38 @@
FROM ghcr.io/astral-sh/uv:0.5.30@sha256:bb74263127d6451222fe7f71b330edfb189ab1c98d7898df2401fbf4f272d9b9 AS uv
FROM python:3.11-slim@sha256:6ed5bff4d7d377e2a27d9285553b8c21cfccc4f00881de1b24c9bc8d90016e82 AS python
FROM code.forgejo.org/forgejo/runner:6.2.1@sha256:fecc96a111a15811a6887ce488e75718089f24599e613e93db8e54fe70b706e8 AS forgejo-runner
FROM mcr.microsoft.com/vscode/devcontainers/base:bookworm@sha256:6155a486f236fd5127b76af33086029d64f64cf49dd504accb6e5f949098eb7e
LABEL repository="www.coastalcommits.com/cswimr/SeaCogs"
LABEL maintainer="cswimr <seaswimmerthefsh@gmail.com>"
RUN apt-get update; \
apt-get install -y --no-install-recommends \
# Red-DiscordBot
build-essential \
git \
# PyNaCl
libsodium-dev \
# CFFI
libffi-dev \
# SSH repository support
openssh-client \
# Cog dependencies
# Audio
openjdk-17-jre-headless \
# PyLav
libaio1 \
libaio-dev \
# SeaUtils
dnsutils; \
apt-get clean; \
rm -rf /var/lib/apt/lists/*
COPY --from=uv --chown=vscode: /uv /uvx /bin/
COPY --from=python --chown=vscode: /usr/local /usr/local
COPY --from=forgejo-runner --chown=vscode: /bin/forgejo-runner /bin/forgejo-runner
COPY --chown=vscode: .devcontainer/home/* /home/vscode/
RUN ln -s /usr/local/bin/python3.11 /usr/local/bin/python; \
python --version; \
python -m ensurepip

View file

@ -0,0 +1,52 @@
{
"name": "Red-DiscordBot: SeaCogs",
"build": {
"context": "..",
"dockerfile": "Dockerfile"
},
"features": {
"ghcr.io/devcontainers/features/docker-in-docker:2": {}
},
"customizations": {
"vscode": {
"settings": {
"python.terminal.activateEnvInCurrentTerminal": true,
"python.terminal.activateEnvironment": true,
"terminal.integrated.defaultProfile.linux": "zsh",
"terminal.integrated.profiles.linux": {
"zsh": {
"path": "/bin/zsh"
}
}
},
"extensions": [
"charliermarsh.ruff",
"ms-azuretools.vscode-docker",
"ms-python.python",
"tekumara.typos-vscode",
"tamasfe.even-better-toml",
"redhat.vscode-yaml",
"DavidAnson.vscode-markdownlint",
"yy0931.vscode-sqlite3-editor",
"aaron-bond.better-comments",
"donjayamanne.githistory",
"eamodio.gitlens"
]
}
},
"containerEnv": {
"DISPLAY": "dummy",
"PYTHONUNBUFFERED": "True",
"UV_LINK_MODE": "copy",
"UV_PYTHON_PREFERENCE": "only-system",
"UV_PYTHON_DOWNLOADS": "never",
"PROJECT_DIR": "/workspaces/SeaCogs"
},
"mounts": [
"source=seacogs-persistent-data,target=/workspaces/SeaCogs/.data,type=volume"
],
"postCreateCommand": {
"Setup Virtual Environment": "uv sync --frozen && sudo chown -R vscode:vscode /workspaces/SeaCogs/.data && uv run redbot-setup --no-prompt --instance-name=local --data-path=/workspaces/SeaCogs/.data --backend=json"
},
"remoteUser": "vscode"
}

View file

@ -0,0 +1,3 @@
#!/usr/bin/env bash
alias runactions="forgejo-runner exec --default-actions-url=https://www.coastalcommits.com --gitea-instance=https://www.coastalcommits.com"

View file

@ -9,20 +9,15 @@ jobs:
lint: lint:
name: Lint Code (Ruff & Pylint) name: Lint Code (Ruff & Pylint)
runs-on: docker runs-on: docker
container: catthehacker/ubuntu:act-latest@sha256:cd837565ef74f3d0f94e89ff6723292caa415306bddabfe566932ae892ca9334 container: www.coastalcommits.com/cswimr/actions:uv@sha256:211aaf7d9ac98087579ebf9fab87a9122f51b2697e3a3649ac9f4bd3b03b8e5d
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- name: "Setup uv" - name: Install python
uses: actions/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5 run: uv python install 3.11
with:
version: "latest"
enable-cache: true
prune-cache: false
github-token: ${{ secrets.GITHUBTOKEN }}
- name: "Install dependencies" - name: Install dependencies
run: uv sync run: uv sync
- name: Analysing code with Ruff - name: Analysing code with Ruff
@ -35,26 +30,21 @@ jobs:
docs: docs:
name: Build Documentation (MkDocs) name: Build Documentation (MkDocs)
runs-on: docker runs-on: docker
container: catthehacker/ubuntu:act-latest@sha256:cd837565ef74f3d0f94e89ff6723292caa415306bddabfe566932ae892ca9334 container: www.coastalcommits.com/cswimr/actions:docs@sha256:e405cd6b9b1182a570ddee32ed8dd1b2f899edc625d006c8b4b2f18c100e724f
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
with: with:
fetch-depth: 0 fetch-depth: 0
- name: "Setup uv" - name: Install python
uses: actions/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5 run: uv python install 3.11
with:
version: "latest"
enable-cache: true
prune-cache: false
github-token: ${{ secrets.GITHUBTOKEN }}
- name: Install dependencies - name: Install dependencies
run: uv sync --no-dev --group=documentation run: uv sync --no-dev --extra=documentation
- name: Set environment variables - name: Set environment variables
uses: actions/env@1791216cd180e6578dd1d67fb8d2852b883a5f53 # v2 uses: actions/env@v2
- name: Build documentation - name: Build documentation
run: | run: |
@ -74,13 +64,13 @@ jobs:
echo "${YELLOW}Deploying to ${BLUE}Meli ${YELLOW}on branch ${GREEN}$CI_ACTION_REF_NAME_SLUG${YELLOW}...\n" echo "${YELLOW}Deploying to ${BLUE}Meli ${YELLOW}on branch ${GREEN}$CI_ACTION_REF_NAME_SLUG${YELLOW}...\n"
npx -p "@getmeli/cli" meli upload ./site \ npx -p "@getmeli/cli" meli upload ./site \
--url "https://meli.csw.im" \ --url "https://pages.coastalcommits.com" \
--site "${{ vars.MELI_SITE_ID }}" \ --site "${{ vars.MELI_SITE_ID }}" \
--token "${{ secrets.MELI_TOKEN }}" \ --token "${{ secrets.MELI_TOKEN }}" \
--release "$CI_ACTION_REF_NAME_SLUG/${{ env.GITHUB_SHA }}" \ --release "$CI_ACTION_REF_NAME_SLUG/${{ env.GITHUB_SHA }}" \
--branch "$CI_ACTION_REF_NAME_SLUG" --branch "$CI_ACTION_REF_NAME_SLUG"
echo "\n${YELLOW}Deployed to ${BLUE}Meli ${YELLOW}on branch ${GREEN}$CI_ACTION_REF_NAME_SLUG${YELLOW}!" echo "\n${YELLOW}Deployed to ${BLUE}Meli ${YELLOW}on branch ${GREEN}$CI_ACTION_REF_NAME_SLUG${YELLOW}!"
echo "${GREEN}https://$CI_ACTION_REF_NAME_SLUG.seacogs.csw.im/" echo "${GREEN}https://$CI_ACTION_REF_NAME_SLUG.seacogs.coastalcommits.com/"
env: env:
GITEA_TOKEN: ${{ secrets.COASTALCOMMITSTOKEN }} GITEA_TOKEN: ${{ secrets.COASTALCOMMITSTOKEN }}

View file

@ -1,56 +1,27 @@
# SeaCogs # SeaCogs
[![Discord](https://img.shields.io/discord/1070058354925383681?logo=discord&color=%235661f6)](https://discord.gg/eMUMe77Yb8) [![Discord](https://img.shields.io/discord/1070058354925383681?logo=discord&color=%235661f6)](https://discord.gg/eMUMe77Yb8)
[![Documentation](https://img.shields.io/badge/docs-CoastalCommits%20Pages-3e83fd?logo=materialformkdocs)](https://seacogs.csw.im) [![Documentation](https://img.shields.io/badge/docs-CoastalCommits%20Pages-3e83fd?logo=materialformkdocs)](https://seacogs.coastalcommits.com)
![Python Versions](https://img.shields.io/badge/python-3.10%20%7C%203.11-%233776ab?logo=python) ![Python Versions](https://img.shields.io/badge/python-3.10%20%7C%203.11-%233776ab?logo=python)
My assorted cogs for Red-DiscordBot. My assorted cogs for Red-DiscordBot.
## Developing ## Development
You'll need some prerequisites before you can start working on my cogs. To get started with a development environment, first clone this repository.
[git](https://git-scm.com) - [uv](https://docs.astral.sh/uv)
Additionally, I recommend a code editor of some variety. [Visual Studio Code](https://code.visualstudio.com) is a good, beginner-friendly option.
### Installing Prerequisites ```sh
git clone https://coastalcommits.com/cswimr/SeaCogs.git
_This section of the guide only applies to Windows systems.
If you're on Linux, refer to the documentation of the projects listed above. I also offer a [Nix Flake](./flake.nix) that contains all of the required prerequisites, if you're a Nix user._
#### [`git`](https://git-scm.com)
You can download git from the [git download page](https://git-scm.com/downloads/win).
Alternatively, you can use `winget`:
```ps1
winget install --id=Git.Git -e --source=winget
``` ```
#### [`uv`](https://docs.astral.sh/uv) Then, install Poetry.
You can install uv with the following Powershell command: ```sh
pip install poetry
```ps1
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
``` ```
Alternatively, you can use `winget`: Finally, use Poetry to create a virtual environment with all of the dependencies required by my cogs.
```ps1 ```sh
winget install --id=astral-sh.uv -e poetry install
```
### Getting the Source Code
Once you have [`git`](https://git-scm.com) installed, you can use the `git clone` command to get a copy of the repository on your system.
```bash
git clone https://c.csw.im/cswimr/SeaCogs.git
```
Then, you can use `uv` to install the Python dependencies required for development.
```bash
uv sync --frozen
``` ```

File diff suppressed because it is too large Load diff

View file

@ -1,34 +1,33 @@
# pylint: disable=duplicate-code # pylint: disable=duplicate-code
import json import json
from datetime import timedelta import os
from typing import Dict from time import time
from typing import Dict, List
from discord import ButtonStyle, Interaction, Message, ui from discord import ButtonStyle, File, Interaction, Message, ui
from redbot.core import commands from redbot.core import commands, data_manager
from redbot.core.utils.chat_formatting import box, warning from redbot.core.utils.chat_formatting import warning
from ..utilities.database import connect, create_guild_table, mysql_log from ..models.moderation import Moderation
from ..models.type import Type, type_registry
from ..utilities.json import dump
from ..utilities.utils import create_guild_table, timedelta_from_string
class ImportAuroraView(ui.View): class ImportAuroraView(ui.View):
def __init__(self, timeout, ctx, message): def __init__(self, timeout, ctx, message, data: List[Dict[str, any]]):
super().__init__() super().__init__()
self.ctx: commands.Context = ctx self.ctx: commands.Context = ctx
self.message: Message = message self.message: Message = message
self.data: List[Dict[str, any]] = data
@ui.button(label="Yes", style=ButtonStyle.success) @ui.button(label="Yes", style=ButtonStyle.success)
async def import_button_y(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument async def import_button_y(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
await self.message.delete() await self.message.delete()
await interaction.response.send_message("Deleting original table...", ephemeral=True) await interaction.response.send_message("Deleting original table...", ephemeral=True)
database = connect()
cursor = database.cursor()
query = f"DROP TABLE IF EXISTS moderation_{self.ctx.guild.id};" query = f"DROP TABLE IF EXISTS moderation_{self.ctx.guild.id};"
cursor.execute(query) await Moderation.execute(query=query, return_obj=False)
cursor.close()
database.commit()
await interaction.edit_original_response(content="Creating new table...") await interaction.edit_original_response(content="Creating new table...")
@ -36,68 +35,91 @@ class ImportAuroraView(ui.View):
await interaction.edit_original_response(content="Importing moderations...") await interaction.edit_original_response(content="Importing moderations...")
file = await self.ctx.message.attachments[0].read()
data: list[dict] = sorted(json.loads(file), key=lambda x: x["moderation_id"])
user_mod_types = ["NOTE", "WARN", "ADDROLE", "REMOVEROLE", "MUTE", "UNMUTE", "KICK", "TEMPBAN", "BAN", "UNBAN"]
channel_mod_types = ["SLOWMODE", "LOCKDOWN"]
failed_cases = [] failed_cases = []
for case in data: for case in self.data:
if case["moderation_id"] == 0: if case["moderation_id"] == 0:
continue continue
moderation_type: Type = type_registry[case["moderation_type"].lower()]
if "target_type" not in case or not case["target_type"]: if "target_type" not in case or not case["target_type"]:
if case["moderation_type"] in user_mod_types: if moderation_type.channel:
case["target_type"] = "USER" case["target_type"] = "channel"
elif case["moderation_type"] in channel_mod_types:
case["target_type"] = "CHANNEL"
else: else:
case["target_type"] = "USER" case["target_type"] = "user"
if "role_id" not in case or not case["role_id"]: if "role_id" not in case or not case["role_id"]:
case["role_id"] = 0 case["role_id"] = None
else:
case["role_id"] = int(case["role_id"])
if "changes" not in case or not case["changes"]: case["target_id"] = int(case["target_id"])
case["changes"] = [] case["moderator_id"] = int(case["moderator_id"])
changes = case.get("changes", None)
if not changes:
changes = []
else:
if not isinstance(changes, list):
changes = json.loads(changes)
if isinstance(changes, str):
changes: list[dict] = json.loads(changes)
for change in changes:
if "bot" in change:
del change["bot"]
if "metadata" not in case: if "metadata" not in case:
metadata = {} metadata = {}
else: else:
metadata: Dict[str, any] = json.loads(case["metadata"]) if isinstance(case["metadata"], str):
metadata: Dict[str, any] = json.loads(case["metadata"])
else:
metadata = case["metadata"]
if not metadata.get("imported_from"): if not metadata.get("imported_from"):
metadata.update({"imported_from": "Aurora"}) metadata.update({"imported_from": "Aurora"})
metadata.update({"imported_timestamp": int(time())})
if case["duration"] != "NULL": if case["duration"] != "NULL" and case["duration"] is not None:
hours, minutes, seconds = map(int, case["duration"].split(":")) duration = timedelta_from_string(case["duration"])
duration = timedelta(hours=hours, minutes=minutes, seconds=seconds) if moderation_type.key == "ban":
moderation_type = type_registry["tempban"]
else: else:
duration = "NULL" duration = None
await mysql_log( try:
self.ctx.guild.id, await Moderation.log(
case["moderator_id"], bot=interaction.client,
case["moderation_type"], guild_id=self.ctx.guild.id,
case["target_type"], moderator_id=case["moderator_id"],
case["target_id"], moderation_type=moderation_type,
case["role_id"], target_type=case["target_type"].lower(),
duration, target_id=case["target_id"],
case["reason"], role_id=case["role_id"],
timestamp=case["timestamp"], duration=duration,
resolved=case["resolved"], reason=case["reason"],
resolved_by=case["resolved_by"], timestamp=case["timestamp"],
resolved_reason=case["resolve_reason"], resolved=case["resolved"],
expired=case["expired"], resolved_by=case["resolved_by"],
changes=case["changes"], resolved_reason=case["resolve_reason"],
metadata=metadata, expired=case["expired"],
database=database, changes=changes,
) metadata=metadata,
return_obj=False,
)
except Exception as e: # pylint: disable=broad-exception-caught
failed_cases.append(str(case["moderation_id"]) + f": {e}")
await interaction.edit_original_response(content="Import complete.") await interaction.edit_original_response(content="Import complete.")
if failed_cases: if failed_cases:
await interaction.edit_original_response(content="Import complete.\n" + warning("Failed to import the following cases:\n") + box(failed_cases)) filename = str(data_manager.cog_data_path(cog_instance=self)) + str(os.sep) + f"failed_cases_{interaction.guild.id}.json"
with open(filename, "w", encoding="utf-8") as f:
dump(obj=failed_cases, fp=f, indent=2)
await interaction.channel.send(content="Import complete.\n" + warning("Failed to import the following cases:\n"), file=File(filename, f"failed_cases_{interaction.guild.id}.json"))
os.remove(filename)
@ui.button(label="No", style=ButtonStyle.danger) @ui.button(label="No", style=ButtonStyle.danger)
async def import_button_n(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument async def import_button_n(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument

View file

@ -1,18 +1,21 @@
# pylint: disable=duplicate-code # pylint: disable=duplicate-code
import json import json
from datetime import timedelta from datetime import timedelta
from time import time
from discord import ButtonStyle, Interaction, Message, ui from discord import ButtonStyle, Interaction, Message, ui
from redbot.core import commands from redbot.core import commands
from redbot.core.utils.chat_formatting import box, warning from redbot.core.utils.chat_formatting import box, warning
from ..utilities.database import connect, create_guild_table, mysql_log from ..models.moderation import Change, Moderation
from ..utilities.utils import create_guild_table
class ImportGalacticBotView(ui.View): class ImportGalacticBotView(ui.View):
def __init__(self, timeout, ctx, message): def __init__(self, timeout, ctx, message):
super().__init__() super().__init__()
self.ctx: commands.Context = ctx self.ctx: commands.Context = ctx
self.timeout = timeout
self.message: Message = message self.message: Message = message
@ui.button(label="Yes", style=ButtonStyle.success) @ui.button(label="Yes", style=ButtonStyle.success)
@ -20,14 +23,14 @@ class ImportGalacticBotView(ui.View):
await self.message.delete() await self.message.delete()
await interaction.response.send_message("Deleting original table...", ephemeral=True) await interaction.response.send_message("Deleting original table...", ephemeral=True)
database = connect() database = await Moderation.connect()
cursor = database.cursor() cursor = await database.cursor()
query = f"DROP TABLE IF EXISTS moderation_{self.ctx.guild.id};" query = f"DROP TABLE IF EXISTS moderation_{self.ctx.guild.id};"
cursor.execute(query) await cursor.execute(query)
cursor.close() await cursor.close()
database.commit() await database.commit()
await interaction.edit_original_response(content="Creating new table...") await interaction.edit_original_response(content="Creating new table...")
@ -63,12 +66,12 @@ class ImportGalacticBotView(ui.View):
if case["duration"] is not None and float(case["duration"]) != 0: if case["duration"] is not None and float(case["duration"]) != 0:
duration = timedelta(seconds=round(float(case["duration"]) / 1000)) duration = timedelta(seconds=round(float(case["duration"]) / 1000))
else: else:
duration = "NULL" duration = None
except OverflowError: except OverflowError:
failed_cases.append(case["case"]) failed_cases.append(case["case"])
continue continue
metadata = {"imported_from": "GalacticBot"} metadata = {"imported_from": "GalacticBot", "imported_timestamp": int(time())}
if case["type"] == "SLOWMODE": if case["type"] == "SLOWMODE":
metadata["seconds"] = case["data"]["seconds"] metadata["seconds"] = case["data"]["seconds"]
@ -92,37 +95,43 @@ class ImportGalacticBotView(ui.View):
if resolved_timestamp is None: if resolved_timestamp is None:
resolved_timestamp = timestamp resolved_timestamp = timestamp
changes = [ changes = [
{ Change.from_dict(
"type": "ORIGINAL", interaction.client,
"reason": case["reason"], {
"user_id": case["executor"], "type": "ORIGINAL",
"timestamp": timestamp, "reason": case["reason"],
}, "user_id": case["executor"],
{ "timestamp": timestamp,
"type": "RESOLVE", },
"reason": resolved_reason, ),
"user_id": resolved_by, Change.from_dict(
"timestamp": resolved_timestamp, interaction.client,
}, {
"type": "RESOLVE",
"reason": resolved_reason,
"user_id": resolved_by,
"timestamp": resolved_timestamp,
},
),
] ]
else: else:
resolved = 0 resolved = None
resolved_by = "NULL" resolved_by = None
resolved_reason = "NULL" resolved_reason = None
changes = [] changes = None
if case["reason"] and case["reason"] != "N/A": if case["reason"] and case["reason"] != "N/A":
reason = case["reason"] reason = case["reason"]
else: else:
reason = "NULL" reason = None
await mysql_log( await Moderation.log(
self.ctx.guild.id, self.ctx.guild.id,
case["executor"], case["executor"],
case["type"], case["type"],
case["targetType"], case["targetType"],
case["target"], case["target"],
0, None,
duration, duration,
reason, reason,
timestamp=timestamp, timestamp=timestamp,

View file

@ -9,6 +9,7 @@
"disabled": false, "disabled": false,
"min_bot_version": "3.5.0", "min_bot_version": "3.5.0",
"min_python_version": [3, 10, 0], "min_python_version": [3, 10, 0],
"requirements": ["pydantic", "aiosqlite", "phx-class-registry==5.1.1"],
"tags": [ "tags": [
"mod", "mod",
"moderate", "moderate",

View file

@ -1,20 +1,24 @@
from discord import ButtonStyle, Interaction, Message, ui from discord import ButtonStyle, Interaction, Message, ui
from discord.errors import NotFound
from redbot.core import commands from redbot.core import commands
from redbot.core.utils.chat_formatting import error from redbot.core.utils.chat_formatting import error
from aurora.utilities.config import config from ..utilities.config import config
from aurora.utilities.factory import addrole_embed from ..utilities.factory import addrole_embed
class Addrole(ui.View): class Addrole(ui.View):
def __init__(self, ctx: commands.Context, message: Message, timeout: int = None): def __init__(self, ctx: commands.Context, message: Message, timeout: int | None = None):
super().__init__() super().__init__()
self.ctx = ctx self.ctx = ctx
self.message = message self.message = message
self.timeout = timeout self.timeout = timeout
async def on_timeout(self): async def on_timeout(self):
await self.message.edit(view=None) try:
await self.message.edit(view=None)
except NotFound:
pass
@ui.select(cls=ui.RoleSelect, placeholder="Select a role", min_values=0, max_values=25) @ui.select(cls=ui.RoleSelect, placeholder="Select a role", min_values=0, max_values=25)
async def addrole_select(self, interaction: Interaction, select: ui.RoleSelect): async def addrole_select(self, interaction: Interaction, select: ui.RoleSelect):

View file

@ -1,20 +1,24 @@
from discord import ButtonStyle, Interaction, Message, ui from discord import ButtonStyle, Interaction, Message, ui
from discord.errors import NotFound
from redbot.core import commands from redbot.core import commands
from aurora.utilities.config import config from ..utilities.config import config
from aurora.utilities.factory import guild_embed from ..utilities.factory import guild_embed
from aurora.utilities.utils import create_pagesize_options from ..utilities.utils import create_pagesize_options
class Guild(ui.View): class Guild(ui.View):
def __init__(self, ctx: commands.Context, message: Message, timeout: int = None): def __init__(self, ctx: commands.Context, message: Message, timeout: int | None = None):
super().__init__() super().__init__()
self.ctx = ctx self.ctx = ctx
self.message = message self.message = message
self.timeout = timeout self.timeout = timeout
async def on_timeout(self): async def on_timeout(self):
await self.message.edit(view=None) try:
await self.message.edit(view=None)
except NotFound:
pass
@ui.button(label="Show Moderator", style=ButtonStyle.green, row=0) @ui.button(label="Show Moderator", style=ButtonStyle.green, row=0)
async def show_moderator(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument async def show_moderator(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
@ -37,7 +41,7 @@ class Guild(ui.View):
await interaction.message.edit(embed=await guild_embed(self.ctx)) await interaction.message.edit(embed=await guild_embed(self.ctx))
@ui.button(label="Respect Hierarchy", style=ButtonStyle.green, row=0) @ui.button(label="Respect Hierarchy", style=ButtonStyle.green, row=0)
async def respect_heirarchy(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument async def respect_hierarchy(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True) await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
return return

View file

@ -1,20 +1,24 @@
from discord import ButtonStyle, Interaction, Message, ui from discord import ButtonStyle, Interaction, Message, ui
from discord.errors import NotFound
from redbot.core import commands from redbot.core import commands
from redbot.core.utils.chat_formatting import error from redbot.core.utils.chat_formatting import error
from aurora.utilities.config import config from ..utilities.config import config
from aurora.utilities.factory import immune_embed from ..utilities.factory import immune_embed
class Immune(ui.View): class Immune(ui.View):
def __init__(self, ctx: commands.Context, message: Message, timeout: int = None): def __init__(self, ctx: commands.Context, message: Message, timeout: int | None = None):
super().__init__() super().__init__()
self.ctx = ctx self.ctx = ctx
self.message = message self.message = message
self.timeout = timeout self.timeout = timeout
async def on_timeout(self): async def on_timeout(self):
await self.message.edit(view=None) try:
await self.message.edit(view=None)
except NotFound:
pass
@ui.select(cls=ui.RoleSelect, placeholder="Select a role", min_values=0, max_values=25) @ui.select(cls=ui.RoleSelect, placeholder="Select a role", min_values=0, max_values=25)
async def immune_select(self, interaction: Interaction, select: ui.RoleSelect): async def immune_select(self, interaction: Interaction, select: ui.RoleSelect):

View file

@ -1,20 +1,24 @@
from discord import ButtonStyle, Interaction, Message, ui from discord import ButtonStyle, Interaction, Message, ui
from discord.errors import NotFound
from redbot.core import commands from redbot.core import commands
from aurora.utilities.config import config from ..utilities.config import config
from aurora.utilities.factory import overrides_embed from ..utilities.factory import overrides_embed
from aurora.utilities.utils import create_pagesize_options from ..utilities.utils import create_pagesize_options
class Overrides(ui.View): class Overrides(ui.View):
def __init__(self, ctx: commands.Context, message: Message, timeout: int = None): def __init__(self, ctx: commands.Context, message: Message, timeout: int | None = None):
super().__init__() super().__init__()
self.ctx = ctx self.ctx = ctx
self.message = message self.message = message
self.timeout = timeout self.timeout = timeout
async def on_timeout(self): async def on_timeout(self):
await self.message.edit(view=None) try:
await self.message.edit(view=None)
except NotFound:
pass
@ui.button(label="Auto Evidence Format", style=ButtonStyle.green, row=0) @ui.button(label="Auto Evidence Format", style=ButtonStyle.green, row=0)
async def auto_evidenceformat(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument async def auto_evidenceformat(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument

71
aurora/menus/types.py Normal file
View file

@ -0,0 +1,71 @@
from discord import ButtonStyle, Interaction, Message, ui
from discord.errors import NotFound
from redbot.core import commands
from ..models.type import Type
from ..utilities.config import config
from ..utilities.factory import type_embed
class Types(ui.View):
def __init__(self, ctx: commands.Context, message: Message, moderation_type: Type, timeout: int | None = None):
super().__init__()
self.ctx = ctx
self.message = message
self.type = moderation_type
self.timeout = timeout
async def on_timeout(self):
try:
await self.message.edit(view=None)
except NotFound:
pass
@ui.button(label="Show in History", style=ButtonStyle.green, row=0)
async def show_in_history(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
return
await interaction.response.defer()
current_setting = await config.custom("types", interaction.guild.id, self.type.key).show_in_history()
await config.custom("types", interaction.guild.id, self.type.key).show_in_history.set(not current_setting)
await interaction.message.edit(embed=await type_embed(self.ctx, self.type))
@ui.button(label="Show Moderator", style=ButtonStyle.green, row=0)
async def show_moderator(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
return
await interaction.response.defer()
current_setting = await config.custom("types", interaction.guild.id, self.type.key).show_moderator()
await config.custom("types", interaction.guild.id, self.type.key).show_moderator.set(not current_setting)
await interaction.message.edit(embed=await type_embed(self.ctx, self.type))
@ui.button(label="Use Discord Permissions", style=ButtonStyle.green, row=0)
async def use_discord_permissions(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
return
await interaction.response.defer()
current_setting = await config.custom("types", interaction.guild.id, self.type.key).use_discord_permissions()
await config.custom("types", interaction.guild.id, self.type.key).use_discord_permissions.set(not current_setting)
await interaction.message.edit(embed=await type_embed(self.ctx, self.type))
@ui.button(label="DM Users", style=ButtonStyle.green, row=0)
async def dm_users(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
return
await interaction.response.defer()
current_setting = await config.custom("types", interaction.guild.id, self.type.key).dm_users()
await config.custom("types", interaction.guild.id, self.type.key).dm_users.set(not current_setting)
await interaction.message.edit(embed=await type_embed(self.ctx, self.type))
@ui.button(label="Reset", style=ButtonStyle.red, row=1)
async def reset(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
return
await interaction.response.defer()
await config.custom("types", interaction.guild.id, self.type.key).clear()
await interaction.message.edit(embed=await type_embed(self.ctx, self.type))

View file

@ -0,0 +1,2 @@
from .moderation_types import * # noqa: F403
# This just imports all the built-in moderation types so they can be registered, as they aren't imported anywhere else.

34
aurora/models/base.py Normal file
View file

@ -0,0 +1,34 @@
from typing import Any, Optional
from discord import Guild
from pydantic import BaseModel, ConfigDict
from redbot.core.bot import Red
class AuroraBaseModel(BaseModel):
"""Base class for all models in Aurora."""
model_config = ConfigDict(ignored_types=(Red,), arbitrary_types_allowed=True)
bot: Red
def dump(self) -> dict:
return self.model_dump(exclude={"bot"})
def to_json(self, indent: int | None = None, file: Any | None = None, **kwargs) -> str:
from ..utilities.json import dump, dumps # pylint: disable=cyclic-import
return dump(self.dump(), file, indent=indent, **kwargs) if file else dumps(self.dump(), indent=indent, **kwargs)
class AuroraGuildModel(AuroraBaseModel):
"""Subclass of AuroraBaseModel that includes a guild_id attribute and a guild attribute."""
model_config = ConfigDict(ignored_types=(Red, Guild), arbitrary_types_allowed=True)
guild_id: int
guild: Optional[Guild] = None
def dump(self) -> dict:
return self.model_dump(exclude={"bot", "guild_id", "guild"})
def __repr__(self) -> str:
return f"<{self.__class__.__name__} guild_id={self.guild_id}>"

79
aurora/models/change.py Normal file
View file

@ -0,0 +1,79 @@
import json
from datetime import datetime, timedelta
from typing import Literal, Optional
from redbot.core.bot import Red
from ..utilities.utils import timedelta_from_string
from .base import AuroraBaseModel
from .partials import PartialUser
class Change(AuroraBaseModel):
type: Literal["ORIGINAL", "RESOLVE", "EDIT"]
timestamp: datetime
user_id: int
reason: Optional[str] = None
duration: Optional[timedelta] = None
end_timestamp: Optional[datetime] = None
@property
def unix_timestamp(self) -> int:
return int(self.timestamp.timestamp())
@property
def unix_end_timestamp(self) -> Optional[int]:
if self.end_timestamp:
return int(self.end_timestamp.timestamp())
return None
def __str__(self):
return f"{self.type} {self.user_id} {self.reason}"
def __repr__(self) -> str:
attrs = [
("type", self.type),
("timestamp", self.timestamp),
("user_id", self.user_id),
("reason", self.reason),
("duration", self.duration),
("end_timestamp", self.end_timestamp),
]
joined = " ".join(f"{key}={value!r}" for key, value in attrs)
return f"<{self.__class__.__name__} {joined}>"
async def get_user(self) -> "PartialUser":
return await PartialUser.from_id(self.bot, self.user_id)
@classmethod
def from_dict(cls, bot: Red, data: dict) -> "Change":
if isinstance(data, str):
data = json.loads(data)
if data.get("duration") and not isinstance(data["duration"], timedelta) and not data["duration"] == "NULL":
duration = timedelta_from_string(data["duration"])
elif data.get("duration") and isinstance(data["duration"], timedelta):
duration = data["duration"]
else:
duration = None
if data.get("end_timestamp") and not isinstance(data["end_timestamp"], datetime):
end_timestamp = datetime.fromtimestamp(data["end_timestamp"])
elif data.get("end_timestamp") and isinstance(data["end_timestamp"], datetime):
end_timestamp = data["end_timestamp"]
else:
end_timestamp = None
if not isinstance(data["timestamp"], datetime):
timestamp = datetime.fromtimestamp(data["timestamp"])
else:
timestamp = data["timestamp"]
try:
data["user_id"] = int(data["user_id"])
except ValueError:
data["user_id"] = 0
data.update({"timestamp": timestamp, "end_timestamp": end_timestamp, "duration": duration})
if "bot" in data:
del data["bot"]
return cls(bot=bot, **data)

576
aurora/models/moderation.py Normal file
View file

@ -0,0 +1,576 @@
import json
import sqlite3
from datetime import datetime, timedelta
from time import time
from typing import Dict, Iterable, List, Optional, Tuple, Union
import discord
from aiosqlite import Connection, Cursor, OperationalError, Row
from aiosqlite import connect as aiosqlite_connect
from redbot.core import data_manager
from redbot.core.bot import Red
from ..utilities.logger import logger
from ..utilities.utils import timedelta_to_string
from .base import AuroraGuildModel
from .change import Change
from .partials import PartialChannel, PartialRole, PartialUser
from .type import Type, type_registry
class Moderation(AuroraGuildModel):
"""This class represents a moderation case in the database.
Attributes:
bot (Red): The bot instance.
guild (discord.Guild): The guild the case belongs to.
moderation_id (int): The ID of the moderation case.
timestamp (datetime): The timestamp of the case.
moderation_type (Type): The type of moderation case.
target_type (str): The type of target. Should be either `user` or `channel`.
target_id (int): The ID of the target.
moderator_id (int): The ID of the moderator who issued the case.
role_id (int): The ID of the role, if applicable.
duration (timedelta): The duration of the case, if applicable.
end_timestamp (datetime): The end timestamp of the case, if applicable.
reason (str): The reason for the case.
resolved (bool): Whether the case is resolved.
resolved_by (int): The ID of the user who resolved the case.
resolve_reason (str): The reason the case was resolved.
expired (bool): Whether the case is expired.
changes (List[Change]): A list of changes to the case.
metadata (Dict): A dictionary of metadata stored with the case.
Properties:
id (int): The ID of the case.
type (Type): The type of the case.
unix_timestamp (int): The timestamp of the case as a Unix timestamp.
Methods:
get_moderator: Gets the moderator who issued the case.
get_target: Gets the target of the case.
get_resolved_by: Gets the user who resolved the case.
get_role: Gets the role, if applicable.
resolve: Resolves the case.
update: Updates the case in the database.
Class Methods:
from_dict: Creates a `Moderation` object from a dictionary.
from_result: Creates a `Moderation` object from a database result.
execute: Executes a query on the database.
get_latest: Gets the latest cases from the database.
get_next_case_number: Gets the next case number to use.
find_by_id: Finds a case by its ID.
find_by_target: Finds cases by the target.
find_by_moderator: Finds cases by the moderator.
log: Logs a moderation case in the database.
Static Methods:
connect: Connects to the SQLite database.
"""
moderation_id: int
timestamp: datetime
moderation_type: Type
target_type: str
target_id: int
moderator_id: int
role_id: Optional[int] = None
duration: Optional[timedelta] = None
end_timestamp: Optional[datetime] = None
reason: Optional[str] = None
resolved: bool
resolved_by: Optional[int] = None
resolve_reason: Optional[str] = None
expired: bool
changes: List["Change"]
metadata: Dict
@property
def id(self) -> int:
return self.moderation_id
@property
def type(self) -> Type:
return self.moderation_type
@property
def unix_timestamp(self) -> int:
return int(self.timestamp.timestamp())
async def get_moderator(self) -> "PartialUser":
return await PartialUser.from_id(self.bot, self.moderator_id)
async def get_target(self) -> Union["PartialUser", "PartialChannel"]:
if self.target_type.lower() == "user":
return await PartialUser.from_id(self.bot, self.target_id)
return await PartialChannel.from_id(self.bot, self.target_id, self.guild)
async def get_resolved_by(self) -> Optional["PartialUser"]:
if self.resolved_by:
return await PartialUser.from_id(self.bot, self.resolved_by)
return None
async def get_role(self) -> Optional["PartialRole"]:
if self.role_id:
return await PartialRole.from_id(self.bot, self.guild, self.role_id)
return None
def __str__(self) -> str:
return f"{self.moderation_type} {self.target_type} {self.target_id} {self.reason}"
def __int__(self) -> int:
return self.moderation_id
def __repr__(self) -> str:
attrs = [
("guild_id", self.guild_id),
("moderation_id", self.moderation_id),
("timestamp", self.timestamp),
("type", self.type),
("target_type", self.target_type),
("target_id", self.target_id),
("moderator_id", self.moderator_id),
("role_id", self.role_id),
("duration", self.duration),
("end_timestamp", self.end_timestamp),
("reason", self.reason),
("resolved", self.resolved),
("resolved_by", self.resolved_by),
("resolve_reason", self.resolve_reason),
("expired", self.expired),
("changes", self.changes),
("metadata", self.metadata),
]
joined = " ".join(f"{key}={value!r}" for key, value in attrs)
return f"<{self.__class__.__name__} {joined}>"
async def resolve(self, resolved_by: int, reason: str) -> Tuple[bool, str]:
if self.resolved:
raise ValueError("Case is already resolved!")
self.resolved = True
self.resolved_by = resolved_by
self.resolve_reason = reason
success, msg = await self.type.resolve_handler(moderation=self, reason=reason)
if not self.changes:
self.changes.append(
Change.from_dict(
self.bot,
{
"type": "ORIGINAL",
"timestamp": self.timestamp,
"reason": self.reason,
"user_id": self.moderator_id,
"duration": self.duration,
"end_timestamp": self.end_timestamp,
},
)
)
self.changes.append(
Change.from_dict(
self.bot,
{
"type": "RESOLVE",
"timestamp": datetime.now(),
"reason": reason,
"user_id": resolved_by,
},
)
)
await self.update()
return success, msg
async def update(self) -> None:
from ..utilities.json import dumps
query = f"UPDATE moderation_{self.guild_id} SET timestamp = ?, moderation_type = ?, target_type = ?, moderator_id = ?, role_id = ?, duration = ?, end_timestamp = ?, reason = ?, resolved = ?, resolved_by = ?, resolve_reason = ?, expired = ?, changes = ?, metadata = ? WHERE moderation_id = ?;"
await self.execute(
query,
(
self.timestamp.timestamp(),
self.moderation_type.key,
self.target_type,
self.moderator_id,
self.role_id,
timedelta_to_string(self.duration) if self.duration else None,
self.end_timestamp.timestamp() if self.end_timestamp else None,
self.reason,
self.resolved,
self.resolved_by,
self.resolve_reason,
self.expired,
dumps(self.changes),
dumps(self.metadata),
self.moderation_id,
),
)
logger.verbose(
"Row updated in moderation_%s!\n%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s",
self.moderation_id,
self.guild_id,
self.timestamp.timestamp(),
self.moderation_type.key,
self.target_type,
self.moderator_id,
self.role_id,
timedelta_to_string(self.duration) if self.duration else None,
self.end_timestamp.timestamp() if self.end_timestamp else None,
self.reason,
self.resolved,
self.resolved_by,
self.resolve_reason,
self.expired,
dumps(self.changes),
dumps(self.metadata),
)
@classmethod
async def from_dict(cls, bot: Red, data: dict) -> "Moderation":
if data.get("guild_id"):
try:
guild = bot.get_guild(data["guild_id"])
if not guild:
guild = await bot.fetch_guild(data["guild_id"])
except (discord.Forbidden, discord.HTTPException):
guild = None
data.update({"guild": guild})
return cls(bot=bot, **data)
@classmethod
async def from_result(cls, bot: Red, result: Iterable, guild_id: int) -> "Moderation":
if result[7] is not None and result[7] != "NULL":
try:
hours, minutes, seconds = map(int, result[7].split(":"))
duration = timedelta(hours=hours, minutes=minutes, seconds=seconds)
except ValueError as e:
logger.error("Error parsing duration for case %s: %s", result[0], result[7])
raise e
else:
duration = None
if result[14] is not None:
changes = json.loads(result[14])
change_obj_list = []
if changes:
for change in changes:
change_obj_list.append(Change.from_dict(bot=bot, data=change))
if result[15] is not None:
metadata = json.loads(result[15])
else:
metadata = {}
moderation_type = str.lower(result[2])
if moderation_type in type_registry:
moderation_type = type_registry[moderation_type]
else:
logger.error("Unknown moderation type in case %s: %s", result[0], result[2])
case = {
"moderation_id": int(result[0]),
"guild_id": int(guild_id),
"timestamp": datetime.fromtimestamp(result[1]),
"moderation_type": moderation_type,
"target_type": str(result[3]),
"target_id": int(result[4]),
"moderator_id": int(result[5]),
"role_id": int(result[6]) if result[6] is not None else None,
"duration": duration,
"end_timestamp": datetime.fromtimestamp(result[8]) if result[8] is not None else None,
"reason": result[9],
"resolved": bool(result[10]),
"resolved_by": result[11],
"resolve_reason": result[12],
"expired": bool(result[13]),
"changes": change_obj_list,
"metadata": metadata if metadata else {},
}
return await cls.from_dict(bot=bot, data=case)
@staticmethod
async def connect() -> Connection:
"""Connects to the SQLite database, and returns a connection object."""
try:
connection = await aiosqlite_connect(database=data_manager.cog_data_path(raw_name="Aurora") / "aurora.db")
return connection
except OperationalError as e:
logger.error("Unable to access the SQLite database!\nError:\n%s", e.msg)
raise ConnectionRefusedError(f"Unable to access the SQLite Database!\n{e.msg}") from e
@classmethod
async def execute(cls, query: str, parameters: tuple | None = None, bot: Red | None = None, guild_id: int | None = None, cursor: Cursor | None = None, return_obj: bool = True) -> Union[Tuple["Moderation"], Iterable[Row]]:
"""Executes a query on the database.
Arguments:
query (str): The query to execute.
parameters (tuple): The parameters to pass to the query.
bot (Red): The bot instance.
guild_id (int): The ID of the guild to execute the query on.
cursor (Cursor): The cursor to use for the query.
return_obj (bool): Whether to return the case object(s). Defaults to `True`. If `False`, returns a `Iterable` of `aiosqlite.Row` objects.
Returns: The result of the query, either as a `Tuple` of `Moderation` objects or an `Iterable` of `aiosqlite.Row` objects.
"""
logger.trace('Executing query: "%s" with parameters "%s"', query, parameters)
if not parameters:
parameters = ()
if not cursor:
no_cursor = True
database = await cls.connect()
cursor = await database.cursor()
else:
no_cursor = False
try:
await cursor.execute(query, parameters)
except OperationalError as e:
logger.error('Error executing query: "%s" with parameters "%s"\nError:\n%s', query, parameters, e)
raise OperationalError(f'Error executing query: "{query}" with parameters "{parameters}"') from e
results = await cursor.fetchall()
await database.commit()
if no_cursor:
await cursor.close()
await database.close()
if results and return_obj and bot and guild_id:
cases = []
for result in results:
if result[0] == 0:
continue
case = await cls.from_result(bot=bot, result=result, guild_id=guild_id)
cases.append(case)
return tuple(cases)
return results
@classmethod
async def get_latest(cls, bot: Red, guild_id: int, before: datetime | None = None, after: datetime | None = None, limit: int | None = None, offset: int = 0, types: Iterable[Type] | None = None, expired: bool | None = None, cursor: Cursor | None = None) -> Tuple["Moderation"]:
params = []
query = f"SELECT * FROM moderation_{guild_id}"
conditions = []
if types:
conditions.append(f"moderation_type IN ({', '.join(['?' for _ in types])})")
params.extend([t.key for t in types])
if before:
conditions.append("timestamp < ?")
params.append(int(before.timestamp()))
if after:
conditions.append("timestamp > ?")
params.append(int(after.timestamp()))
if expired is not None:
conditions.append("expired = ?")
params.append(int(expired))
if conditions:
query += " WHERE " + " AND ".join(conditions)
query += " ORDER BY moderation_id DESC"
if limit:
query += " LIMIT ? OFFSET ?"
params.extend((limit, offset))
query += ";"
return await cls.execute(bot=bot, guild_id=guild_id, query=query, parameters=tuple(params) if params else (), cursor=cursor)
@classmethod
async def get_next_case_number(cls, bot: Red, guild_id: int, cursor: Cursor | None = None) -> int:
result = await cls.get_latest(bot=bot, guild_id=guild_id, cursor=cursor, limit=1)
return (result[0].moderation_id + 1) if result else 1
@classmethod
async def find_by_id(cls, bot: Red, moderation_id: int, guild_id: int, cursor: Cursor | None = None) -> "Moderation":
query = f"SELECT * FROM moderation_{guild_id} WHERE moderation_id = ?;"
case = await cls.execute(bot=bot, guild_id=guild_id, query=query, parameters=(moderation_id,), cursor=cursor)
if case:
return case[0]
raise ValueError(f"Case {moderation_id} not found in moderation_{guild_id}!")
@classmethod
async def find_by_target(cls, bot: Red, guild_id: int, target: int, before: datetime = None, after: datetime = None, types: Iterable[Type] | None = None, expired: bool | None = None, cursor: Cursor | None = None) -> Tuple["Moderation"]:
query = f"SELECT * FROM moderation_{guild_id} WHERE target_id = ?"
params = [target]
if types:
query += f" AND moderation_type IN ({', '.join(['?' for _ in types])})"
for t in types:
params.append(t.key)
if before:
query += " AND timestamp < ?"
params.append(int(before.timestamp()))
if after:
query += " AND timestamp > ?"
params.append(int(after.timestamp()))
if expired is not None:
query += " AND expired = ?"
params.append(int(expired))
query += " ORDER BY moderation_id DESC;"
return await cls.execute(bot=bot, guild_id=guild_id, query=query, parameters=params, cursor=cursor)
@classmethod
async def find_by_moderator(cls, bot: Red, guild_id: int, moderator: int, before: datetime = None, after: datetime = None, types: Iterable[Type] | None = None, expired: bool | None = None, cursor: Cursor | None = None) -> Tuple["Moderation"]:
query = f"SELECT * FROM moderation_{guild_id} WHERE moderator_id = ?"
params = [moderator]
if types:
query += f" AND moderation_type IN ({', '.join(['?' for _ in types])})"
for t in types:
params.append(t.key)
if before:
query += " AND timestamp < ?"
params.append(int(before.timestamp()))
if after:
query += " AND timestamp > ?"
params.append(int(after.timestamp()))
if expired is not None:
query += " AND expired = ?"
params.append(int(expired))
query += " ORDER BY moderation_id DESC;"
return await cls.execute(bot=bot, guild_id=guild_id, query=query, parameters=params, cursor=cursor)
@classmethod
async def log(
cls,
bot: Red,
guild_id: int,
moderator_id: int,
moderation_type: Type,
target_type: str,
target_id: int,
role_id: int | None = None,
duration: timedelta | None = None,
reason: str | None = None,
database: sqlite3.Connection | None = None,
timestamp: datetime | None = None,
resolved: bool = False,
resolved_by: int | None = None,
resolved_reason: str | None = None,
expired: bool | None = None,
changes: list | None = None,
metadata: dict | None = None,
return_obj: bool = True,
) -> Union["Moderation", int]:
"""Logs a moderation case in the database.
Args:
bot (Red): The bot instance.
guild_id (int): The ID of the guild to log the case in.
moderator_id (int): The ID of the moderator who issued the case.
moderation_type (Type): The type of moderation case. See `aurora.models.moderation_types` for the built-in options.
target_type (str): The type of target. Should be either `user` or `channel`.
target_id (int): The ID of the target.
role_id (int): The ID of the role, if applicable.
duration (timedelta): The duration of the case, if applicable.
reason (str): The reason for the case.
database (sqlite3.Connection): The database connection to use to log the case. A connection will be automatically created if not provided.
timestamp (datetime): The timestamp of the case. Will be automatically generated if not provided.
resolved (bool): Whether the case is resolved.
resolved_by (int): The ID of the user who resolved the case.
resolved_reason (str): The reason the case was resolved.
expired (bool): Whether the case is expired.
changes (list): A list of changes to log. You usually shouldn't pass this, as it's automatically generated by the `/edit` and `/resolve` commands.
metadata (dict): A dictionary of metadata to store with the case.
return_obj (bool): Whether to return the case object. Defaults to `True`. If `False`, returns the case ID.
Returns:
Union[Moderation, int]: The `Moderation` object if `return_obj` is `True`, otherwise the case ID.
"""
from ..utilities.json import dumps
if not timestamp:
timestamp = datetime.fromtimestamp(time())
elif not isinstance(timestamp, datetime):
timestamp = datetime.fromtimestamp(timestamp)
if duration == "NULL":
duration = None
if duration is not None:
end_timestamp = timestamp + duration
else:
duration = None
end_timestamp = None
if not expired:
if end_timestamp:
expired = bool(timestamp > end_timestamp)
else:
expired = False
if reason == "NULL":
reason = None
if resolved_by in ["NULL", "?"]:
resolved_by = None
if resolved_reason == "NULL":
resolved_reason = None
if role_id == 0:
role_id = None
if not database:
database = await cls.connect()
close_db = True
else:
close_db = False
moderation_id = await cls.get_next_case_number(bot=bot, guild_id=guild_id)
case = {
"moderation_id": moderation_id,
"timestamp": timestamp.timestamp(),
"moderation_type": moderation_type.key,
"target_type": target_type,
"target_id": target_id,
"moderator_id": moderator_id,
"role_id": role_id,
"duration": timedelta_to_string(duration) if duration else None,
"end_timestamp": end_timestamp.timestamp() if end_timestamp else None,
"reason": reason,
"resolved": resolved,
"resolved_by": resolved_by,
"resolve_reason": resolved_reason,
"expired": expired,
"changes": dumps(changes),
"metadata": dumps(metadata),
}
sql = f"INSERT INTO `moderation_{guild_id}` (moderation_id, timestamp, moderation_type, target_type, target_id, moderator_id, role_id, duration, end_timestamp, reason, resolved, resolved_by, resolve_reason, expired, changes, metadata) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
await database.execute(sql, tuple(case.values()))
await database.commit()
if close_db:
await database.close()
logger.verbose(
"Row inserted into moderation_%s!\n%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s",
guild_id,
case["moderation_id"],
case["timestamp"],
case["moderation_type"],
case["target_type"],
case["target_id"],
case["moderator_id"],
case["role_id"],
case["duration"],
case["end_timestamp"],
case["reason"],
case["resolved"],
case["resolved_by"],
case["resolve_reason"],
case["expired"],
case["changes"],
case["metadata"],
)
if return_obj:
return await cls.find_by_id(bot=bot, moderation_id=moderation_id, guild_id=guild_id)
return moderation_id

View file

@ -0,0 +1,962 @@
# pylint: disable=abstract-method
from datetime import timedelta
from math import ceil
from time import time
from typing import Tuple
from discord import AllowedMentions, File, Interaction, Member, Object, Role, TextChannel, User
from discord.abc import Messageable
from discord.errors import Forbidden, HTTPException, NotFound
from redbot.core import app_commands, commands
from redbot.core.bot import Red
from redbot.core.commands.converter import parse_relativedelta, parse_timedelta
from redbot.core.utils.chat_formatting import bold, error, humanize_timedelta, inline
from ..utilities.config import config
from ..utilities.factory import message_factory, resolve_factory
from ..utilities.logger import logger
from ..utilities.utils import get_footer_image, log, send_evidenceformat, timedelta_from_relativedelta
from .moderation import Moderation
from .type import Type, type_registry
def get_icon(bot: Red) -> File:
cog = bot.get_cog("Aurora")
if cog:
return get_footer_image(cog)
raise ValueError("Aurora cog not found. How was this managed?")
class Note(Type):
key = "note"
string = "note"
verb = "noted"
def void(self) -> None:
return None
@classmethod
async def handler(cls, ctx: commands.Context, target: Member | User, silent: bool, reason: str) -> "Note":
response = await ctx.send(content=f"{target.mention} has {cls.embed_desc}{cls.verb}!\n**Reason** - `{reason}`")
if silent is False:
try:
embed = await message_factory(
bot=ctx.bot,
color=await ctx.embed_color(),
guild=ctx.guild,
moderator=ctx.author,
reason=reason,
moderation_type=cls(),
response=response,
)
await target.send(embed=embed, file=get_icon(ctx.bot))
except HTTPException:
pass
moderation = await Moderation.log(
bot=ctx.bot,
guild_id=ctx.guild.id,
moderator_id=ctx.author.id,
moderation_type=cls(),
target_type="user",
target_id=target.id,
role_id=None,
duration=None,
reason=reason,
)
await response.edit(content=f"{target.mention} has {cls.embed_desc}{cls.verb}! (Case `#{moderation.id:,}`)\n**Reason** - `{reason}`")
await log(ctx=ctx, moderation_id=moderation.id)
await send_evidenceformat(ctx=ctx, moderation_id=moderation.id)
return cls()
@classmethod
async def resolve_handler(cls, moderation: Moderation, reason: str) -> Tuple[bool, str]:
if await config.guild(moderation.guild).dm_users() is True:
try:
target = await moderation.bot.fetch_user(moderation.target_id)
embed = await resolve_factory(moderation=moderation, reason=reason)
await target.send(embed=embed, file=get_icon(bot=moderation.bot))
except (Forbidden, HTTPException, NotFound):
pass
return True, ""
class Warn(Type):
key = "warn"
string = "warn"
verb = "warned"
def void(self) -> None:
return None
@classmethod
async def handler(cls, ctx: commands.Context, target: Member | User, silent: bool, reason: str) -> "Warn":
response = await ctx.send(content=f"{target.mention} has {cls.embed_desc}{cls.verb}!\n**Reason** - `{reason}`")
if silent is False:
try:
embed = await message_factory(
bot=ctx.bot,
color=await ctx.embed_color(),
guild=ctx.guild,
moderator=ctx.author,
reason=reason,
moderation_type=cls(),
response=response,
)
await target.send(embed=embed, file=get_icon(ctx.bot))
except HTTPException:
pass
moderation = await Moderation.log(
bot=ctx.bot,
guild_id=ctx.guild.id,
moderator_id=ctx.author.id,
moderation_type=cls(),
target_type="user",
target_id=target.id,
role_id=None,
duration=None,
reason=reason,
)
await response.edit(content=f"{target.mention} has {cls.embed_desc}{cls.verb}! (Case `#{moderation.id:,}`)\n**Reason** - `{reason}`")
await log(ctx=ctx, moderation_id=moderation.id)
await send_evidenceformat(ctx=ctx, moderation_id=moderation.id)
return cls()
@classmethod
async def resolve_handler(cls, moderation: Moderation, reason: str) -> Tuple[bool, str]:
if await config.guild(moderation.guild).dm_users() is True:
try:
target = await moderation.bot.fetch_user(moderation.target_id)
embed = await resolve_factory(moderation=moderation, reason=reason)
await target.send(embed=embed, file=get_icon(bot=moderation.bot))
except (Forbidden, HTTPException, NotFound):
pass
return True, ""
class AddRole(Type):
key = "addrole"
string = "addrole"
verb = "added a role to"
embed_desc = "been given the "
def void(self) -> None:
return None
@classmethod
async def handler(cls, ctx: commands.Context, target: Member, role: Role, silent: bool, duration: str | None = None, reason: str | None = None):
addrole_whitelist = await config.guild(ctx.guild).addrole_whitelist()
if not addrole_whitelist:
await ctx.send(
content=error("There are no whitelisted roles set for this server!"),
ephemeral=True,
)
return None
if duration is not None:
try:
parsed_time = parse_relativedelta(argument=duration)
if parsed_time is None:
raise commands.BadArgument()
parsed_time = timedelta_from_relativedelta(relativedelta=parsed_time)
except (commands.BadArgument, ValueError):
await ctx.send(content=error(text="Please provide a valid duration!"), ephemeral=True)
return cls()
else:
parsed_time = None
if role.id not in addrole_whitelist:
await ctx.send(content=error("That role isn't whitelisted!"), ephemeral=True)
return None
if role.id in [user_role.id for user_role in target.roles]:
await ctx.send(
content=error(f"{target.mention} already has this role!"),
ephemeral=True,
)
return None
response = await ctx.send(content=f"{target.mention} has {cls.embed_desc}{role.mention} role{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time else ''}!\n**Reason** - `{reason}`")
if silent is False:
try:
embed = await message_factory(
bot=ctx.bot,
color=await ctx.embed_color(),
guild=ctx.guild,
moderator=ctx.author,
reason=reason,
moderation_type=cls(),
response=response,
duration=parsed_time,
)
await target.send(embed=embed, file=get_icon(ctx.bot))
except HTTPException:
pass
await target.add_roles(
role,
reason=f"Role added by {ctx.author.id}{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time else ''} for: {reason}",
)
moderation = await Moderation.log(
bot=ctx.bot,
guild_id=ctx.guild.id,
moderator_id=ctx.author.id,
moderation_type=cls(),
target_type="user",
target_id=target.id,
role_id=role.id,
duration=parsed_time,
reason=reason,
)
await response.edit(
content=f"{target.mention} has {cls.embed_desc}{role.mention} role{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time else ''}! (Case `#{moderation.id:,}`)\n**Reason** - `{reason}`",
)
await log(ctx=ctx, moderation_id=moderation.id)
await send_evidenceformat(ctx=ctx, moderation_id=moderation.id)
return cls()
@classmethod
async def duration_edit_handler(cls, interaction: Interaction, old_moderation: Moderation, new_moderation: Moderation) -> bool: # pylint: disable=unused-argument
return True
@classmethod
async def expiry_handler(cls, moderation: Moderation) -> int:
try:
target = moderation.guild.get_member(moderation.target_id)
if not target:
try:
target = await moderation.guild.fetch_member(moderation.target_id)
except NotFound:
return 0
await target.remove_roles(Object(moderation.role_id), reason=f"Automatic role removal from case #{moderation.id}")
if await config.guild(moderation.guild).dm_users() is True:
try:
embed = await message_factory(
bot=moderation.bot,
color=await moderation.bot.get_embed_color(moderation.guild.channels[0]),
guild=moderation.guild,
reason=f"Automatic role removal from case #{moderation.id}",
moderation_type=type_registry["removerole"],
moderator=None,
duration=None,
response=None,
case=False,
)
await target.send(embed=embed, file=get_icon(bot=moderation.bot))
except HTTPException:
pass
logger.trace(
"Removed role %s from %s (%s)",
moderation.role_id,
target.name,
target.id,
)
return 1
except (
NotFound,
Forbidden,
HTTPException,
) as e:
logger.error(
"Removing the role %s from user %s failed due to: \n%s",
moderation.role_id,
moderation.target_id,
e,
)
return 0
@classmethod
async def resolve_handler(cls, moderation: Moderation, reason: str) -> Tuple[bool, str]:
try:
target = await moderation.guild.fetch_member(moderation.target_id)
await target.remove_roles(Object(moderation.role_id), reason=reason)
if await config.guild(moderation.guild).dm_users() is True:
try:
embed = await resolve_factory(moderation=moderation, reason=reason)
await target.send(embed=embed, file=get_icon(bot=moderation.bot))
except HTTPException:
pass
logger.trace(
"Removed role %s from %s (%s)",
moderation.role_id,
target.name,
target.id,
)
return True, ""
except (NotFound, Forbidden, HTTPException) as e:
logger.error(
"Failed to remove role %s from user %s (%s)\n%s",
moderation.role_id,
target.name,
target.id,
e,
)
return False, "Failed to remove role from user."
class RemoveRole(Type):
key = "removerole"
string = "removerole"
verb = "removed a role from"
embed_desc = "had the "
def void(self) -> None:
return None
@classmethod
async def handler(cls, ctx: commands.Context, target: Member, role: Role, silent: bool, duration: str | None = None, reason: str | None = None):
addrole_whitelist = await config.guild(ctx.guild).addrole_whitelist()
if not addrole_whitelist:
await ctx.send(
content=error("There are no whitelisted roles set for this server!"),
ephemeral=True,
)
return None
if duration is not None:
try:
parsed_time = parse_relativedelta(argument=duration)
if parsed_time is None:
raise commands.BadArgument()
parsed_time = timedelta_from_relativedelta(relativedelta=parsed_time)
except (commands.BadArgument, ValueError):
await ctx.send(content=error(text="Please provide a valid duration!"), ephemeral=True)
return cls()
else:
parsed_time = None
if role.id not in addrole_whitelist:
await ctx.send(content=error("That role isn't whitelisted!"), ephemeral=True)
return None
if role.id not in [user_role.id for user_role in target.roles]:
await ctx.send(
content=error(f"{target.mention} does not have this role!"),
ephemeral=True,
)
return None
response = await ctx.send(content=f"{target.mention} has {cls.embed_desc}{role.mention} role removed{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time else ''}!\n**Reason** - `{reason}`")
if silent is False:
try:
embed = await message_factory(
bot=ctx.bot,
color=await ctx.embed_color(),
guild=ctx.guild,
moderator=ctx.author,
reason=reason,
moderation_type=cls(),
response=response,
duration=parsed_time,
)
await target.send(embed=embed, file=get_icon(ctx.bot))
except HTTPException:
pass
await target.remove_roles(
role,
reason=f"Role removed by {ctx.author.id}{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time else ''} for: {reason}",
)
moderation = await Moderation.log(
bot=ctx.bot,
guild_id=ctx.guild.id,
moderator_id=ctx.author.id,
moderation_type=cls(),
target_type="user",
target_id=target.id,
role_id=role.id,
duration=parsed_time,
reason=reason,
)
await response.edit(
content=f"{target.mention} has {cls.embed_desc}{role.mention} role removed{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time else ''}! (Case `#{moderation.id:,}`)\n**Reason** - `{reason}`",
)
await log(ctx=ctx, moderation_id=moderation.id)
await send_evidenceformat(ctx=ctx, moderation_id=moderation.id)
return cls()
@classmethod
async def duration_edit_handler(cls, interaction: Interaction, old_moderation: Moderation, new_moderation: Moderation) -> bool: # pylint: disable=unused-argument
return True
@classmethod
async def expiry_handler(cls, moderation: Moderation) -> int:
try:
target = moderation.guild.get_member(moderation.target_id)
if not target:
try:
target = await moderation.guild.fetch_member(moderation.target_id)
except NotFound:
return 0
await target.add_roles(Object(moderation.role_id), reason=f"Automatic role addition from case #{moderation.id}")
if await config.guild(moderation.guild).dm_users() is True:
try:
embed = await message_factory(
bot=moderation.bot,
color=await moderation.bot.get_embed_color(moderation.guild.channels[0]),
guild=moderation.guild,
reason=f"Automatic role addition from case #{moderation.id}",
moderation_type=type_registry["addrole"],
moderator=None,
duration=None,
response=None,
case=False,
)
await target.send(embed=embed, file=get_icon(bot=moderation.bot))
except HTTPException:
pass
logger.trace(
"Added role %s to %s (%s)",
moderation.role_id,
target.name,
target.id,
)
return 1
except (
NotFound,
Forbidden,
HTTPException,
) as e:
logger.error(
"Adding the role %s to user %s failed due to: \n%s",
moderation.role_id,
moderation.target_id,
e,
)
return 0
@classmethod
async def resolve_handler(cls, moderation: Moderation, reason: str) -> Tuple[bool, str]:
try:
target = await moderation.get_target()
await target.add_roles(Object(moderation.role_id), reason=reason)
if await config.guild(moderation.guild).dm_users() is True:
try:
embed = await resolve_factory(moderation=moderation, reason=reason)
await target.send(embed=embed, file=get_icon(bot=moderation.bot))
except HTTPException:
pass
logger.trace(
"Added role %s to %s (%s)",
moderation.role_id,
target.name,
target.id,
)
return True, ""
except (NotFound, Forbidden, HTTPException) as e:
logger.error(
"Failed to add role %s to user %s (%s)\n%s",
moderation.role_id,
target.name,
target.id,
e,
)
return False, "Failed to add role to user."
class Mute(Type):
key = "mute"
string = "mute"
verb = "muted"
def void(self) -> None:
return None
@classmethod
async def handler(cls, ctx: commands.Context, target: Member, silent: bool, duration: str, reason: str = None):
if target.is_timed_out() is True:
await ctx.send(
error(f"{target.mention} is already muted!"),
allowed_mentions=AllowedMentions(users=False),
ephemeral=True,
)
return None
try:
parsed_time = parse_timedelta(duration, maximum=timedelta(days=28))
if parsed_time is None:
await ctx.send(error("Please provide a valid duration!"), ephemeral=True)
return None
except commands.BadArgument:
await ctx.send(error("Please provide a duration that is less than 28 days."), ephemeral=True)
return None
await target.timeout(parsed_time, reason=f"Muted by {ctx.author.id} for: {reason}")
response = await ctx.send(content=f"{target.mention} has been muted for {humanize_timedelta(timedelta=parsed_time)}!\n**Reason** - `{reason}`")
if silent is False:
try:
embed = await message_factory(
bot=ctx.bot,
color=await ctx.embed_color(),
guild=ctx.guild,
moderator=ctx.author,
reason=reason,
moderation_type=cls(),
response=response,
duration=parsed_time,
)
await target.send(embed=embed, file=get_icon(ctx.bot))
except HTTPException:
pass
moderation = await Moderation.log(
bot=ctx.bot,
guild_id=ctx.guild.id,
moderator_id=ctx.author.id,
moderation_type=cls(),
target_type="user",
target_id=target.id,
role_id=None,
duration=parsed_time,
reason=reason,
)
await response.edit(content=f"{target.mention} has been muted for {humanize_timedelta(timedelta=parsed_time)}! (Case `#{moderation.id:,}`)\n**Reason** - `{reason}`")
await log(ctx=ctx, moderation_id=moderation.id)
await send_evidenceformat(ctx=ctx, moderation_id=moderation.id)
return cls()
@classmethod
async def resolve_handler(cls, moderation: Moderation, reason: str) -> Tuple[bool, str]:
try:
target = await moderation.guild.fetch_member(moderation.target_id)
except (Forbidden, HTTPException, NotFound):
return False, "User is not in the server, so I cannot unmute them."
if target.is_timed_out() is False:
return True, ""
await target.timeout(None, reason=reason)
if await config.guild(moderation.guild).dm_users() is True:
try:
embed = await resolve_factory(moderation=moderation, reason=reason)
await target.send(embed=embed, file=get_icon(bot=moderation.bot))
except (Forbidden, HTTPException):
pass
return True, ""
@classmethod
async def duration_edit_handler(cls, interaction: Interaction, old_moderation: Moderation, new_moderation: Moderation) -> bool: # pylint: disable=unused-argument
if (time() - new_moderation.unix_timestamp) + new_moderation.duration.total_seconds() > 2419200:
await interaction.response.send_message(content=error("Please provide a duration that is less than 28 days from the initial moderation."), ephemeral=True)
return False
try:
member = await interaction.guild.fetch_member(new_moderation.target_id)
await member.timeout(
new_moderation.duration,
reason=f"Case #{new_moderation.id:,} edited by {interaction.user.id}",
)
except NotFound:
pass
return True
class Unmute(Type):
key = "unmute"
string = "unmute"
verb = "unmuted"
def void(self) -> None:
return None
@classmethod
async def handler(cls, ctx: commands.Context, target: Member, silent: bool, reason: str = None):
if target.is_timed_out() is False:
await ctx.send(
content=error(f"{target.mention} is not muted!"),
allowed_mentions=AllowedMentions(users=False),
ephemeral=True,
)
return
if reason:
await target.timeout(None, reason=f"{cls.verb.title()} by {ctx.author.id} for: {reason}")
else:
await target.timeout(None, reason=f"{cls.verb.title()} by {ctx.author.id}")
reason = "No reason given."
response_message = await ctx.send(content=f"{target.mention} has been {cls.verb}!\n**Reason** - `{reason}`")
if silent is False:
try:
embed = await message_factory(
bot=ctx.bot,
color=await ctx.embed_color(),
guild=ctx.guild,
moderator=ctx.author,
reason=reason,
moderation_type=cls(),
response=response_message,
)
await target.send(embed=embed, file=get_icon(ctx.bot))
except HTTPException:
pass
moderation = await Moderation.log(
bot=ctx.bot,
guild_id=ctx.guild.id,
moderator_id=ctx.author.id,
moderation_type=cls(),
target_type="user",
target_id=target.id,
role_id=None,
duration=None,
reason=reason,
)
await response_message.edit(content=f"{target.mention} has been {cls.verb}! (Case `#{moderation.id:,}`)\n**Reason** - `{reason}`")
await log(ctx=ctx, moderation_id=moderation.id)
await send_evidenceformat(ctx=ctx, moderation_id=moderation.id)
class Kick(Type):
key = "kick"
string = "kick"
verb = "kicked"
removes_from_guild = True
def void(self) -> None:
return None
@classmethod
async def handler(cls, ctx: commands.Context, target: Member | User, silent: bool, reason: str = None) -> "Kick":
"""Kick a user."""
bot = ctx.bot
response_message = await ctx.send(f"{target.mention} has been {cls.verb}!\n{bold('Reason:')} {inline(reason)}")
if silent is False:
try:
embed = await message_factory(bot=bot, color=await ctx.embed_color(), guild=ctx.guild, reason=reason, moderation_type=cls(), moderator=ctx.author, duration=None, response=response_message)
await target.send(embed=embed, file=get_icon(bot))
except HTTPException:
pass
await target.kick(reason=f"{str.title(cls.verb)} by {ctx.author.id} for: {reason}")
moderation = await Moderation.log(bot=bot, guild_id=ctx.guild.id, moderator_id=ctx.author.id, moderation_type=cls(), target_type="user", target_id=target.id, role_id=None, duration=None, reason=reason)
await response_message.edit(content=f"{target.mention} has been {cls.verb}! (Case {inline(f'#{moderation.id}')})\n{bold('Reason:')} {inline(reason)}")
await log(ctx=ctx, moderation_id=moderation.id)
await send_evidenceformat(ctx=ctx, moderation_id=moderation.id)
return cls()
@classmethod
async def resolve_handler(cls, moderation: Moderation, reason: str) -> Tuple[bool, str]:
if await config.guild(moderation.guild).dm_users() is True:
try:
target = await moderation.bot.fetch_user(moderation.target_id)
embed = await resolve_factory(moderation=moderation, reason=reason)
await target.send(embed=embed, file=get_icon(bot=moderation.bot))
except (Forbidden, HTTPException, NotFound):
pass
return True, ""
class Ban(Type):
key = "ban"
string = "ban"
verb = "banned"
removes_from_guild = True
def void(self) -> None:
return None
@classmethod
async def handler(cls, ctx: commands.Context, target: Member | User, silent: bool, reason: str = None, delete_messages: app_commands.Choice | None = None) -> "Ban":
"""Ban a user."""
bot = ctx.bot
try:
await ctx.guild.fetch_ban(target)
await ctx.send(content=error(f"{target.mention} is already {cls.verb}!"), ephemeral=True)
return None
except NotFound:
pass
if delete_messages is None:
delete_messages_seconds = 0
else:
delete_messages_seconds = delete_messages.value
response_message = await ctx.send(f"{target.mention} has been {cls.verb}!\n{bold('Reason:')} {inline(reason)}")
if silent is False:
try:
embed = await message_factory(bot=bot, color=await ctx.embed_color(), guild=ctx.guild, reason=reason, moderation_type=cls(), moderator=ctx.author, duration=None, response=response_message)
await target.send(embed=embed, file=get_icon(bot))
except HTTPException:
pass
await ctx.guild.ban(target, reason=f"{str.title(cls.verb)} by {ctx.author.id} for: {reason}", delete_message_seconds=delete_messages_seconds)
moderation = await Moderation.log(bot=bot, guild_id=ctx.guild.id, moderator_id=ctx.author.id, moderation_type=cls(), target_type="user", target_id=target.id, role_id=None, duration=None, reason=reason)
await response_message.edit(content=f"{target.mention} has been {cls.verb}! (Case {inline(f'#{moderation.id}')})\n{bold('Reason:')} {inline(reason)}")
await log(ctx=ctx, moderation_id=moderation.id)
await send_evidenceformat(ctx=ctx, moderation_id=moderation.id)
return cls()
@classmethod
async def resolve_handler(cls, moderation: Moderation, reason: str) -> Tuple[bool, str]:
try:
target = await moderation.bot.fetch_user(moderation.target_id)
except (HTTPException, NotFound):
return False, "Fetching the target failed, so I cannot unban them."
try:
await moderation.guild.unban(user=target, reason=reason)
except (NotFound, Forbidden, HTTPException) as e:
if e == NotFound:
return True, ""
return False, "I do not have permission to unban this user."
if await config.guild(moderation.guild).dm_users() is True:
try:
embed = await resolve_factory(moderation=moderation, reason=reason)
await target.send(embed=embed, file=get_icon(bot=moderation.bot))
except (Forbidden, HTTPException):
pass
return True, ""
class Tempban(Ban):
key = "tempban"
string = "tempban"
verb = "tempbanned"
removes_from_guild = True
def void(self) -> None:
return None
@classmethod
async def handler(cls, ctx: commands.Context, target: Member | User, silent: bool, duration: str, reason: str = None, delete_messages: app_commands.Choice | None = None) -> "Ban": # pylint: disable=arguments-renamed
"""Ban a user."""
bot = ctx.bot
try:
await ctx.guild.fetch_ban(target)
await ctx.send(content=error(f"{target.mention} is already {Ban.verb}!"), ephemeral=True)
return None
except NotFound:
pass
if delete_messages is None:
delete_messages_seconds = 0
else:
delete_messages_seconds = delete_messages.value
try:
parsed_time = parse_relativedelta(argument=duration)
if parsed_time is None:
raise commands.BadArgument()
parsed_time = timedelta_from_relativedelta(relativedelta=parsed_time)
except (commands.BadArgument, ValueError):
await ctx.send(content=error(text="Please provide a valid duration!"), ephemeral=True)
return cls()
response_message = await ctx.send(content=f"{target.mention} has been {cls.verb} for {humanize_timedelta(timedelta=parsed_time)}!\n{bold(text='Reason:')} {inline(text=reason)}")
if silent is False:
try:
embed = await message_factory(bot=bot, color=await ctx.embed_color(), guild=ctx.guild, reason=reason, moderation_type=cls(), moderator=ctx.author, duration=parsed_time, response=response_message)
await target.send(embed=embed, file=get_icon(bot))
except HTTPException:
pass
await ctx.guild.ban(target, reason=f"{str.title(cls.verb)} by {ctx.author.id} for: {reason} (Duration: {parsed_time})", delete_message_seconds=delete_messages_seconds)
moderation = await Moderation.log(bot=bot, guild_id=ctx.guild.id, moderator_id=ctx.author.id, moderation_type=cls(), target_type="user", target_id=target.id, role_id=None, duration=parsed_time, reason=reason)
await response_message.edit(content=f"{target.mention} has been {cls.verb} for {humanize_timedelta(timedelta=parsed_time)}! (Case {inline(text=f'#{moderation.id}')})\n{bold(text='Reason:')} {inline(reason)}")
await log(ctx, moderation.id)
await send_evidenceformat(ctx, moderation.id)
return cls()
@classmethod
async def expiry_handler(cls, moderation: Moderation) -> int:
reason = f"Automatic {Unban.string} from case #{moderation.id}"
try:
target = moderation.bot.get_user(moderation.target_id)
if not target:
try:
target = await moderation.bot.fetch_user(moderation.target_id)
except NotFound:
return 0
await moderation.guild.unban(user=target, reason=reason)
if await config.guild(moderation.guild).dm_users() is True:
try:
embed = await message_factory(
bot=moderation.bot,
color=await moderation.bot.get_embed_color(moderation.guild.channels[0]),
guild=moderation.guild,
reason=reason,
moderation_type=type_registry["unban"],
moderator=None,
duration=None,
response=None,
case=False,
)
await target.send(embed=embed, file=get_icon(bot=moderation.bot))
except HTTPException:
pass
logger.trace(
"%s %s (%s) from %s (%s)",
Unban.verb.title(),
target.name,
target.id,
moderation.guild.name,
moderation.guild.id,
)
return 1
except (NotFound, Forbidden, HTTPException) as e:
logger.error(
"Failed to %s %s (%s) from %s (%s)\n%s",
Unban.string,
target.name,
target.id,
moderation.guild.name,
moderation.guild.id,
e,
)
return 0
@classmethod
async def duration_edit_handler(cls, interaction: Interaction, old_moderation: Moderation, new_moderation: Moderation) -> bool: # pylint: disable=unused-argument
return True
class Softban(Type):
key = "softban"
string = "softban"
verb = "softbanned"
removes_from_guild = True
def void(self) -> None:
return None
@classmethod
async def handler(cls, ctx: commands.Context, target: Member | User, silent: bool, reason: str = None, delete_messages: app_commands.Choice | None = None) -> "Softban":
"""Softban a user."""
bot = ctx.bot
try:
await ctx.guild.fetch_ban(target)
await ctx.send(content=error(f"{target.mention} is already {Ban.verb}!"), ephemeral=True)
except NotFound:
pass
if delete_messages is None:
delete_messages_seconds = 0
else:
delete_messages_seconds = delete_messages.value
response_message = await ctx.send(f"{target.mention} has been {cls.verb}!\n{bold('Reason:')} {inline(reason)}")
if silent is False:
try:
embed = await message_factory(bot=bot, color=await ctx.embed_color(), guild=ctx.guild, reason=reason, moderation_type=cls(), moderator=ctx.author, duration=None, response=response_message)
await target.send(embed=embed, file=get_icon(bot))
except HTTPException:
pass
await ctx.guild.ban(target, reason=f"{str.title(cls.verb)} by {ctx.author.id} for: {reason}", delete_message_seconds=delete_messages_seconds)
await ctx.guild.unban(target, reason=f"{str.title(cls.verb)} by {ctx.author.id} for: {reason}")
moderation = await Moderation.log(bot=bot, guild_id=ctx.guild.id, moderator_id=ctx.author.id, moderation_type=cls(), target_type="user", target_id=target.id, role_id=None, duration=None, reason=reason)
await response_message.edit(content=f"{target.mention} has been {cls.verb}! (Case {inline(f'#{moderation.id}')})\n{bold('Reason:')} {inline(reason)}")
await log(ctx, moderation.id)
await send_evidenceformat(ctx, moderation.id)
return cls()
@classmethod
async def resolve_handler(cls, moderation: Moderation, reason: str) -> Tuple[bool, str]:
if await config.guild(moderation.guild).dm_users() is True:
try:
target = await moderation.bot.fetch_user(moderation.target_id)
embed = await resolve_factory(moderation=moderation, reason=reason)
await target.send(embed=embed, file=get_icon(bot=moderation.bot))
except (Forbidden, HTTPException, NotFound):
pass
return True, ""
class Unban(Type):
key = "unban"
string = "unban"
verb = "unbanned"
removes_from_guild = True
def void(self) -> None:
return None
@classmethod
async def handler(cls, ctx: commands.Context, target: Member | User, silent: bool, reason: str = None) -> "Unban":
"""Unban a user."""
bot = ctx.bot
try:
await ctx.guild.fetch_ban(target)
except NotFound:
await ctx.send(content=error(f"{target.mention} is not {Ban.verb}!"), ephemeral=True)
return None
response_message = await ctx.send(f"{target.mention} has been {cls.verb}!\n{bold('Reason:')} {inline(reason)}")
if silent is False:
try:
embed = await message_factory(bot=bot, color=await ctx.embed_color(), guild=ctx.guild, reason=reason, moderation_type=cls(), moderator=ctx.author, duration=None, response=response_message)
await target.send(embed=embed, file=get_icon(bot))
except HTTPException:
pass
await ctx.guild.unban(target, reason=f"{str.title(cls.verb)} by {ctx.author.id} for: {reason}")
moderation = await Moderation.log(bot=bot, guild_id=ctx.guild.id, moderator_id=ctx.author.id, moderation_type=cls(), target_type="user", target_id=target.id, role_id=None, duration=None, reason=reason)
await response_message.edit(content=f"{target.mention} has been {cls.verb}! (Case {inline(f'#{moderation.id}')})\n{bold('Reason:')} {inline(reason)}")
await log(ctx, moderation.id)
await send_evidenceformat(ctx, moderation.id)
return cls()
class Slowmode(Type):
key = "slowmode"
string = "slowmode"
verb = "set the slowmode in"
channel = True
def void(self) -> None:
return None
@classmethod
async def handler(cls, ctx: commands.Context, target: Messageable, silent: bool, duration: str | None, reason: str, interval: int) -> "Slowmode": # pylint: disable=unused-argument
"""Set the slowmode in a channel."""
bot = ctx.bot
timedelta_interval = timedelta(seconds=interval)
if ceil(timedelta_interval.total_seconds()) > 21600:
await ctx.send(content=error(text="The slowmode interval cannot exceed 6 hours!"), ephemeral=True)
return cls()
if isinstance(target, TextChannel):
if reason:
await target.edit(slowmode_delay=ceil(timedelta_interval.total_seconds()), reason=f"Slowmode set by {ctx.author.id} for: {reason}")
else:
await target.edit(slowmode_delay=ceil(timedelta_interval.total_seconds()), reason=f"Slowmode set by {ctx.author.id}")
reason = "No reason given."
assert ctx.guild
moderation = await Moderation.log(bot=bot, guild_id=ctx.guild.id, moderator_id=ctx.author.id, moderation_type=cls(), target_type="channel", target_id=target.id, role_id=None, duration=None, reason=reason, metadata={"interval": interval})
await ctx.send(content=f"{ctx.author.mention} has {cls.verb} {target.mention} to {humanize_timedelta(timedelta=timedelta_interval) or '0 seconds'}!\n{bold(text='Reason:')} {inline(text=reason)}")
await log(ctx=ctx, moderation_id=moderation.id)
return cls()
class Lockdown(Type):
key = "lockdown"
string = "lockdown"
verb = "locked down"
channel = True
def void(self) -> None:
return None

90
aurora/models/partials.py Normal file
View file

@ -0,0 +1,90 @@
from discord import ChannelType, Forbidden, Guild, HTTPException, InvalidData, NotFound, Role, User
from discord.abc import Messageable
from redbot.core.bot import Red
from .base import AuroraBaseModel, AuroraGuildModel
class PartialUser(AuroraBaseModel):
id: int
username: str
discriminator: int
_obj: User | None
@property
def name(self):
return f"{self.username}#{self.discriminator}" if self.discriminator != 0 else self.username
def __str__(self):
return self.name
def __repr__(self):
return f"<{self.__class__.__name__} id={self.id}>"
@classmethod
async def from_id(cls, bot: Red, user_id: int) -> "PartialUser":
user = bot.get_user(user_id)
if not user:
try:
user = await bot.fetch_user(user_id)
return cls(bot=bot, id=user.id, username=user.name, discriminator=user.discriminator, _obj=user)
except NotFound:
return cls(bot=bot, id=user_id, username="Deleted User", discriminator=0, _obj=None)
return cls(bot=bot, id=user.id, username=user.name, discriminator=user.discriminator, _obj=user)
class PartialChannel(AuroraGuildModel):
id: int
name: str
type: ChannelType
_obj: Messageable | None
@property
def mention(self):
if self.name in ["Deleted Channel", "Forbidden Channel"]:
return self.name
return f"<#{self.id}>"
def __str__(self):
return self.mention
def __repr__(self):
return f"<{self.__class__.__name__} id={self.id} guild_id={self.guild_id}>"
@classmethod
async def from_id(cls, bot: Red, channel_id: int, guild: Guild) -> "PartialChannel":
channel = bot.get_channel(channel_id)
if not channel:
try:
channel = await bot.fetch_channel(channel_id)
return cls(bot=bot, guild_id=channel.guild.id, guild=guild, id=channel.id, name=channel.name, type=channel.type, _obj=channel)
except (NotFound, InvalidData, HTTPException, Forbidden) as e:
if e == Forbidden:
return cls(bot=bot, guild_id=0, id=channel_id, name="Forbidden Channel")
return cls(bot=bot, guild_id=0, id=channel_id, name="Deleted Channel", type=ChannelType.text, _obj=None)
return cls(bot=bot, guild_id=channel.guild.id, guild=guild, id=channel.id, name=channel.name, type=channel.type, _obj=channel)
class PartialRole(AuroraGuildModel):
id: int
name: str
_obj: Role | None
@property
def mention(self):
if self.name in ["Deleted Role", "Forbidden Role"]:
return self.name
return f"<@&{self.id}>"
def __str__(self):
return self.mention
def __repr__(self) -> str:
return f"<{self.__class__.__name__} id={self.id} guild_id={self.guild_id}>"
@classmethod
async def from_id(cls, bot: Red, guild: Guild, role_id: int) -> "PartialRole":
role = guild.get_role(role_id)
if not role:
return cls(bot=bot, guild_id=guild.id, id=role_id, name="Deleted Role", _obj=None)
return cls(bot=bot, guild_id=guild.id, id=role.id, name=role.name, _obj=role)

101
aurora/models/type.py Normal file
View file

@ -0,0 +1,101 @@
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Dict, Tuple
from class_registry import ClassRegistry
from class_registry.base import AutoRegister
from discord import Interaction, Member, User
from discord.abc import Messageable
from redbot.core import commands
if TYPE_CHECKING:
from .moderation import Moderation
type_registry: Dict["str", "Type"] = ClassRegistry(attr_name="key", unique=True)
class Type(AutoRegister(registry=type_registry), ABC):
"""This is a base class for moderation types.
Attributes:
key (str): The key to use for this type. This should be unique, as this is how the type is registered internally. Changing this key will break existing cases with this type.
string (str): The string to display for this type.
verb (str): The verb to use for this type.
embed_desc (str): The string to use for embed descriptions.
channel (bool): Whether this type targets channels or users. If this is `true` in a subclass, its overridden handler methods should be typed with `discord.abc.Messageable` instead of `discord.Member | discord.User`.
removes_from_guild (bool): Whether this type's handler removes the target from the guild, or if the moderation is expected to occur whenever the user is not in the guild. This does not actually remove the target from the guild, the handler method is responsible for that.
Properties:
name (str): The string to display for this type. This is the same as the `string` attribute.
"""
key = "type"
string = "type"
verb = "typed"
embed_desc = "been "
channel = False
removes_from_guild = False
@abstractmethod
def void(self) -> Any:
"""This method should be overridden by any child classes. This is a placeholder to allow for automatic class registration."""
raise NotImplementedError
@property
def name(self) -> str:
"""Alias for the `string` attribute."""
return self.string
def __str__(self) -> str:
return self.string
def __repr__(self) -> str:
attrs = [
("key", self.key),
("channel", self.channel),
]
joined = " ".join(f"{key}={value!r}" for key, value in attrs)
return f"<{self.__class__.__name__} {joined}>"
@classmethod
async def handler(cls, ctx: commands.Context, target: Member | User | Messageable, silent: bool, **kwargs) -> "Type": # pylint: disable=unused-argument
"""This method should be overridden by any child classes, but should retain the same starting keyword arguments.
Arguments:
ctx (commands.Context): The context of the command.
target (discord.Member | discord.User | discord.abc.Messageable): The target of the moderation.
silent (bool): Whether details about the moderation should be DM'ed to the target of the moderation.
"""
raise NotImplementedError
@classmethod
async def resolve_handler(cls, moderation: "Moderation", reason: str) -> Tuple[bool, str]: # pylint: disable=unused-argument
"""This method should be overridden by any resolvable child classes, but should retain the same keyword arguments.
If your moderation type should not be resolvable, do not override this.
Arguments:
moderation (aurora.models.Moderation): The moderation to resolve.
reason (str): The reason for resolving the moderation.
"""
raise NotImplementedError
@classmethod
async def expiry_handler(cls, moderation: "Moderation") -> int: # pylint: disable=unused-argument
"""This method should be overridden by any expirable child classes, but should retain the same keyword arguments and return an integer.
If your moderation type should not expire, do not override this, but also do not set an `end_timestamp` when you log your moderation.
Arguments:
moderation (aurora.models.Moderation): The moderation that is expiring.
"""
raise NotImplementedError
@classmethod
async def duration_edit_handler(cls, interaction: Interaction, old_moderation: "Moderation", new_moderation: "Moderation") -> bool: # pylint: disable=unused-argument
"""This method should be overridden by any child classes with editable durations, but should retain the same keyword arguments and should return True if the duration was successfully modified, or False if it was not.
If your moderation type's duration should not be editable, do not override this.
Arguments:
interaction (discord.Interaction): The interaction that triggered the duration edit.
old_moderation (aurora.models.Moderation): The old moderation, from before the `/edit` command was invoked.
new_moderation (aurora.models.Moderation): The current state of the moderation.
"""
raise NotImplementedError

View file

@ -27,3 +27,13 @@ def register_config(config_obj: Config):
history_inline_pagesize=None, history_inline_pagesize=None,
auto_evidenceformat=None, auto_evidenceformat=None,
) )
moderation_type = {
"show_in_history": True,
"show_moderator": None,
"use_discord_permissions": None,
"dm_users": None,
}
config_obj.init_custom("types", 2)
config_obj.register_custom("types", **moderation_type)

View file

@ -8,18 +8,23 @@ from discord import Guild
from redbot.core import data_manager from redbot.core import data_manager
from .logger import logger from .logger import logger
from .utils import convert_timedelta_to_str, generate_dict, get_next_case_number from .utils import (convert_timedelta_to_str, generate_dict,
get_next_case_number)
def connect() -> sqlite3.Connection: def connect() -> sqlite3.Connection:
"""Connects to the SQLite database, and returns a connection object.""" """Connects to the SQLite database, and returns a connection object."""
try: try:
return sqlite3.connect(database=data_manager.cog_data_path(raw_name="Aurora") / "aurora.db") connection = sqlite3.connect(
database=data_manager.cog_data_path(raw_name="Aurora") / "aurora.db"
)
return connection
except sqlite3.OperationalError as e: except sqlite3.OperationalError as e:
logger.error("Unable to access the SQLite database!\nError:\n%s", e.msg) logger.error("Unable to access the SQLite database!\nError:\n%s", e.msg)
msg = f"Unable to access the SQLite Database!\n{e.msg}" raise ConnectionRefusedError(
raise ConnectionRefusedError(msg) from e f"Unable to access the SQLite Database!\n{e.msg}"
) from e
async def create_guild_table(guild: Guild): async def create_guild_table(guild: Guild):

View file

@ -2,83 +2,69 @@
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import Union from typing import Union
from discord import Color, Embed, Guild, Interaction, InteractionMessage, Member, Role, User from discord import Color, Embed, Guild, Interaction, Member, Message, Role, User
from redbot.core import commands from redbot.core import commands
from redbot.core.utils.chat_formatting import bold, box, error, humanize_timedelta, warning from redbot.core.bot import Red
from redbot.core.utils.chat_formatting import bold, box, error, humanize_timedelta, inline, warning
from aurora.utilities.config import config from ..models.moderation import Moderation
from aurora.utilities.utils import fetch_channel_dict, fetch_user_dict, get_bool_emoji, get_next_case_number, get_pagesize_str from ..models.partials import PartialUser
from ..models.type import Type
from .config import config
from .utils import get_bool_emoji, get_pagesize_str
async def message_factory( async def message_factory(
bot: Red,
color: Color, color: Color,
guild: Guild, guild: Guild,
reason: str, reason: str,
moderation_type: str, moderation_type: Type,
moderator: Union[Member, User] = None, moderator: Union[Member, User] | None = None,
duration: timedelta = None, duration: timedelta | None = None,
response: InteractionMessage = None, response: Message | None = None,
role: Role = None, case: bool = True,
) -> Embed: ) -> Embed:
"""This function creates a message from set parameters, meant for contacting the moderated user. """This function creates a message from set parameters, meant for contacting the moderated user.
Args: Args:
bot (Red): The bot instance.
color (Color): The color of the embed. color (Color): The color of the embed.
guild (Guild): The guild the moderation occurred in. guild (Guild): The guild the moderation occurred in.
reason (str): The reason for the moderation. reason (str): The reason for the moderation.
moderation_type (str): The type of moderation. moderation_type (Type): The type of moderation.
moderator (Union[Member, User], optional): The moderator who performed the moderation. Defaults to None. moderator (Union[Member, User], optional): The moderator who performed the moderation. Defaults to None.
duration (timedelta, optional): The duration of the moderation. Defaults to None. duration (timedelta, optional): The duration of the moderation. Defaults to None.
response (InteractionMessage, optional): The response message. Defaults to None. response (Message, optional): The response message. Defaults to None.
role (Role, optional): The role that was added or removed. Defaults to None. case (bool, optional): Whether the message is for a moderation case. Defaults to True.
Returns: Returns:
embed: The message embed. embed: The message embed.
""" """
if response is not None and moderation_type not in [ if response is not None and not moderation_type.removes_from_guild:
"kicked",
"banned",
"tempbanned",
"unbanned",
]:
guild_name = f"[{guild.name}]({response.jump_url})" guild_name = f"[{guild.name}]({response.jump_url})"
else: else:
guild_name = guild.name guild_name = guild.name
title = moderation_type if duration:
if moderation_type in ["tempbanned", "muted"] and duration:
embed_duration = f" for {humanize_timedelta(timedelta=duration)}" embed_duration = f" for {humanize_timedelta(timedelta=duration)}"
else: else:
embed_duration = "" embed_duration = ""
if moderation_type == "note":
embed_desc = "received a"
elif moderation_type == "addrole":
embed_desc = f"received the {role.name} role"
title = "Role Added"
moderation_type = ""
elif moderation_type == "removerole":
embed_desc = f"lost the {role.name} role"
title = "Role Removed"
moderation_type = ""
else:
embed_desc = "been"
embed = Embed( embed = Embed(
title=str.title(title), title=str.title(moderation_type.verb),
description=f"You have {embed_desc} {moderation_type}{embed_duration} in {guild_name}.", description=f"You have {moderation_type.embed_desc}{moderation_type.verb}{embed_duration} in {guild_name}.",
color=color, color=color,
timestamp=datetime.now(), timestamp=datetime.now(),
) )
if await config.guild(guild).show_moderator() and moderator is not None: show_moderator = await config.custom("types", guild.id, moderation_type.key).show_moderator()
embed.add_field( if show_moderator is None:
name="Moderator", show_moderator = await config.guild(guild).show_moderator()
value=f"`{moderator.name} ({moderator.id})`",
inline=False, if show_moderator and moderator is not None:
) embed.add_field(name="Moderator", value=f"`{moderator.name} ({moderator.id})`", inline=False)
embed.add_field(name="Reason", value=f"`{reason}`", inline=False) embed.add_field(name="Reason", value=f"`{reason}`", inline=False)
@ -87,216 +73,190 @@ async def message_factory(
else: else:
embed.set_author(name=guild.name) embed.set_author(name=guild.name)
if case:
embed.set_footer(
text=f"Case #{await Moderation.get_next_case_number(bot=bot, guild_id=guild.id):,}",
icon_url="attachment://arrow.png",
)
return embed
async def resolve_factory(moderation: Moderation, reason: str) -> Embed:
"""This function creates a resolved embed from set parameters, meant for contacting the moderated user.
Args:
moderation (aurora.models.Moderation): The moderation object.
reason (str): The reason for resolving the moderation.
Returns: `discord.Embed`
"""
embed = Embed(
title=str.title(moderation.type.name) + " Resolved",
description=f"Your {moderation.type.name} in {moderation.guild.name} has been resolved.",
color=await moderation.bot.get_embed_color(moderation.guild.channels[0]),
timestamp=datetime.now(),
)
embed.add_field(name="Reason", value=f"`{reason}`", inline=False)
if moderation.guild.icon.url is not None:
embed.set_author(name=moderation.guild.name, icon_url=moderation.guild.icon.url)
else:
embed.set_author(name=moderation.guild.name)
embed.set_footer( embed.set_footer(
text=f"Case #{await get_next_case_number(guild.id):,}", text=f"Case #{moderation.id:,}",
icon_url="attachment://arrow.png", icon_url="attachment://arrow.png",
) )
return embed return embed
async def log_factory( async def log_factory(ctx: commands.Context, moderation: Moderation, resolved: bool = False) -> Embed:
interaction: Interaction,
case_dict: dict,
resolved: bool = False,
) -> Embed:
"""This function creates a log embed from set parameters, meant for moderation logging. """This function creates a log embed from set parameters, meant for moderation logging.
Args: Args:
interaction (Interaction): The interaction object. ctx (commands.Context): The ctx object.
case_dict (dict): The case dictionary. moderation (aurora.models.Moderation): The moderation object.
resolved (bool, optional): Whether the case is resolved or not. Defaults to False. resolved (bool, optional): Whether the case is resolved or not. Defaults to False.
""" """
target_name = "" target = await moderation.get_target()
moderator = await moderation.get_moderator()
if resolved: if resolved:
if case_dict["target_type"] == "USER":
target_user = await fetch_user_dict(interaction.client, case_dict["target_id"])
target_name = f"`{target_user['name']}`" if target_user["discriminator"] == "0" else f"`{target_user['name']}#{target_user['discriminator']}`"
elif case_dict["target_type"] == "CHANNEL":
target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"])
if target_user["mention"]:
target_name = f"{target_user['mention']}"
else:
target_name = f"`{target_user['name']}`"
moderator_user = await fetch_user_dict(interaction.client, case_dict["moderator_id"])
moderator_name = f"`{moderator_user['name']}`" if moderator_user["discriminator"] == "0" else f"`{moderator_user['name']}#{moderator_user['discriminator']}`"
embed = Embed( embed = Embed(
title=f"📕 Case #{case_dict['moderation_id']:,} Resolved", title=f"📕 Case #{moderation.id:,} Resolved",
color=await interaction.client.get_embed_color(interaction.channel), color=await ctx.bot.get_embed_color(ctx.channel),
) )
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>" resolved_by = await moderation.get_resolved_by()
embed.description = f"**Type:** {str.title(moderation.type.string)}\n**Target:** {target.name} ({target.id})\n**Moderator:** {moderator.name} ({moderator.id})\n**Timestamp:** <t:{moderation.unix_timestamp}> | <t:{moderation.unix_timestamp}:R>"
if case_dict["duration"] != "NULL": if moderation.duration is not None:
td = timedelta( duration_embed = f"{humanize_timedelta(timedelta=moderation.duration)} | <t:{moderation.end_timestamp}:R>" if not moderation.expired else str(humanize_timedelta(timedelta=moderation.duration))
**{ embed.description = embed.description + f"\n**Duration:** {duration_embed}\n**Expired:** {moderation.expired}"
unit: int(val)
for unit, val in zip(
["hours", "minutes", "seconds"],
case_dict["duration"].split(":"),
)
},
)
duration_embed = f"{humanize_timedelta(timedelta=td)} | <t:{case_dict['end_timestamp']}:R>" if case_dict["expired"] == "0" else str(humanize_timedelta(timedelta=td))
embed.description = embed.description + f"\n**Duration:** {duration_embed}\n**Expired:** {bool(case_dict['expired'])}"
embed.add_field(name="Reason", value=box(case_dict["reason"]), inline=False) if moderation.metadata.items():
for key, value in moderation.metadata.items():
embed.description += f"\n**{key.title()}:** {value}"
embed.add_field(name="Reason", value=box(moderation.reason), inline=False)
resolved_user = await fetch_user_dict(interaction.client, 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( embed.add_field(
name="Resolve Reason", name="Resolve Reason",
value=f"Resolved by `{resolved_name}` ({resolved_user['id']}) for:\n" + box(case_dict["resolve_reason"]), value=f"Resolved by `{resolved_by.name}` ({resolved_by.id}) for:\n" + box(moderation.resolve_reason),
inline=False, inline=False,
) )
else: else:
if case_dict["target_type"] == "USER":
target_user = await fetch_user_dict(interaction.client, case_dict["target_id"])
target_name = f"`{target_user['name']}`" if target_user["discriminator"] == "0" else f"`{target_user['name']}#{target_user['discriminator']}`"
elif case_dict["target_type"] == "CHANNEL":
target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"])
if target_user["mention"]:
target_name = target_user["mention"]
else:
target_name = f"`{target_user['name']}`"
moderator_user = await fetch_user_dict(interaction.client, case_dict["moderator_id"])
moderator_name = f"`{moderator_user['name']}`" if moderator_user["discriminator"] == "0" else f"`{moderator_user['name']}#{moderator_user['discriminator']}`"
embed = Embed( embed = Embed(
title=f"📕 Case #{case_dict['moderation_id']:,}", title=f"📕 Case #{moderation.id:,}",
color=await interaction.client.get_embed_color(interaction.channel), color=await ctx.bot.get_embed_color(ctx.channel),
) )
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>" embed.description = f"**Type:** {str.title(moderation.type.string)}\n**Target:** {target.name} ({target.id})\n**Moderator:** {moderator.name} ({moderator.id})\n**Timestamp:** <t:{moderation.unix_timestamp}> | <t:{moderation.unix_timestamp}:R>"
if case_dict["duration"] != "NULL": if moderation.duration:
td = timedelta( embed.description = embed.description + f"\n**Duration:** {humanize_timedelta(timedelta=moderation.duration)} | <t:{moderation.unix_timestamp}:R>"
**{
unit: int(val)
for unit, val in zip(
["hours", "minutes", "seconds"],
case_dict["duration"].split(":"),
)
},
)
embed.description = embed.description + f"\n**Duration:** {humanize_timedelta(timedelta=td)} | <t:{case_dict['end_timestamp']}:R>"
embed.add_field(name="Reason", value=box(case_dict["reason"]), inline=False) if moderation.metadata.items():
for key, value in moderation.metadata.items():
embed.description += f"\n**{key.title()}:** {value}"
embed.add_field(name="Reason", value=box(moderation.reason), inline=False)
return embed return embed
async def case_factory(interaction: Interaction, case_dict: dict) -> Embed: async def case_factory(interaction: Interaction, moderation: Moderation) -> Embed:
"""This function creates a case embed from set parameters. """This function creates a case embed from set parameters.
Args: Args:
interaction (Interaction): The interaction object. interaction (discord.Interaction): The interaction object.
case_dict (dict): The case dictionary. moderation (aurora.models.Moderation): The moderation object.
""" """
target_name = "" target = await moderation.get_target()
if case_dict["target_type"] == "USER": moderator = await moderation.get_moderator()
target_user = await fetch_user_dict(interaction.client, case_dict["target_id"])
target_name = f"`{target_user['name']}`" if target_user["discriminator"] == "0" else f"`{target_user['name']}#{target_user['discriminator']}`"
elif case_dict["target_type"] == "CHANNEL":
target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"])
if target_user["mention"]:
target_name = f"{target_user['mention']}"
else:
target_name = f"`{target_user['name']}`"
moderator_user = await fetch_user_dict(interaction.client, case_dict["moderator_id"])
moderator_name = f"`{moderator_user['name']}`" if moderator_user["discriminator"] == "0" else f"`{moderator_user['name']}#{moderator_user['discriminator']}`"
embed = Embed( embed = Embed(
title=f"📕 Case #{case_dict['moderation_id']:,}", title=f"📕 Case #{moderation.id:,}",
color=await interaction.client.get_embed_color(interaction.channel), color=await interaction.client.get_embed_color(interaction.channel),
) )
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>" embed.description = f"**Type:** {str.title(moderation.type.string)}\n**Target:** `{target.name}` ({target.id})\n**Moderator:** `{moderator.name}` ({moderator.id})\n**Resolved:** {moderation.resolved}\n**Timestamp:** <t:{moderation.unix_timestamp}> | <t:{moderation.unix_timestamp}:R>"
if case_dict["duration"] != "NULL": if moderation.duration:
td = timedelta( duration_embed = f"{humanize_timedelta(timedelta=moderation.duration)} | <t:{moderation.unix_timestamp}:R>" if moderation.expired is False else str(humanize_timedelta(timedelta=moderation.duration))
**{ embed.description += f"\n**Duration:** {duration_embed}\n**Expired:** {moderation.expired}"
unit: int(val)
for unit, val in zip(
["hours", "minutes", "seconds"],
case_dict["duration"].split(":"),
)
},
)
duration_embed = f"{humanize_timedelta(timedelta=td)} | <t:{case_dict['end_timestamp']}:R>" if bool(case_dict["expired"]) is False else str(humanize_timedelta(timedelta=td))
embed.description += f"\n**Duration:** {duration_embed}\n**Expired:** {bool(case_dict['expired'])}"
embed.description += f"\n**Changes:** {len(case_dict['changes']) - 1}" if case_dict["changes"] else "\n**Changes:** 0" embed.description += f"\n**Changes:** {len(moderation.changes) - 1}" if moderation.changes else "\n**Changes:** 0"
if case_dict["role_id"]: if moderation.role_id:
embed.description += f"\n**Role:** <@&{case_dict['role_id']}>" role = await moderation.get_role()
embed.description += f"\n**Role:** {role.name}"
if case_dict["metadata"]: if moderation.metadata:
if case_dict["metadata"]["imported_from"]: if moderation.metadata.get("imported_from"):
embed.description += f"\n**Imported From:** {case_dict['metadata']['imported_from']}" embed.description += f"\n**Imported From:** {moderation.metadata['imported_from']}"
moderation.metadata.pop("imported_from")
if moderation.metadata.get("imported_timestamp"):
embed.description += f"\n**Imported Timestamp:** <t:{moderation.metadata['imported_timestamp']}> | <t:{moderation.metadata['imported_timestamp']}:R>"
moderation.metadata.pop("imported_timestamp")
if moderation.metadata.items():
for key, value in moderation.metadata.items():
embed.description += f"\n**{key.title()}:** {value}"
embed.add_field(name="Reason", value=box(case_dict["reason"]), inline=False) embed.add_field(name="Reason", value=box(moderation.reason), inline=False)
if case_dict["resolved"] == 1: if moderation.resolved:
resolved_user = await fetch_user_dict(interaction.client, case_dict["resolved_by"]) resolved_user = await moderation.get_resolved_by()
resolved_name = f"`{resolved_user['name']}`" if resolved_user["discriminator"] == "0" else f"`{resolved_user['name']}#{resolved_user['discriminator']}`" if not resolved_user:
resolved_user = PartialUser(bot=interaction.client, id=0, username="Deleted User", discriminator="0")
embed.add_field( embed.add_field(
name="Resolve Reason", name="Resolve Reason",
value=f"Resolved by {resolved_name} ({resolved_user['id']}) for:\n{box(case_dict['resolve_reason'])}", value=f"Resolved by `{resolved_user.name or 'Deleted User'}` ({resolved_user.id or '0'}) for:\n{box(moderation.resolve_reason)}",
inline=False, inline=False,
) )
return embed return embed
async def changes_factory(interaction: Interaction, case_dict: dict) -> Embed: async def changes_factory(interaction: Interaction, moderation: Moderation) -> Embed:
"""This function creates a changes embed from set parameters. """This function creates a changes embed from set parameters.
Args: Args:
interaction (Interaction): The interaction object. interaction (discord.Interaction): The interaction object.
case_dict (dict): The case dictionary. moderation (aurora.models.Moderation): The moderation object.
""" """
embed = Embed( embed = Embed(
title=f"📕 Case #{case_dict['moderation_id']:,} Changes", title=f"📕 Case #{moderation.id:,} Changes",
color=await interaction.client.get_embed_color(interaction.channel), color=await interaction.client.get_embed_color(interaction.channel),
) )
memory_dict = {} memory_dict = {}
if case_dict["changes"]: if moderation.changes:
for change in case_dict["changes"]: for change in moderation.changes:
if change["user_id"] not in memory_dict: if change.user_id not in memory_dict:
memory_dict[str(change["user_id"])] = await fetch_user_dict( memory_dict[str(change.user_id)] = await change.get_user()
interaction.client,
change["user_id"],
)
user = memory_dict[str(change["user_id"])] user: PartialUser = memory_dict[str(change.user_id)]
name = user["name"] if user["discriminator"] == "0" else f"{user['name']}#{user['discriminator']}"
timestamp = f"<t:{change['timestamp']}> | <t:{change['timestamp']}:R>" timestamp = f"<t:{change.unix_timestamp}> | <t:{change.unix_timestamp}:R>"
end_timestamp = f"<t:{change.unix_end_timestamp}> | <t:{change.unix_end_timestamp}:R>" if change.end_timestamp else None
if change["type"] == "ORIGINAL": change_str = [
embed.add_field( f"{bold('User:')} {inline(user.name)} ({user.id})",
name="Original", f"{bold('Reason:')} {change.reason}" if change.reason else "",
value=f"**User:** `{name}` ({user['id']})\n**Reason:** {change['reason']}\n**Timestamp:** {timestamp}", f"{bold('Duration:')} {humanize_timedelta(timedelta=change.duration)}" if change.duration else "",
inline=False, f"{bold('End Timestamp:')} {end_timestamp}" if end_timestamp else "",
) f"{bold('Timestamp')} {timestamp}",
]
copy = change_str.copy()
for string in change_str:
if string == "":
copy.remove(string)
elif change["type"] == "EDIT": embed.add_field(
embed.add_field( name=change.type.title(),
name="Edit", value="\n".join(copy),
value=f"**User:** `{name}` ({user['id']})\n**Reason:** {change['reason']}\n**Timestamp:** {timestamp}", inline=False,
inline=False, )
)
elif change["type"] == "RESOLVE":
embed.add_field(
name="Resolve",
value=f"**User:** `{name}` ({user['id']})\n**Reason:** {change['reason']}\n**Timestamp:** {timestamp}",
inline=False,
)
else: else:
embed.description = "*No changes have been made to this case.* 🙁" embed.description = "*No changes have been made to this case.* 🙁"
@ -304,37 +264,29 @@ async def changes_factory(interaction: Interaction, case_dict: dict) -> Embed:
return embed return embed
async def evidenceformat_factory(interaction: Interaction, case_dict: dict) -> str: async def evidenceformat_factory(moderation: Moderation) -> str:
"""This function creates a codeblock in evidence format from set parameters. """This function creates a codeblock in evidence format from set parameters.
Args: Args:
interaction (Interaction): The interaction object. interaction (discord.Interaction): The interaction object.
case_dict (dict): The case dictionary. moderation (aurora.models.Moderation): The moderation object.
""" """
target_name = "" target = await moderation.get_target()
if case_dict["target_type"] == "USER": moderator = await moderation.get_moderator()
target_user = await fetch_user_dict(interaction.client, case_dict["target_id"])
target_name = target_user["name"] if target_user["discriminator"] == "0" else f"{target_user['name']}#{target_user['discriminator']}"
elif case_dict["target_type"] == "CHANNEL": content = f"Case: {moderation.id:,} ({str.title(moderation.type.string)})\nTarget: {target.name} ({target.id})\nModerator: {moderator.name} ({moderator.id})"
target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"])
target_name = target_user["name"]
moderator_user = await fetch_user_dict(interaction.client, case_dict["moderator_id"]) if moderation.duration is not None:
moderator_name = moderator_user["name"] if moderator_user["discriminator"] == "0" else f"{moderator_user['name']}#{moderator_user['discriminator']}" content += f"\nDuration: {humanize_timedelta(timedelta=moderation.duration)}"
content = f"Case: {case_dict['moderation_id']:,} ({str.title(case_dict['moderation_type'])})\nTarget: {target_name} ({target_user['id']})\nModerator: {moderator_name} ({moderator_user['id']})" if moderation.role_id:
role = await moderation.get_role()
content += "\nRole: " + (role.name if role is not None else moderation.role_id)
if case_dict["role_id"] != "0": content += f"\nReason: {moderation.reason}"
role = interaction.guild.get_role(int(case_dict["role_id"]))
content += "\nRole: " + (role.name if role is not None else case_dict["role_id"])
if case_dict["duration"] != "NULL": for key, value in moderation.metadata.items():
hours, minutes, seconds = map(int, case_dict["duration"].split(":")) content += f"\n{key.title()}: {value}"
td = timedelta(hours=hours, minutes=minutes, seconds=seconds)
content += f"\nDuration: {humanize_timedelta(timedelta=td)}"
content += f"\nReason: {case_dict['reason']}"
return box(content, "prolog") return box(content, "prolog")
@ -388,9 +340,7 @@ async def guild_embed(ctx: commands.Context) -> Embed:
guild_settings = { guild_settings = {
"show_moderator": await config.guild(ctx.guild).show_moderator(), "show_moderator": await config.guild(ctx.guild).show_moderator(),
"use_discord_permissions": await config.guild( "use_discord_permissions": await config.guild(ctx.guild).use_discord_permissions(),
ctx.guild,
).use_discord_permissions(),
"ignore_modlog": await config.guild(ctx.guild).ignore_modlog(), "ignore_modlog": await config.guild(ctx.guild).ignore_modlog(),
"ignore_other_bots": await config.guild(ctx.guild).ignore_other_bots(), "ignore_other_bots": await config.guild(ctx.guild).ignore_other_bots(),
"dm_users": await config.guild(ctx.guild).dm_users(), "dm_users": await config.guild(ctx.guild).dm_users(),
@ -398,9 +348,7 @@ async def guild_embed(ctx: commands.Context) -> Embed:
"history_ephemeral": await config.guild(ctx.guild).history_ephemeral(), "history_ephemeral": await config.guild(ctx.guild).history_ephemeral(),
"history_inline": await config.guild(ctx.guild).history_inline(), "history_inline": await config.guild(ctx.guild).history_inline(),
"history_pagesize": await config.guild(ctx.guild).history_pagesize(), "history_pagesize": await config.guild(ctx.guild).history_pagesize(),
"history_inline_pagesize": await config.guild( "history_inline_pagesize": await config.guild(ctx.guild).history_inline_pagesize(),
ctx.guild,
).history_inline_pagesize(),
"auto_evidenceformat": await config.guild(ctx.guild).auto_evidenceformat(), "auto_evidenceformat": await config.guild(ctx.guild).auto_evidenceformat(),
"respect_hierarchy": await config.guild(ctx.guild).respect_hierarchy(), "respect_hierarchy": await config.guild(ctx.guild).respect_hierarchy(),
} }
@ -444,23 +392,11 @@ async def addrole_embed(ctx: commands.Context) -> Embed:
roles = [] roles = []
async with config.guild(ctx.guild).addrole_whitelist() as whitelist: async with config.guild(ctx.guild).addrole_whitelist() as whitelist:
for role in whitelist: for role in whitelist:
evalulated_role = ctx.guild.get_role(role) or error(f"`{role}` (Not Found)") evaluated_role = ctx.guild.get_role(role) or error(f"`{role}` (Not Found)")
if isinstance(evalulated_role, Role): if isinstance(evaluated_role, Role):
roles.append( roles.append({"id": evaluated_role.id, "mention": evaluated_role.mention, "position": evaluated_role.position})
{
"id": evalulated_role.id,
"mention": evalulated_role.mention,
"position": evalulated_role.position,
},
)
else: else:
roles.append( roles.append({"id": role, "mention": error(f"`{role}` (Not Found)"), "position": 0})
{
"id": role,
"mention": error(f"`{role}` (Not Found)"),
"position": 0,
},
)
if roles: if roles:
roles = sorted(roles, key=lambda x: x["position"], reverse=True) roles = sorted(roles, key=lambda x: x["position"], reverse=True)
@ -499,23 +435,11 @@ async def immune_embed(ctx: commands.Context) -> Embed:
roles = [] roles = []
async with config.guild(ctx.guild).immune_roles() as immune_roles: async with config.guild(ctx.guild).immune_roles() as immune_roles:
for role in immune_roles: for role in immune_roles:
evalulated_role = ctx.guild.get_role(role) or error(f"`{role}` (Not Found)") evaluated_role = ctx.guild.get_role(role) or error(f"`{role}` (Not Found)")
if isinstance(evalulated_role, Role): if isinstance(evaluated_role, Role):
roles.append( roles.append({"id": evaluated_role.id, "mention": evaluated_role.mention, "position": evaluated_role.position})
{
"id": evalulated_role.id,
"mention": evalulated_role.mention,
"position": evalulated_role.position,
},
)
else: else:
roles.append( roles.append({"id": role, "mention": error(f"`{role}` (Not Found)"), "position": 0})
{
"id": role,
"mention": error(f"`{role}` (Not Found)"),
"position": 0,
},
)
if roles: if roles:
roles = sorted(roles, key=lambda x: x["position"], reverse=True) roles = sorted(roles, key=lambda x: x["position"], reverse=True)
@ -546,3 +470,34 @@ async def immune_embed(ctx: commands.Context) -> Embed:
e.description += "\n\n" + immune_str e.description += "\n\n" + immune_str
return e return e
async def type_embed(ctx: commands.Context, moderation_type=Type) -> Embed:
"""Generates a configuration menu field value for a guild's settings."""
type_settings = {
"show_in_history": await config.custom("types", ctx.guild.id, moderation_type.key).show_in_history(),
"show_moderator": await config.custom("types", ctx.guild.id, moderation_type.key).show_moderator(),
"use_discord_permissions": await config.custom("types", ctx.guild.id, moderation_type.key).use_discord_permissions(),
"dm_users": await config.custom("types", ctx.guild.id, moderation_type.key).dm_users(),
}
guild_str = [
"- " + bold("Show in History: ") + get_bool_emoji(type_settings["show_in_history"]),
"- " + bold("Show Moderator: ") + get_bool_emoji(type_settings["show_moderator"]),
"- " + bold("Use Discord Permissions: ") + get_bool_emoji(type_settings["use_discord_permissions"]),
"- " + bold("DM Users: ") + get_bool_emoji(type_settings["dm_users"]),
]
guild_str = "\n".join(guild_str)
e = await _config(ctx)
e.title += f": {moderation_type.string.title()} Configuration"
e.description = (
f"""
Use the buttons below to manage Aurora's configuration for the {bold(moderation_type.string)} moderation type.
If an option has a question mark (\N{BLACK QUESTION MARK ORNAMENT}\N{VARIATION SELECTOR-16}) next to it, Aurora will default to the guild level setting instead.
See `{ctx.prefix}aurora set guild` for more information.\n
"""
+ guild_str
)
return e

108
aurora/utilities/json.py Normal file
View file

@ -0,0 +1,108 @@
import json
from datetime import datetime, timedelta
from typing import Any
from redbot.core.bot import Red
from ..models.base import AuroraBaseModel
from ..models.type import Type
class JSONEncoder(json.JSONEncoder):
def default(self, o) -> Any:
match o:
case datetime():
return int(o.timestamp())
case timedelta():
from ..utilities.utils import timedelta_to_string
return timedelta_to_string(o)
case AuroraBaseModel():
return o.dump()
case Type():
return o.key
case Red():
return None
case _:
return super().default(o)
# This is a wrapper around the json module's dumps function that uses our custom JSONEncoder class
def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, default=None, sort_keys=False, **kw) -> str:
"""Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is true then ``dict`` keys that are not basic types
(``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped
instead of raising a ``TypeError``.
If ``ensure_ascii`` is false, then the return value can contain non-ASCII
characters if they appear in strings contained in ``obj``. Otherwise, all
such characters are escaped in JSON strings.
If ``check_circular`` is false, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``RecursionError`` (or worse).
If ``allow_nan`` is false, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. ``None`` is the most compact
representation.
If specified, ``separators`` should be an ``(item_separator, key_separator)``
tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and
``(',', ': ')`` otherwise. To get the most compact JSON representation,
you should specify ``(',', ':')`` to eliminate whitespace.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
If *sort_keys* is true (default: ``False``), then the output of
dictionaries will be sorted by key.
"""
return json.dumps(obj, cls=JSONEncoder, skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, default=default, sort_keys=sort_keys, **kw)
# This is a wrapper around the json module's dump function that uses our custom JSONEncoder class
def dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, default=None, sort_keys=False, **kw) -> str:
"""Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
If ``skipkeys`` is true then ``dict`` keys that are not basic types
(``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped
instead of raising a ``TypeError``.
If ``ensure_ascii`` is false, then the strings written to ``fp`` can
contain non-ASCII characters if they appear in strings contained in
``obj``. Otherwise, all such characters are escaped in JSON strings.
If ``check_circular`` is false, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``RecursionError`` (or worse).
If ``allow_nan`` is false, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
in strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. ``None`` is the most compact
representation.
If specified, ``separators`` should be an ``(item_separator, key_separator)``
tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and
``(',', ': ')`` otherwise. To get the most compact JSON representation,
you should specify ``(',', ':')`` to eliminate whitespace.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
If *sort_keys* is true (default: ``False``), then the output of
dictionaries will be sorted by key.
"""
return json.dump(obj, fp, cls=JSONEncoder, skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, default=default, sort_keys=sort_keys, **kw)

View file

@ -1,23 +1,25 @@
# pylint: disable=cyclic-import # pylint: disable=cyclic-import
import json from datetime import datetime, timedelta
from datetime import datetime from typing import Optional, Tuple, Union
from datetime import timedelta as td
from typing import Optional, Union
import aiosqlite
from dateutil.relativedelta import relativedelta as rd from dateutil.relativedelta import relativedelta as rd
from discord import File, Guild, Interaction, Member, SelectOption, User from discord import File, Guild, Interaction, Member, SelectOption, TextChannel, User
from discord.errors import Forbidden, NotFound from discord.errors import Forbidden
from redbot.core import commands, data_manager from redbot.core import commands, data_manager
from redbot.core.utils.chat_formatting import error from redbot.core.utils.chat_formatting import error
from .config import config from ..models.type import Type
from ..utilities.config import config
from ..utilities.json import dumps
from ..utilities.logger import logger
def check_permissions( def check_permissions(
user: User, user: User,
permissions: list, permissions: Tuple[str],
ctx: Union[commands.Context, Interaction] = None, ctx: commands.Context | Interaction | None = None,
guild: Guild = None, guild: Guild | None = None,
) -> Union[bool, str]: ) -> Union[bool, str]:
"""Checks if a user has a specific permission (or a list of permissions) in a channel.""" """Checks if a user has a specific permission (or a list of permissions) in a channel."""
if ctx: if ctx:
@ -38,41 +40,56 @@ def check_permissions(
return False return False
async def check_moddable(target: Union[User, Member], interaction: Interaction, permissions: list) -> bool: async def check_moddable(
target: Union[User, Member, TextChannel],
ctx: commands.Context,
permissions: Tuple[str],
moderation_type: Type,
) -> bool:
"""Checks if a moderator can moderate a target.""" """Checks if a moderator can moderate a target."""
if check_permissions(interaction.client.user, permissions, guild=interaction.guild): is_channel = isinstance(target, TextChannel)
await interaction.response.send_message(
use_discord_permissions = await config.custom("types", ctx.guild.id, moderation_type.key).use_discord_permissions()
if use_discord_permissions is None:
use_discord_permissions = await config.guild(ctx.guild).use_discord_permissions()
if check_permissions(ctx.bot.user, permissions, guild=ctx.guild):
await ctx.send(
error(f"I do not have the `{permissions}` permission, required for this action."), error(f"I do not have the `{permissions}` permission, required for this action."),
ephemeral=True, ephemeral=True,
) )
return False return False
if await config.guild(interaction.guild).use_discord_permissions() is True: if use_discord_permissions is True:
if check_permissions(interaction.user, permissions, guild=interaction.guild): if check_permissions(ctx.author, permissions, guild=ctx.guild):
await interaction.response.send_message( await ctx.send(
error(f"You do not have the `{permissions}` permission, required for this action."), error(f"You do not have the `{permissions}` permission, required for this action."),
ephemeral=True, ephemeral=True,
) )
return False return False
if interaction.user.id == target.id: if ctx.author.id == target.id:
await interaction.response.send_message(content="You cannot moderate yourself!", ephemeral=True) await ctx.send(content="You cannot moderate yourself!", ephemeral=True)
return False return False
if target.bot: if not is_channel and target.bot:
await interaction.response.send_message(content="You cannot moderate bots!", ephemeral=True) await ctx.send(content="You cannot moderate bots!", ephemeral=True)
return False return False
if isinstance(target, Member): if isinstance(target, Member):
if interaction.user.top_role <= target.top_role and await config.guild(interaction.guild).respect_hierarchy() is True: if ctx.author.top_role <= target.top_role and await config.guild(ctx.guild).respect_hierarchy() is True:
await interaction.response.send_message( await ctx.send(
content=error("You cannot moderate members with a higher role than you!"), content=error("You cannot moderate members with a higher role than you!"),
ephemeral=True, ephemeral=True,
) )
return False return False
if interaction.guild.get_member(interaction.client.user.id).top_role <= target.top_role: if target.guild_permissions.administrator:
await interaction.response.send_message( await ctx.send(content="You cannot moderate members with the Administrator permission!", ephemeral=True)
return False
if ctx.guild.get_member(ctx.bot.user.id).top_role <= target.top_role:
await ctx.send(
content=error("You cannot moderate members with a role higher than the bot!"), content=error("You cannot moderate members with a role higher than the bot!"),
ephemeral=True, ephemeral=True,
) )
@ -82,7 +99,7 @@ async def check_moddable(target: Union[User, Member], interaction: Interaction,
for role in target.roles: for role in target.roles:
if role.id in immune_roles: if role.id in immune_roles:
await interaction.response.send_message( await ctx.send(
content=error("You cannot moderate members with an immune role!"), content=error("You cannot moderate members with an immune role!"),
ephemeral=True, ephemeral=True,
) )
@ -91,140 +108,50 @@ async def check_moddable(target: Union[User, Member], interaction: Interaction,
return True return True
async def get_next_case_number(guild_id: str, cursor=None) -> int: async def log(ctx: commands.Context, moderation_id: int, resolved: bool = False) -> None:
"""This function returns the next case number from the MySQL table for a specific guild."""
from .database import connect
if not cursor:
database = connect()
cursor = database.cursor()
cursor.execute(f"SELECT moderation_id FROM `moderation_{guild_id}` ORDER BY moderation_id DESC LIMIT 1")
result = cursor.fetchone()
return (result[0] + 1) if result else 1
def generate_dict(result) -> dict:
return {
"moderation_id": result[0],
"timestamp": result[1],
"moderation_type": result[2],
"target_type": result[3],
"target_id": result[4],
"moderator_id": result[5],
"role_id": result[6],
"duration": result[7],
"end_timestamp": result[8],
"reason": result[9],
"resolved": result[10],
"resolved_by": result[11],
"resolve_reason": result[12],
"expired": result[13],
"changes": json.loads(result[14]),
"metadata": json.loads(result[15]),
}
async def fetch_user_dict(client: commands.Bot, user_id: str) -> dict:
"""This function returns a dictionary containing either user information or a standard deleted user template."""
if user_id == "?":
user_dict = {"id": "?", "name": "Unknown User", "discriminator": "0"}
else:
try:
user = client.get_user(int(user_id))
if user is None:
user = await client.fetch_user(int(user_id))
user_dict = {
"id": user.id,
"name": user.name,
"discriminator": user.discriminator,
}
except NotFound:
user_dict = {
"id": user_id,
"name": "Deleted User",
"discriminator": "0",
}
return user_dict
async def fetch_channel_dict(guild: Guild, channel_id: int) -> dict:
"""This function returns a dictionary containing either channel information or a standard deleted channel template."""
try:
channel = guild.get_channel(int(channel_id))
if not channel:
channel = await guild.fetch_channel(channel_id)
channel_dict = {
"id": channel.id,
"name": channel.name,
"mention": channel.mention,
}
except NotFound:
channel_dict = {"id": channel_id, "name": "Deleted Channel", "mention": None}
return channel_dict
async def fetch_role_dict(guild: Guild, role_id: int) -> dict:
"""This function returns a dictionary containing either role information or a standard deleted role template."""
role = guild.get_role(int(role_id))
if not role:
pass
return {"id": role.id, "name": role.name}
async def log(interaction: Interaction, moderation_id: int, resolved: bool = False) -> None:
"""This function sends a message to the guild's configured logging channel when an infraction takes place.""" """This function sends a message to the guild's configured logging channel when an infraction takes place."""
from .database import fetch_case from ..models.moderation import Moderation
from .factory import log_factory from .factory import log_factory
logging_channel_id = await config.guild(interaction.guild).log_channel() logging_channel_id = await config.guild(ctx.guild).log_channel()
if logging_channel_id != " ": if logging_channel_id != " ":
logging_channel = interaction.guild.get_channel(logging_channel_id) logging_channel = ctx.guild.get_channel(logging_channel_id)
case = await fetch_case(moderation_id, interaction.guild.id) try:
if case: moderation = await Moderation.find_by_id(ctx.bot, moderation_id, ctx.guild.id)
embed = await log_factory(interaction=interaction, case_dict=case, resolved=resolved) embed = await log_factory(ctx=ctx, moderation=moderation, resolved=resolved)
try: try:
await logging_channel.send(embed=embed) await logging_channel.send(embed=embed)
except Forbidden: except Forbidden:
return return
except ValueError:
return
async def send_evidenceformat(interaction: Interaction, case_dict: dict) -> None: async def send_evidenceformat(ctx: commands.Context, moderation_id: int) -> None:
"""This function sends an ephemeral message to the moderator who took the moderation action, with a pre-made codeblock for use in the mod-evidence channel.""" """This function sends an ephemeral message to the moderator who took the moderation action, with a pre-made codeblock for use in the mod-evidence channel."""
from ..models.moderation import Moderation
from .factory import evidenceformat_factory from .factory import evidenceformat_factory
send_evidence_bool = await config.user(interaction.user).auto_evidenceformat() or await config.guild(interaction.guild).auto_evidenceformat() or False send_evidence_bool = await config.user(ctx.author).auto_evidenceformat() or await config.guild(guild=ctx.guild).auto_evidenceformat() or False
if send_evidence_bool is False: if send_evidence_bool is True:
return moderation = await Moderation.find_by_id(ctx.bot, moderation_id, ctx.guild.id)
content = await evidenceformat_factory(moderation=moderation)
content = await evidenceformat_factory(interaction=interaction, case_dict=case_dict) if not ctx.interaction:
await interaction.followup.send(content=content, ephemeral=True) await ctx.author.send(content=content)
else:
await ctx.send(content=content, ephemeral=True)
def convert_timedelta_to_str(timedelta: td) -> str:
"""This function converts a timedelta object to a string."""
total_seconds = int(timedelta.total_seconds())
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
return f"{hours}:{minutes}:{seconds}"
def get_bool_emoji(value: Optional[bool]) -> str: def get_bool_emoji(value: Optional[bool]) -> str:
"""Returns a unicode emoji based on a boolean value.""" """Returns a unicode emoji based on a boolean value."""
if value is True: match value:
return "\N{WHITE HEAVY CHECK MARK}" case True:
if value is False: return "\N{WHITE HEAVY CHECK MARK}"
return "\N{NO ENTRY SIGN}" case False:
return "\N{BLACK QUESTION MARK ORNAMENT}\N{VARIATION SELECTOR-16}" return "\N{NO ENTRY SIGN}"
case _:
return "\N{BLACK QUESTION MARK ORNAMENT}\N{VARIATION SELECTOR-16}"
def get_pagesize_str(value: Union[int, None]) -> str: def get_pagesize_str(value: Union[int, None]) -> str:
@ -242,20 +169,108 @@ def create_pagesize_options() -> list[SelectOption]:
label="Default", label="Default",
value="default", value="default",
description="Reset the pagesize to the default value.", description="Reset the pagesize to the default value.",
), )
) )
options.extend(SelectOption(label=str(i), value=str(i), description=f"Set the pagesize to {i}") for i in range(1, 21)) for i in range(1, 21):
options.append(
SelectOption(
label=str(i),
value=str(i),
description=f"Set the pagesize to {i}.",
)
)
return options return options
def timedelta_from_relativedelta(relativedelta: rd) -> td: def timedelta_from_relativedelta(relativedelta: rd) -> timedelta:
"""Converts a relativedelta object to a timedelta object.""" """Converts a relativedelta object to a timedelta object."""
now = datetime.now() now = datetime.now()
then = now - relativedelta then = now - relativedelta
return now - then return now - then
def timedelta_from_string(string: str) -> timedelta:
"""Converts a string to a timedelta object."""
hours, minutes, seconds = map(int, string.split(":"))
return timedelta(hours=hours, minutes=minutes, seconds=seconds)
def timedelta_to_string(td: timedelta) -> str:
"""Converts a timedelta object to a string."""
days = td.days * 24
hours, remainder = divmod(td.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
return f"{days + hours}:{minutes:02}:{seconds:02}"
def get_footer_image(coginstance: commands.Cog) -> File: def get_footer_image(coginstance: commands.Cog) -> File:
"""Returns the footer image for the embeds.""" """Returns the footer image for the embeds."""
image_path = data_manager.bundled_data_path(coginstance) / "arrow.png" image_path = data_manager.bundled_data_path(coginstance) / "arrow.png"
return File(image_path, filename="arrow.png", description="arrow") return File(image_path, filename="arrow.png", description="arrow")
async def create_guild_table(guild: Guild) -> None:
from ..models.moderation import Moderation
try:
await Moderation.execute(f"SELECT * FROM `moderation_{guild.id}`", return_obj=False)
logger.trace("SQLite Table exists for server %s (%s)", guild.name, guild.id)
except aiosqlite.OperationalError:
query = f"""
CREATE TABLE `moderation_{guild.id}` (
moderation_id INTEGER PRIMARY KEY NOT NULL,
timestamp INTEGER NOT NULL,
moderation_type TEXT NOT NULL,
target_type TEXT NOT NULL,
target_id INTEGER NOT NULL,
moderator_id INTEGER NOT NULL,
role_id INTEGER,
duration TEXT,
end_timestamp INTEGER,
reason TEXT,
resolved INTEGER NOT NULL,
resolved_by TEXT,
resolve_reason TEXT,
expired INTEGER NOT NULL,
changes JSON NOT NULL,
metadata JSON NOT NULL
)
"""
await Moderation.execute(query=query, return_obj=False)
index_query_1 = f"CREATE INDEX IF NOT EXISTS idx_target_id ON moderation_{guild.id}(target_id);"
await Moderation.execute(query=index_query_1, return_obj=False)
index_query_2 = f"CREATE INDEX IF NOT EXISTS idx_moderator_id ON moderation_{guild.id}(moderator_id);"
await Moderation.execute(query=index_query_2, return_obj=False)
index_query_3 = f"CREATE INDEX IF NOT EXISTS idx_moderation_id ON moderation_{guild.id}(moderation_id);"
await Moderation.execute(query=index_query_3, return_obj=False)
insert_query = f"""
INSERT INTO `moderation_{guild.id}`
(moderation_id, timestamp, moderation_type, target_type, target_id, moderator_id, role_id, duration, end_timestamp, reason, resolved, resolved_by, resolve_reason, expired, changes, metadata)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"""
insert_values = (
0,
0,
"NULL",
"NULL",
0,
0,
None,
None,
None,
None,
0,
None,
None,
0,
dumps([]),
dumps({}),
)
await Moderation.execute(query=insert_query, parameters=insert_values, return_obj=False)
logger.trace("SQLite Table created for server %s (%s)", guild.name, guild.id)

View file

@ -26,7 +26,7 @@ class Backup(commands.Cog):
__author__ = ["[cswimr](https://www.coastalcommits.com/cswimr)"] __author__ = ["[cswimr](https://www.coastalcommits.com/cswimr)"]
__git__ = "https://www.coastalcommits.com/cswimr/SeaCogs" __git__ = "https://www.coastalcommits.com/cswimr/SeaCogs"
__version__ = "1.1.4" __version__ = "1.1.3"
__documentation__ = "https://seacogs.coastalcommits.com/backup/" __documentation__ = "https://seacogs.coastalcommits.com/backup/"
def __init__(self, bot: Red): def __init__(self, bot: Red):
@ -49,6 +49,7 @@ class Backup(commands.Cog):
@commands.is_owner() @commands.is_owner()
async def backup(self, ctx: commands.Context) -> None: async def backup(self, ctx: commands.Context) -> None:
"""Backup your installed cogs.""" """Backup your installed cogs."""
pass
@backup.command(name="export") @backup.command(name="export")
@commands.is_owner() @commands.is_owner()

View file

@ -11,7 +11,7 @@
"hidden": false, "hidden": false,
"disabled": false, "disabled": false,
"min_bot_version": "3.5.6", "min_bot_version": "3.5.6",
"max_bot_version": "3.5.17", "max_bot_version": "3.5.16",
"min_python_version": [ "min_python_version": [
3, 3,
9, 9,

View file

@ -21,7 +21,7 @@ class HotReload(commands.Cog):
__author__ = ["[cswimr](https://www.coastalcommits.com/cswimr)"] __author__ = ["[cswimr](https://www.coastalcommits.com/cswimr)"]
__git__ = "https://www.coastalcommits.com/cswimr/SeaCogs" __git__ = "https://www.coastalcommits.com/cswimr/SeaCogs"
__version__ = "1.4.2" __version__ = "1.4.1"
__documentation__ = "https://seacogs.coastalcommits.com/hotreload/" __documentation__ = "https://seacogs.coastalcommits.com/hotreload/"
def __init__(self, bot: Red) -> None: def __init__(self, bot: Red) -> None:
@ -60,7 +60,6 @@ class HotReload(commands.Cog):
] ]
return "\n".join(text) return "\n".join(text)
# pylint: disable=protected-access
async def get_paths(self) -> Generator[Path, None, None]: async def get_paths(self) -> Generator[Path, None, None]:
"""Retrieve user defined paths.""" """Retrieve user defined paths."""
cog_manager = self.bot._cog_mgr # noqa: SLF001 # We have to use this private method because there is no public API to get user defined paths cog_manager = self.bot._cog_mgr # noqa: SLF001 # We have to use this private method because there is no public API to get user defined paths
@ -92,6 +91,7 @@ class HotReload(commands.Cog):
@commands.group(name="hotreload") @commands.group(name="hotreload")
async def hotreload_group(self, ctx: commands.Context) -> None: async def hotreload_group(self, ctx: commands.Context) -> None:
"""HotReload configuration commands.""" """HotReload configuration commands."""
pass
@hotreload_group.command(name="notifychannel") @hotreload_group.command(name="notifychannel")
async def hotreload_notifychannel(self, ctx: commands.Context, channel: discord.TextChannel) -> None: async def hotreload_notifychannel(self, ctx: commands.Context, channel: discord.TextChannel) -> None:
@ -155,7 +155,6 @@ class HotReloadHandler(RegexMatchingEventHandler):
loop=self.cog.bot.loop, loop=self.cog.bot.loop,
) )
# pylint: disable=protected-access
async def reload_cogs(self, cog_names: Sequence[str], paths: Sequence[Path]) -> None: async def reload_cogs(self, cog_names: Sequence[str], paths: Sequence[Path]) -> None:
"""Reload modified cogs.""" """Reload modified cogs."""
if not self.compile_modified_files(cog_names, paths): if not self.compile_modified_files(cog_names, paths):

View file

@ -2,29 +2,28 @@ from redbot.core import Config
config: Config = Config.get_conf(None, identifier=457581387213637448123567, cog_name="Pterodactyl", force_registration=True) config: Config = Config.get_conf(None, identifier=457581387213637448123567, cog_name="Pterodactyl", force_registration=True)
def register_config(config_obj: Config) -> None: def register_config(config_obj: Config) -> None:
config_obj.register_global( config_obj.register_global(
base_url=None, base_url=None,
server_id=None, server_id=None,
console_channel=None, console_channel=None,
console_commands_enabled=False, console_commands_enabled=False,
current_status="", current_status='',
chat_regex=r"^\[\d{2}:\d{2}:\d{2}\sINFO\]: (?!\[(?:Server|Rcon)\])(?:<|\[)(\w+)(?:>|\]) (.*)", chat_regex=r"^\[\d{2}:\d{2}:\d{2}\sINFO\]: (?!\[(?:Server|Rcon)\])(?:<|\[)(\w+)(?:>|\]) (.*)",
server_regex=r"^\[\d{2}:\d{2}:\d{2} INFO\]:(?: \[Not Secure\])? \[(?:Server|Rcon)\] (.*)", server_regex=r"^\[\d{2}:\d{2}:\d{2} INFO\]:(?: \[Not Secure\])? \[(?:Server|Rcon)\] (.*)",
join_regex=r"^\[\d{2}:\d{2}:\d{2} INFO\]: ([^<\n]+) joined the game$", join_regex=r"^\[\d{2}:\d{2}:\d{2} INFO\]: ([^<\n]+) joined the game$",
leave_regex=r"^\[\d{2}:\d{2}:\d{2} INFO\]: ([^<\n]+) left the game$", leave_regex=r"^\[\d{2}:\d{2}:\d{2} INFO\]: ([^<\n]+) left the game$",
achievement_regex=r"^\[\d{2}:\d{2}:\d{2} INFO\]: (.*) has (made the advancement|completed the challenge) \[(.*)\]$", achievement_regex=r"^\[\d{2}:\d{2}:\d{2} INFO\]: (.*) has (made the advancement|completed the challenge) \[(.*)\]$",
chat_command='tellraw @a ["",{"text":".$N ","color":".$C","insertion":"<@.$I>","hoverEvent":{"action":"show_text","contents":"Shift click to mention this user inside Discord"}},{"text":"(DISCORD):","color":"blue","clickEvent":{"action":"open_url","value":".$V"},"hoverEvent":{"action":"show_text","contents":"Click to join the Discord Server"}},{"text":" .$M","color":"white"}]', # noqa: E501 chat_command='tellraw @a ["",{"text":".$N ","color":".$C","insertion":"<@.$I>","hoverEvent":{"action":"show_text","contents":"Shift click to mention this user inside Discord"}},{"text":"(DISCORD):","color":"blue","clickEvent":{"action":"open_url","value":".$V"},"hoverEvent":{"action":"show_text","contents":"Click to join the Discord Server"}},{"text":" .$M","color":"white"}]', # noqa: E501
topic="Server IP: .$H\nServer Players: .$P/.$M", topic='Server IP: .$H\nServer Players: .$P/.$M',
topic_hostname=None, topic_hostname=None,
topic_port=25565, topic_port=25565,
api_endpoint="minecraft", api_endpoint="minecraft",
chat_channel=None, chat_channel=None,
startup_msg="Server started!", startup_msg='Server started!',
shutdown_msg="Server stopped!", shutdown_msg='Server stopped!',
join_msg="Welcome to the server! 👋", join_msg='Welcome to the server! 👋',
leave_msg="Goodbye! 👋", leave_msg='Goodbye! 👋',
mask_ip=True, mask_ip=True,
invite=None, invite=None,
regex_blacklist={}, regex_blacklist={},

View file

@ -9,10 +9,7 @@
"hidden": false, "hidden": false,
"disabled": false, "disabled": false,
"min_bot_version": "3.5.0", "min_bot_version": "3.5.0",
"min_python_version": [3, 10, 0], "min_python_version": [3, 8, 0],
"requirements": [ "requirements": ["git+https://github.com/cswimr/pydactyl", "websockets"],
"git+https://github.com/iamkubi/pydactyl@v2.0.5",
"websockets"
],
"tags": ["pterodactyl", "minecraft", "server", "management"] "tags": ["pterodactyl", "minecraft", "server", "management"]
} }

View file

@ -2,14 +2,6 @@ import aiohttp
async def get_status(host: str, port: int = 25565) -> tuple[bool, dict]: async def get_status(host: str, port: int = 25565) -> tuple[bool, dict]:
"""Get the status of a Minecraft server using the [mcsrvstat.us API](https://api.mcsrvstat.us).
Args:
host (str): The host of the server.
port (int, optional): The port to connect to. Defaults to 25565.
Returns:
A tuple containing a boolean and a dictionary. The boolean is True if the server is online, or False if it is offline. The dictionary contains the response from the API."""
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
async with session.get(f"https://api.mcsrvstat.us/2/{host}:{port}") as response: async with session.get(f"https://api.mcsrvstat.us/2/{host}:{port}") as response:
response = await response.json() # noqa: PLW2901 response = await response.json() # noqa: PLW2901

View file

@ -23,7 +23,7 @@ class Pterodactyl(commands.Cog):
__author__ = ["[cswimr](https://www.coastalcommits.com/cswimr)"] __author__ = ["[cswimr](https://www.coastalcommits.com/cswimr)"]
__git__ = "https://www.coastalcommits.com/cswimr/SeaCogs" __git__ = "https://www.coastalcommits.com/cswimr/SeaCogs"
__version__ = "2.0.9" __version__ = "2.0.6"
__documentation__ = "https://seacogs.coastalcommits.com/pterodactyl/" __documentation__ = "https://seacogs.coastalcommits.com/pterodactyl/"
def __init__(self, bot: Red): def __init__(self, bot: Red):
@ -234,7 +234,7 @@ class Pterodactyl(commands.Cog):
if view.result is True: if view.result is True:
await message.edit(content=f"Sending websocket command to {action} server...", view=None) await message.edit(content=f"Sending websocket command to {action} server...", view=None)
await self._send(json.dumps({"event": "set state", "args": [action]})) await self._websocket_send(json.dumps({"event": "set state", "args": [action]}))
await message.edit(content=f"Server {action_ing}", view=None) await message.edit(content=f"Server {action_ing}", view=None)
return return
@ -248,7 +248,7 @@ class Pterodactyl(commands.Cog):
ctx = await self.bot.get_context(ctx) ctx = await self.bot.get_context(ctx)
if channel: if channel:
await channel.send(f"Received console command from {ctx.author.id}: {command[:1900]}", allowed_mentions=discord.AllowedMentions.none()) await channel.send(f"Received console command from {ctx.author.id}: {command[:1900]}", allowed_mentions=discord.AllowedMentions.none())
await self._send(json.dumps({"event": "send command", "args": [command]})) await self._websocket_send(json.dumps({"event": "send command", "args": [command]}))
await ctx.send(f"Command sent to server. {box(command, 'json')}") await ctx.send(f"Command sent to server. {box(command, 'json')}")
@commands.Cog.listener() @commands.Cog.listener()
@ -416,7 +416,7 @@ class Pterodactyl(commands.Cog):
- `.$V` (version) - `.$V` (version)
- `.$D` (description / Message of the Day)""" - `.$D` (description / Message of the Day)"""
await config.topic.set(text) await config.topic.set(text)
await ctx.send(f"Topic set to:\n{box(text, 'markdown')}") await ctx.send(f"Topic set to:\n{box(text, 'yaml')}")
@pterodactyl_config.group(name="chat") @pterodactyl_config.group(name="chat")
async def pterodactyl_config_chat(self, ctx: commands.Context): async def pterodactyl_config_chat(self, ctx: commands.Context):
@ -607,19 +607,19 @@ class Pterodactyl(commands.Cog):
**Topic Hostname:** `{topic_hostname}` **Topic Hostname:** `{topic_hostname}`
**Topic Port:** `{topic_port}` **Topic Port:** `{topic_port}`
**Topic Text:** {box(topic_text, "markdown")} **Topic Text:** {box(topic_text, "yaml")}
**Chat Command:** {box(chat_command, "json")} **Chat Command:** {box(chat_command, "json")}
**Chat Regex:** {box(chat_regex, "regex")} **Chat Regex:** {box(chat_regex, "re")}
**Server Regex:** {box(server_regex, "regex")} **Server Regex:** {box(server_regex, "re")}
**Join Regex:** {box(join_regex, "regex")} **Join Regex:** {box(join_regex, "re")}
**Leave Regex:** {box(leave_regex, "regex")} **Leave Regex:** {box(leave_regex, "re")}
**Achievement Regex:** {box(achievement_regex, "regex")}""" **Achievement Regex:** {box(achievement_regex, "re")}"""
await ctx.send(embed=embed) await ctx.send(embed=embed)
if not len(regex_blacklist) == 0: if not len(regex_blacklist) == 0:
regex_blacklist_embed = discord.Embed(color=await ctx.embed_color(), title="Regex Blacklist") regex_blacklist_embed = discord.Embed(color=await ctx.embed_color(), title="Regex Blacklist")
for name, regex in regex_blacklist.items(): for name, regex in regex_blacklist.items():
regex_blacklist_embed.add_field(name=name, value=box(regex, "regex"), inline=False) regex_blacklist_embed.add_field(name=name, value=box(regex, "re"), inline=False)
await ctx.send(embed=regex_blacklist_embed) await ctx.send(embed=regex_blacklist_embed)
def get_bool_str(self, inp: bool) -> str: def get_bool_str(self, inp: bool) -> str:

View file

@ -153,7 +153,7 @@ async def retrieve_websocket_credentials(coginstance: Pterodactyl) -> dict:
client = PterodactylClient(base_url, api_key).client client = PterodactylClient(base_url, api_key).client
coginstance.client = client coginstance.client = client
websocket_credentials: dict[str, Any] = client.servers.get_websocket(server_id) websocket_credentials: dict[str, Any] = client.servers.get_websocket(server_id).json()
if not websocket_credentials: if not websocket_credentials:
coginstance.maybe_cancel_task() coginstance.maybe_cancel_task()
raise ValueError("Failed to retrieve websocket credentials. Please ensure the API details are correctly configured.") raise ValueError("Failed to retrieve websocket credentials. Please ensure the API details are correctly configured.")

View file

@ -7,36 +7,36 @@ license = { file = "LICENSE" }
readme = "README.md" readme = "README.md"
requires-python = ">=3.11" requires-python = ">=3.11"
dependencies = [ dependencies = [
"aiosqlite==0.21.0", "aiosqlite>=0.20.0",
"beautifulsoup4==4.13.3", "beautifulsoup4>=4.12.3",
"colorthief==0.2.1", "colorthief>=0.2.1",
"markdownify==1.1.0", "markdownify>=0.14.1",
"numpy==2.2.4", "numpy>=2.2.2",
"phx-class-registry==5.1.1", "phx-class-registry>=5.1.1",
"pillow==10.4.0", "pillow>=10.4.0",
"pip==25.0.1", "pip>=25.0",
"py-dactyl", "py-dactyl",
"pydantic==2.11.1", "pydantic>=2.10.6",
"red-discordbot==3.5.18", "red-discordbot>=3.5.14",
"watchdog==6.0.0", "watchdog>=6.0.0",
"websockets==15.0.1", "websockets>=14.2",
] ]
[dependency-groups] [dependency-groups]
documentation = [ documentation = [
"mkdocs==1.6.1", "mkdocs>=1.6.1",
"mkdocs-git-authors-plugin==0.9.4", "mkdocs-git-authors-plugin>=0.9.2",
"mkdocs-git-revision-date-localized-plugin==1.4.5", "mkdocs-git-revision-date-localized-plugin>=1.3.0",
"mkdocs-material[imaging]==9.6.10", "mkdocs-material[imaging]>=9.5.50",
"mkdocs-redirects==1.2.2", "mkdocs-redirects>=1.2.2",
"mkdocstrings[python]==0.29.0", "mkdocstrings[python]>=0.27.0",
] ]
[tool.uv] [tool.uv]
dev-dependencies = ["pylint==3.3.6", "ruff==0.11.2", "sqlite-web==0.6.4"] dev-dependencies = ["pylint>=3.3.3", "ruff>=0.9.3", "sqlite-web>=0.6.4"]
[tool.uv.sources] [tool.uv.sources]
py-dactyl = { git = "https://github.com/iamkubi/pydactyl", tag = "v2.0.5" } py-dactyl = { git = "https://github.com/cswimr/pydactyl" }
[tool.basedpyright] [tool.basedpyright]
typeCheckingMode = "basic" typeCheckingMode = "basic"
@ -45,32 +45,32 @@ reportAttributeAccessIssue = false # disabled because `commands.group.command` i
[tool.ruff] [tool.ruff]
# Exclude a variety of commonly ignored directories. # Exclude a variety of commonly ignored directories.
exclude = [ exclude = [
".bzr", ".bzr",
".direnv", ".direnv",
".eggs", ".eggs",
".git", ".git",
".git-rewrite", ".git-rewrite",
".hg", ".hg",
".ipynb_checkpoints", ".ipynb_checkpoints",
".mypy_cache", ".mypy_cache",
".nox", ".nox",
".pants.d", ".pants.d",
".pyenv", ".pyenv",
".pytest_cache", ".pytest_cache",
".pytype", ".pytype",
".ruff_cache", ".ruff_cache",
".svn", ".svn",
".tox", ".tox",
".venv", ".venv",
".vscode", ".vscode",
"__pypackages__", "__pypackages__",
"_build", "_build",
"buck-out", "buck-out",
"build", "build",
"dist", "dist",
"node_modules", "node_modules",
"site-packages", "site-packages",
"venv", "venv",
] ]
# Same as Black. # Same as Black.
@ -85,29 +85,29 @@ target-version = "py311"
# Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or # Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or
# McCabe complexity (`C901`) by default. # McCabe complexity (`C901`) by default.
select = [ select = [
"I", "I",
"N", "N",
"F", "F",
"W", "W",
"E", "E",
"G", "G",
"A", "A",
"COM", "COM",
"INP", "INP",
"T20", "T20",
"PLC", "PLC",
"PLE", "PLE",
"PLW", "PLW",
"PLR", "PLR",
"LOG", "LOG",
"SLF", "SLF",
"ERA", "ERA",
"FIX", "FIX",
"PERF", "PERF",
"C4", "C4",
"EM", "EM",
"RET", "RET",
"RSE", "RSE",
] ]
ignore = ["PLR0911", "PLR0912", "PLR0915", "PLR2004", "PLR0913", "EM101"] ignore = ["PLR0911", "PLR0912", "PLR0915", "PLR2004", "PLR0913", "EM101"]

1005
uv.lock generated

File diff suppressed because it is too large Load diff