Compare commits

..

14 commits
main ... tts

Author SHA1 Message Date
9549690767
Merge remote-tracking branch 'origin/main' into tts
Some checks failed
Actions / Build Documentation (MkDocs) (pull_request) Successful in 50s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 1m2s
2024-09-15 23:40:34 -04:00
a43fd3cce1
added __pycache__ to .gitignore 2024-09-15 11:14:14 -04:00
ea0db88fbe
fix(repo): add pylav as a dependency
Some checks failed
Actions / Build Documentation (MkDocs) (pull_request) Successful in 41s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 53s
2024-05-04 10:24:05 -04:00
e587b4c32f
Merge branch 'main' into tts
Some checks failed
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 6s
Actions / Build Documentation (MkDocs) (pull_request) Failing after 8s
2024-05-04 10:21:47 -04:00
e02a97f689 Merge branch 'main' into tts
Some checks failed
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 23s
Actions / Build Documentation (MkDocs) (pull_request) Successful in 24s
2024-02-28 11:30:51 -05:00
01c78d6e5b
Merge branch 'main' into tts
Some checks failed
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 24s
Actions / Build Documentation (MkDocs) (pull_request) Successful in 26s
2024-02-28 11:28:24 -05:00
17312348fc
fix(tts): awaited a coroutine
All checks were successful
Actions / Lint Code (Ruff) (pull_request) Successful in 10s
Actions / Build Documentation (MkDocs) (pull_request) Successful in 26s
2024-02-21 11:48:27 -05:00
567f51fb45
fix(tts): turned autohelp off for tts command
All checks were successful
Actions / Lint Code (Ruff) (pull_request) Successful in 15s
Actions / Build Documentation (MkDocs) (pull_request) Successful in 27s
2024-02-21 11:47:22 -05:00
39fead0928
fix(tts): fixed missing embed in menu 2024-02-21 11:47:13 -05:00
3c4fba46b6
feat(tts): bunch of changes
All checks were successful
Actions / Lint Code (Ruff) (pull_request) Successful in 15s
Actions / Build Documentation (MkDocs) (pull_request) Successful in 27s
- changed how the cog loads, instead of depending on the `PyLavPlayer` cog, it'll just load PyLav from the `__init__.py` file
- moved configuration to a separate file
- added a configuration menu
- added pylav as a dependency in poetry and `info.json`
- set repository python version to `>=3.11,<3.12`
2024-02-21 10:53:28 -05:00
bcca864d02
feat(tts): made pylav check happen on message invocation instead of on cog load
All checks were successful
Actions / Lint Code (Ruff) (pull_request) Successful in 8s
Actions / Build Documentation (MkDocs) (pull_request) Successful in 15s
2024-02-19 18:51:59 -05:00
e5d466cf8b
fix(tts): awaited a coroutine and added an error message if you load the cog without pylav loaded
All checks were successful
Actions / Lint Code (Ruff) (pull_request) Successful in 8s
Actions / Build Documentation (MkDocs) (pull_request) Successful in 14s
2024-02-19 18:42:13 -05:00
014b2b4ef0
misc(tts): comment anchors are cool or smth
All checks were successful
Actions / Lint Code (Ruff) (pull_request) Successful in 6s
Actions / Build Documentation (MkDocs) (pull_request) Successful in 13s
2024-02-19 18:37:34 -05:00
a2f61d697f
feat(tts): added new cog
All checks were successful
Actions / Lint Code (Ruff) (pull_request) Successful in 10s
Actions / Build Documentation (MkDocs) (pull_request) Successful in 14s
2024-02-19 18:35:44 -05:00
66 changed files with 5063 additions and 3522 deletions

View file

@ -12,5 +12,5 @@ Aurora is a fully-featured moderation system. It is heavily inspired by Galactic
```bash ```bash
[p]repo add seacogs https://www.coastalcommits.com/cswimr/SeaCogs [p]repo add seacogs https://www.coastalcommits.com/cswimr/SeaCogs
[p]cog install seacogs aurora [p]cog install seacogs aurora
[p]load aurora [p]cog load aurora
``` ```

View file

@ -7,7 +7,7 @@ Backup allows you to export a JSON list of all of your installed repositories an
```bash ```bash
[p]repo add seacogs https://www.coastalcommits.com/cswimr/SeaCogs [p]repo add seacogs https://www.coastalcommits.com/cswimr/SeaCogs
[p]cog install seacogs backup [p]cog install seacogs backup
[p]load backup [p]cog load backup
``` ```
## Version Compatibility ## Version Compatibility

View file

@ -8,7 +8,7 @@ This cog does require an api key to work.
```bash ```bash
[p]repo add seacogs https://www.coastalcommits.com/cswimr/SeaCogs [p]repo add seacogs https://www.coastalcommits.com/cswimr/SeaCogs
[p]cog install seacogs bible [p]cog install seacogs bible
[p]load bible [p]cog load bible
``` ```
## Setup ## Setup
@ -21,9 +21,8 @@ Then, you can use `[p]set api` to set the API key. Make sure your formatting mat
## Commands ## Commands
### bible passage ### bible passage
- Usage: `[p]bible passage <book> <passage>`
- Usage: `[p]bible passage <book> <passage>` - Aliases: `verse`
- Aliases: `verse`
Get a Bible passage. Get a Bible passage.
@ -32,7 +31,6 @@ Example usage:
`[p]bible passage John 3:16-3:17` `[p]bible passage John 3:16-3:17`
### bible random ### bible random
- Usage: `[p]bible random`
- Usage: `[p]bible random`
Get a random Bible verse. Get a random Bible verse.

View file

@ -7,7 +7,7 @@ EmojiInfo allows you to retrieve information about an emoji.
```bash ```bash
[p]repo add seacogs https://www.coastalcommits.com/cswimr/SeaCogs [p]repo add seacogs https://www.coastalcommits.com/cswimr/SeaCogs
[p]cog install seacogs emojiinfo [p]cog install seacogs emojiinfo
[p]load emojiinfo [p]cog load emojiinfo
``` ```
## Commands ## Commands

View file

@ -1,26 +0,0 @@
# HotReload
HotReload automatically reloads cogs in local cog paths on file change.
This is useful for development, as it allows you to make changes to your cogs and see the changes reflected in Discord immediately, without having to manually `[p]reload` the cog.
## Installation
```bash
[p]repo add seacogs https://www.coastalcommits.com/cswimr/SeaCogs
[p]cog install seacogs hotreload
[p]load hotreload
```
## Commands
### hotreload compile
Determines if the cog should try to compile a modified Python file before reloading the associated cog. Useful for catching syntax errors. Disabled by default.
### hotreload notifychannel
Set the channel where hotreload will send notifications when a cog is reloaded.
### hotreload list
Debugging command that shows the list of currently active observers. May be expanded in the future to show watched file paths.

View file

@ -7,7 +7,7 @@ Nerdify allows you to nerdify other people's text.
```bash ```bash
[p]repo add seacogs https://www.coastalcommits.com/cswimr/SeaCogs [p]repo add seacogs https://www.coastalcommits.com/cswimr/SeaCogs
[p]cog install seacogs nerdify [p]cog install seacogs nerdify
[p]load nerdify [p]cog load nerdify
``` ```
## Commands ## Commands

View file

@ -12,5 +12,5 @@ Pterodactyl allows for connecting to a Pterodactyl server through websockets. It
```bash ```bash
[p]repo add seacogs https://www.coastalcommits.com/cswimr/SeaCogs [p]repo add seacogs https://www.coastalcommits.com/cswimr/SeaCogs
[p]cog install seacogs pterodactyl [p]cog install seacogs pterodactyl
[p]load pterodactyl [p]cog load aurora
``` ```

View file

@ -10,7 +10,7 @@ There are a few caveats to running an instance of Red on Pterodactyl.
- You will not receive any support from the Red developers. - You will not receive any support from the Red developers.
- The built-in Audio cog will not work. - The built-in Audio cog will not work.
- Depending on your host, you might have to request a [`tmpfs` size increase](https://github.com/pelican-eggs/eggs/tree/master/bots/discord/redbot#additional-requirements). - Depending on your host, you might have to request a [`tmpfs` size increase](https://github.com/ign-gg/Pterodactyl-Eggs/tree/master/bots/discord/redbot#additional-requirements).
If these are unacceptable to you, you should [install Red normally](https://docs.discord.red/en/stable/install_guides/index.html). If these are unacceptable to you, you should [install Red normally](https://docs.discord.red/en/stable/install_guides/index.html).
/// ///

View file

@ -1,15 +0,0 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.py]
indent_size = 4
[*.md]
trim_trailing_whitespace = false

1
.envrc
View file

@ -1 +0,0 @@
use flake

View file

@ -1,6 +1,8 @@
name: Bug Report name: Bug Report
about: File a bug report about: File a bug report
title: "[Cog Name] "
labels: [bug] labels: [bug]
ref: master
body: body:
- type: markdown - type: markdown
attributes: attributes:

View file

@ -1,6 +1,8 @@
name: Suggestion name: Suggestion
about: Trying to suggest something for SeaCogs? Use this. about: Trying to suggest something for SeaCogs? Use this.
labels: [enhancement] title: "[Cog Name] "
labels: enhancement
ref: master
body: body:
- type: markdown - type: markdown
attributes: attributes:
@ -11,7 +13,7 @@ body:
attributes: attributes:
label: What cog is your feature request for? label: What cog is your feature request for?
description: Specify the cog within the repository. description: Specify the cog within the repository.
placeholder: E.g., Pterodactyl placeholder: E.g., ModerationCog
validations: validations:
required: true required: true
- type: textarea - type: textarea

View file

@ -2,5 +2,5 @@
<!-- Create a new issue, if it doesn't exist yet --> <!-- Create a new issue, if it doesn't exist yet -->
- [ ] By submitting this pull request, I permit [cswimr](https://www.coastalcommits.com/cswimr) to license my work under - [ ] By submitting this pull request, I permit cswimr to license my work under
the [Mozilla Public License Version 2.0](https://www.coastalcommits.com/cswimr/SeaCogs/src/branch/main/LICENSE). the [Mozilla Public License Version 2.0](https://www.coastalcommits.com/cswimr/SeaCogs/src/branch/main/LICENSE).

View file

@ -12,7 +12,6 @@
too-many-locals, too-many-locals,
too-many-public-methods, too-many-public-methods,
too-many-statements, too-many-statements,
too-many-positional-arguments,
arguments-differ, arguments-differ,
too-many-return-statements, too-many-return-statements,
import-outside-toplevel, import-outside-toplevel,

View file

@ -2,65 +2,47 @@ name: Actions
on: on:
push: push:
branches: branches:
- main - 'main'
pull_request: pull_request:
jobs: jobs:
lint: 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:seacogs
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 uses: actions/checkout@v3
- name: "Setup uv" - name: Install dependencies
uses: actions/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5 run: poetry install --with dev --no-root
with:
version: "latest"
enable-cache: true
prune-cache: false
github-token: ${{ secrets.GITHUBTOKEN }}
- name: "Install dependencies"
run: uv sync
- name: Analysing code with Ruff - name: Analysing code with Ruff
run: uv run ruff check $(git ls-files '*.py') run: ./.venv/bin/ruff check $(git ls-files '*.py')
continue-on-error: true continue-on-error: true
- name: Analysing code with Pylint - name: Analysing code with Pylint
run: uv run pylint --rcfile=.forgejo/workflows/config/.pylintrc $(git ls-files '*.py') run: ./.venv/bin/pylint --rcfile=.forgejo/workflows/config/.pylintrc $(git ls-files '*.py')
docs: 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:seacogs
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 uses: actions/checkout@v3
with: with:
fetch-depth: 0 fetch-depth: 0
- name: "Setup uv"
uses: actions/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5
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: poetry install --with docs --no-root
- 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: |
export SITE_URL="https://$CI_ACTION_REF_NAME_SLUG.seacogs.coastalcommits.com" export SITE_URL="https://$CI_ACTION_REF_NAME_SLUG.seacogs.coastalcommits.com"
export EDIT_URI="src/branch/$CI_ACTION_REF_NAME/.docs" export EDIT_URI="src/branch/$CI_ACTION_REF_NAME/.docs"
uv run mkdocs build -v ./.venv/bin/mkdocs build -v
- name: Deploy documentation - name: Deploy documentation
run: | run: |
@ -74,13 +56,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_SECRET }}" \
--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 }}

5
.gitignore vendored
View file

@ -1,8 +1,5 @@
.cache .cache
.vscode
site site
.venv .venv
.data
__pycache__ __pycache__
.mypy_cache/
.ruff_cache/
.direnv/

12
.vscode/launch.json vendored
View file

@ -1,12 +0,0 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Red-DiscordBot",
"type": "debugpy",
"request": "launch",
"module": "redbot",
"args": ["local", "--dev", "-vvv", "--load-cogs=hotreload"]
}
]
}

32
.vscode/settings.json vendored
View file

@ -1,32 +0,0 @@
{
"[python]": {
"editor.codeActionsOnSave": {
"source.fixAll": "explicit"
},
"editor.defaultFormatter": "charliermarsh.ruff"
},
"[json]": {
"editor.defaultFormatter": "vscode.json-language-features"
},
"[jsonc]": {
"editor.defaultFormatter": "vscode.json-language-features"
},
"files.exclude": {
"**/.git": true,
"**/__pycache__": true,
"**/.ruff_cache": true,
"**/.mypy_cache": true
},
"python.analysis.diagnosticSeverityOverrides": {
"reportAttributeAccessIssue": false, // disabled because `commands.group.command` is listed as Any / Unknown for some reason
"reportCallIssue": "information"
},
"python.analysis.diagnosticMode": "workspace",
"python.analysis.supportDocstringTemplate": true,
"python.analysis.typeCheckingMode": "basic",
"python.analysis.typeEvaluation.enableReachabilityAnalysis": true,
"python.analysis.typeEvaluation.strictDictionaryInference": true,
"python.analysis.typeEvaluation.strictListInference": true,
"python.analysis.typeEvaluation.strictSetInference": true,
"editor.formatOnSave": true,
}

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
``` ```

View file

@ -17,7 +17,7 @@ class AntiPolls(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.0.3" __version__ = "1.0.1"
__documentation__ = "https://seacogs.coastalcommits.com/antipolls/" __documentation__ = "https://seacogs.coastalcommits.com/antipolls/"
def __init__(self, bot: Red): def __init__(self, bot: Red):
@ -45,11 +45,11 @@ class AntiPolls(commands.Cog):
] ]
return "\n".join(text) return "\n".join(text)
async def red_delete_data_for_user(self, **kwargs): # pylint: disable=unused-argument async def red_delete_data_for_user(self, **kwargs): # pylint: disable=unused-argument
"""Nothing to delete.""" """Nothing to delete."""
return return
@commands.Cog.listener("on_message") @commands.Cog.listener('on_message')
async def polls_listener(self, message: discord.Message) -> None: async def polls_listener(self, message: discord.Message) -> None:
if message.guild is None: if message.guild is None:
return self.logger.verbose("Message in direct messages ignored") return self.logger.verbose("Message in direct messages ignored")
@ -62,13 +62,13 @@ class AntiPolls(commands.Cog):
guild_config = await self.config.guild(message.guild).all() guild_config = await self.config.guild(message.guild).all()
if guild_config["manage_messages"] is True and message.author.guild_permissions.manage_messages: if guild_config['manage_messages'] is True and message.author.guild_permissions.manage_messages:
return self.logger.verbose("Message from user with Manage Messages permission ignored") return self.logger.verbose("Message from user with Manage Messages permission ignored")
if message.channel.id in guild_config["channel_whitelist"]: if message.channel.id in guild_config['channel_whitelist']:
return self.logger.verbose("Message in whitelisted channel %s ignored", message.channel.id) return self.logger.verbose("Message in whitelisted channel %s ignored", message.channel.id)
if any(role.id in guild_config["role_whitelist"] for role in message.author.roles): if any(role.id in guild_config['role_whitelist'] for role in message.author.roles):
return self.logger.verbose("Message from whitelisted role %s ignored", message.author.roles) return self.logger.verbose("Message from whitelisted role %s ignored", message.author.roles)
if not message.content and not message.embeds and not message.attachments and not message.stickers: if not message.content and not message.embeds and not message.attachments and not message.stickers:
@ -80,9 +80,9 @@ class AntiPolls(commands.Cog):
return self.logger.error("Failed to delete message: %s", e) return self.logger.error("Failed to delete message: %s", e)
return self.logger.trace("Deleted poll message %s", message.id) return self.logger.trace("Deleted poll message %s", message.id)
return self.logger.verbose("Message %s is not a poll, ignoring", message.id) self.logger.verbose("Message %s is not a poll, ignoring", message.id)
@commands.group(name="antipolls", aliases=["ap"]) # type: ignore @commands.group(name="antipolls", aliases=["ap"])
@commands.guild_only() @commands.guild_only()
@commands.admin_or_permissions(manage_guild=True) @commands.admin_or_permissions(manage_guild=True)
async def antipolls(self, ctx: commands.Context) -> None: async def antipolls(self, ctx: commands.Context) -> None:
@ -95,8 +95,6 @@ class AntiPolls(commands.Cog):
@antipolls_roles.command(name="add") @antipolls_roles.command(name="add")
async def antipolls_roles_add(self, ctx: commands.Context, *roles: discord.Role) -> None: async def antipolls_roles_add(self, ctx: commands.Context, *roles: discord.Role) -> None:
"""Add roles to the whitelist.""" """Add roles to the whitelist."""
assert ctx.guild is not None # using `assert` here and in the rest of this file to satisfy typecheckers
# this is safe because the commands are part of a guild-only command group
async with self.config.guild(ctx.guild).role_whitelist() as role_whitelist: async with self.config.guild(ctx.guild).role_whitelist() as role_whitelist:
role_whitelist: list role_whitelist: list
failed: list[discord.Role] = [] failed: list[discord.Role] = []
@ -112,7 +110,6 @@ class AntiPolls(commands.Cog):
@antipolls_roles.command(name="remove") @antipolls_roles.command(name="remove")
async def antipolls_roles_remove(self, ctx: commands.Context, *roles: discord.Role) -> None: async def antipolls_roles_remove(self, ctx: commands.Context, *roles: discord.Role) -> None:
"""Remove roles from the whitelist.""" """Remove roles from the whitelist."""
assert ctx.guild is not None
async with self.config.guild(ctx.guild).role_whitelist() as role_whitelist: async with self.config.guild(ctx.guild).role_whitelist() as role_whitelist:
role_whitelist: list role_whitelist: list
failed: list[discord.Role] = [] failed: list[discord.Role] = []
@ -126,14 +123,13 @@ class AntiPolls(commands.Cog):
await ctx.send(f"The following roles were not in the whitelist: {humanize_list([role.mention for role in failed])}", delete_after=10) await ctx.send(f"The following roles were not in the whitelist: {humanize_list([role.mention for role in failed])}", delete_after=10)
@antipolls_roles.command(name="list") @antipolls_roles.command(name="list")
async def antipolls_roles_list(self, ctx: commands.Context) -> discord.Message: async def antipolls_roles_list(self, ctx: commands.Context) -> None:
"""List roles in the whitelist.""" """List roles in the whitelist."""
assert ctx.guild is not None
role_whitelist = await self.config.guild(ctx.guild).role_whitelist() role_whitelist = await self.config.guild(ctx.guild).role_whitelist()
if not role_whitelist: if not role_whitelist:
return await ctx.send("No roles in the whitelist.") return await ctx.send("No roles in the whitelist.")
roles = [role for role in (ctx.guild.get_role(role) for role in role_whitelist) if role is not None] roles = [ctx.guild.get_role(role) for role in role_whitelist]
return await ctx.send(humanize_list([role.mention for role in roles])) await ctx.send(humanize_list([role.mention for role in roles]))
@antipolls.group(name="channels") @antipolls.group(name="channels")
async def antipolls_channels(self, ctx: commands.Context) -> None: async def antipolls_channels(self, ctx: commands.Context) -> None:
@ -142,7 +138,6 @@ class AntiPolls(commands.Cog):
@antipolls_channels.command(name="add") @antipolls_channels.command(name="add")
async def antipolls_channels_add(self, ctx: commands.Context, *channels: discord.TextChannel) -> None: async def antipolls_channels_add(self, ctx: commands.Context, *channels: discord.TextChannel) -> None:
"""Add channels to the whitelist.""" """Add channels to the whitelist."""
assert ctx.guild is not None
async with self.config.guild(ctx.guild).channel_whitelist() as channel_whitelist: async with self.config.guild(ctx.guild).channel_whitelist() as channel_whitelist:
channel_whitelist: list channel_whitelist: list
failed: list[discord.TextChannel] = [] failed: list[discord.TextChannel] = []
@ -158,7 +153,6 @@ class AntiPolls(commands.Cog):
@antipolls_channels.command(name="remove") @antipolls_channels.command(name="remove")
async def antipolls_channels_remove(self, ctx: commands.Context, *channels: discord.TextChannel) -> None: async def antipolls_channels_remove(self, ctx: commands.Context, *channels: discord.TextChannel) -> None:
"""Remove channels from the whitelist.""" """Remove channels from the whitelist."""
assert ctx.guild is not None
async with self.config.guild(ctx.guild).channel_whitelist() as channel_whitelist: async with self.config.guild(ctx.guild).channel_whitelist() as channel_whitelist:
channel_whitelist: list channel_whitelist: list
failed: list[discord.TextChannel] = [] failed: list[discord.TextChannel] = []
@ -172,21 +166,16 @@ class AntiPolls(commands.Cog):
await ctx.send(f"The following channels were not in the whitelist: {humanize_list([channel.mention for channel in failed])}", delete_after=10) await ctx.send(f"The following channels were not in the whitelist: {humanize_list([channel.mention for channel in failed])}", delete_after=10)
@antipolls_channels.command(name="list") @antipolls_channels.command(name="list")
async def antipolls_channels_list(self, ctx: commands.Context) -> discord.Message: async def antipolls_channels_list(self, ctx: commands.Context) -> None:
"""List channels in the whitelist.""" """List channels in the whitelist."""
assert ctx.guild is not None
channel_whitelist = await self.config.guild(ctx.guild).channel_whitelist() channel_whitelist = await self.config.guild(ctx.guild).channel_whitelist()
if not channel_whitelist: if not channel_whitelist:
return await ctx.send("No channels in the whitelist.") return await ctx.send("No channels in the whitelist.")
channels = [channel for channel in (ctx.guild.get_channel(channel) for channel in channel_whitelist) if channel is not None] channels = [ctx.guild.get_channel(channel) for channel in channel_whitelist]
for c in channels: await ctx.send(humanize_list([channel.mention for channel in channels]))
if not c:
channels.remove(c)
return await ctx.send(humanize_list([channel.mention for channel in channels]))
@antipolls.command(name="managemessages") @antipolls.command(name="managemessages")
async def antipolls_managemessages(self, ctx: commands.Context, enabled: bool) -> None: async def antipolls_managemessages(self, ctx: commands.Context, enabled: bool) -> None:
"""Toggle Manage Messages permission check.""" """Toggle Manage Messages permission check."""
assert ctx.guild is not None
await self.config.guild(ctx.guild).manage_messages.set(enabled) await self.config.guild(ctx.guild).manage_messages.set(enabled)
await ctx.tick() await ctx.tick()

View file

@ -1,14 +1,17 @@
{ {
"$schema": "https://raw.githubusercontent.com/Cog-Creators/Red-DiscordBot/refs/heads/V3/develop/schema/red_cog_repo.schema.json", "author" : ["cswimr"],
"author": ["cswimr"], "install_msg" : "Thank you for installing AntiPolls!\nYou can find the source code of this cog [here](https://coastalcommits.com/cswimr/SeaCogs).",
"install_msg": "Thank you for installing AntiPolls!\nYou can find the source code of this cog [here](https://coastalcommits.com/cswimr/SeaCogs).", "name" : "AntiPolls",
"name": "AntiPolls", "short" : "AntiPolls deletes messages that contain polls.",
"short": "AntiPolls deletes messages that contain polls.", "description" : "AntiPolls deletes messages that contain polls, with a configurable per-guild role and channel whitelist and support for default Discord permissions (Manage Messages).",
"description": "AntiPolls deletes messages that contain polls, with a configurable per-guild role and channel whitelist and support for default Discord permissions (Manage Messages).", "end_user_data_statement" : "This cog does not store any user data.",
"end_user_data_statement": "This cog does not store any user data.",
"hidden": true, "hidden": true,
"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],
"tags": ["automod", "automoderation", "polls"] "tags": [
"automod",
"automoderation",
"polls"
]
} }

View file

@ -40,7 +40,7 @@ class Aurora(commands.Cog):
This cog stores all of its data in an SQLite database.""" This cog stores all of its data in an SQLite database."""
__author__ = ["cswimr"] __author__ = ["cswimr"]
__version__ = "2.1.5" __version__ = "2.1.3"
__documentation__ = "https://seacogs.coastalcommits.com/aurora/" __documentation__ = "https://seacogs.coastalcommits.com/aurora/"
async def red_delete_data_for_user(self, *, requester, user_id: int): async def red_delete_data_for_user(self, *, requester, user_id: int):
@ -70,8 +70,7 @@ class Aurora(commands.Cog):
await config.user_from_id(user_id).clear() await config.user_from_id(user_id).clear()
else: else:
logger.warning( logger.warning(
"Invalid requester passed to red_delete_data_for_user: %s", "Invalid requester passed to red_delete_data_for_user: %s", requester
requester,
) )
def __init__(self, bot: Red): def __init__(self, bot: Red):
@ -136,8 +135,9 @@ class Aurora(commands.Cog):
if await config.guild(entry.guild).ignore_other_bots() is True: if await config.guild(entry.guild).ignore_other_bots() is True:
if entry.user.bot or entry.target.bot: if entry.user.bot or entry.target.bot:
return return
elif entry.user.id == self.bot.user.id: else:
return if entry.user.id == self.bot.user.id:
return
duration = "NULL" duration = "NULL"
@ -159,10 +159,10 @@ class Aurora(commands.Cog):
elif entry.action == discord.AuditLogAction.member_update: elif entry.action == discord.AuditLogAction.member_update:
if entry.after.timed_out_until is not None: if entry.after.timed_out_until is not None:
timed_out_until_aware = entry.after.timed_out_until.replace( timed_out_until_aware = entry.after.timed_out_until.replace(
tzinfo=timezone.utc, tzinfo=timezone.utc
) )
duration_datetime = timed_out_until_aware - datetime.now( duration_datetime = timed_out_until_aware - datetime.now(
tz=timezone.utc, tz=timezone.utc
) )
minutes = round(duration_datetime.total_seconds() / 60) minutes = round(duration_datetime.total_seconds() / 60)
duration = timedelta(minutes=minutes) duration = timedelta(minutes=minutes)
@ -209,7 +209,7 @@ class Aurora(commands.Cog):
return return
await interaction.response.send_message( await interaction.response.send_message(
content=f"{target.mention} has recieved a note!\n**Reason** - `{reason}`", content=f"{target.mention} has recieved a note!\n**Reason** - `{reason}`"
) )
if silent is None: if silent is None:
@ -239,7 +239,7 @@ class Aurora(commands.Cog):
reason, reason,
) )
await interaction.edit_original_response( await interaction.edit_original_response(
content=f"{target.mention} has received a note! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`", content=f"{target.mention} has received a note! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`"
) )
await log(interaction, moderation_id) await log(interaction, moderation_id)
@ -268,7 +268,7 @@ class Aurora(commands.Cog):
return return
await interaction.response.send_message( await interaction.response.send_message(
content=f"{target.mention} has been warned!\n**Reason** - `{reason}`", content=f"{target.mention} has been warned!\n**Reason** - `{reason}`"
) )
if silent is None: if silent is None:
@ -298,7 +298,7 @@ class Aurora(commands.Cog):
reason, reason,
) )
await interaction.edit_original_response( await interaction.edit_original_response(
content=f"{target.mention} has been warned! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`", content=f"{target.mention} has been warned! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`"
) )
await log(interaction, moderation_id) await log(interaction, moderation_id)
@ -342,8 +342,7 @@ class Aurora(commands.Cog):
parsed_time = parse_timedelta(duration) parsed_time = parse_timedelta(duration)
if parsed_time is None: if parsed_time is None:
await interaction.response.send_message( await interaction.response.send_message(
content=error("Please provide a valid duration!"), content=error("Please provide a valid duration!"), ephemeral=True
ephemeral=True,
) )
return return
else: else:
@ -351,15 +350,12 @@ class Aurora(commands.Cog):
if role.id not in addrole_whitelist: if role.id not in addrole_whitelist:
await interaction.response.send_message( await interaction.response.send_message(
content=error("That role isn't whitelisted!"), content=error("That role isn't whitelisted!"), ephemeral=True
ephemeral=True,
) )
return return
if not await check_moddable( if not await check_moddable(
target, target, interaction, ["moderate_members", "manage_roles"]
interaction,
["moderate_members", "manage_roles"],
): ):
return return
@ -394,7 +390,7 @@ class Aurora(commands.Cog):
reason=f"Role added by {interaction.user.id}{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''} for: {reason}", reason=f"Role added by {interaction.user.id}{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''} for: {reason}",
) )
response: discord.WebhookMessage = await interaction.followup.send( response: discord.WebhookMessage = await interaction.followup.send(
content=f"{target.mention} has been given the {role.mention} role{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''}!\n**Reason** - `{reason}`", content=f"{target.mention} has been given the {role.mention} role{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''}!\n**Reason** - `{reason}`"
) )
moderation_id = await mysql_log( moderation_id = await mysql_log(
@ -452,8 +448,7 @@ class Aurora(commands.Cog):
parsed_time = parse_timedelta(duration) parsed_time = parse_timedelta(duration)
if parsed_time is None: if parsed_time is None:
await interaction.response.send_message( await interaction.response.send_message(
content=error("Please provide a valid duration!"), content=error("Please provide a valid duration!"), ephemeral=True
ephemeral=True,
) )
return return
else: else:
@ -461,15 +456,12 @@ class Aurora(commands.Cog):
if role.id not in addrole_whitelist: if role.id not in addrole_whitelist:
await interaction.response.send_message( await interaction.response.send_message(
content=error("That role isn't whitelisted!"), content=error("That role isn't whitelisted!"), ephemeral=True
ephemeral=True,
) )
return return
if not await check_moddable( if not await check_moddable(
target, target, interaction, ["moderate_members", "manage_roles"]
interaction,
["moderate_members", "manage_roles"],
): ):
return return
@ -504,7 +496,7 @@ class Aurora(commands.Cog):
reason=f"Role removed by {interaction.user.id}{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''} for: {reason}", reason=f"Role removed by {interaction.user.id}{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''} for: {reason}",
) )
response: discord.WebhookMessage = await interaction.followup.send( response: discord.WebhookMessage = await interaction.followup.send(
content=f"{target.mention} has had the {role.mention} role removed{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''}!\n**Reason** - `{reason}`", content=f"{target.mention} has had the {role.mention} role removed{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''}!\n**Reason** - `{reason}`"
) )
moderation_id = await mysql_log( moderation_id = await mysql_log(
@ -561,24 +553,21 @@ class Aurora(commands.Cog):
parsed_time = parse_timedelta(duration, maximum=timedelta(days=28)) parsed_time = parse_timedelta(duration, maximum=timedelta(days=28))
if parsed_time is None: if parsed_time is None:
await interaction.response.send_message( await interaction.response.send_message(
error("Please provide a valid duration!"), error("Please provide a valid duration!"), ephemeral=True
ephemeral=True,
) )
return return
except commands.BadArgument: except commands.BadArgument:
await interaction.response.send_message( await interaction.response.send_message(
error("Please provide a duration that is less than 28 days."), error("Please provide a duration that is less than 28 days."), ephemeral=True
ephemeral=True,
) )
return return
await target.timeout( await target.timeout(
parsed_time, parsed_time, reason=f"Muted by {interaction.user.id} for: {reason}"
reason=f"Muted by {interaction.user.id} for: {reason}",
) )
await interaction.response.send_message( await interaction.response.send_message(
content=f"{target.mention} has been muted for {humanize_timedelta(timedelta=parsed_time)}!\n**Reason** - `{reason}`", content=f"{target.mention} has been muted for {humanize_timedelta(timedelta=parsed_time)}!\n**Reason** - `{reason}`"
) )
if silent is None: if silent is None:
@ -609,7 +598,7 @@ class Aurora(commands.Cog):
reason, reason,
) )
await interaction.edit_original_response( await interaction.edit_original_response(
content=f"{target.mention} has been muted for {humanize_timedelta(timedelta=parsed_time)}! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`", content=f"{target.mention} has been muted for {humanize_timedelta(timedelta=parsed_time)}! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`"
) )
await log(interaction, moderation_id) await log(interaction, moderation_id)
@ -647,15 +636,14 @@ class Aurora(commands.Cog):
if reason: if reason:
await target.timeout( await target.timeout(
None, None, reason=f"Unmuted by {interaction.user.id} for: {reason}"
reason=f"Unmuted by {interaction.user.id} for: {reason}",
) )
else: else:
await target.timeout(None, reason=f"Unbanned by {interaction.user.id}") await target.timeout(None, reason=f"Unbanned by {interaction.user.id}")
reason = "No reason given." reason = "No reason given."
await interaction.response.send_message( await interaction.response.send_message(
content=f"{target.mention} has been unmuted!\n**Reason** - `{reason}`", content=f"{target.mention} has been unmuted!\n**Reason** - `{reason}`"
) )
if silent is None: if silent is None:
@ -685,7 +673,7 @@ class Aurora(commands.Cog):
reason, reason,
) )
await interaction.edit_original_response( await interaction.edit_original_response(
content=f"{target.mention} has been unmuted! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`", content=f"{target.mention} has been unmuted! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`"
) )
await log(interaction, moderation_id) await log(interaction, moderation_id)
@ -714,7 +702,7 @@ class Aurora(commands.Cog):
return return
await interaction.response.send_message( await interaction.response.send_message(
content=f"{target.mention} has been kicked!\n**Reason** - `{reason}`", content=f"{target.mention} has been kicked!\n**Reason** - `{reason}`"
) )
if silent is None: if silent is None:
@ -746,7 +734,7 @@ class Aurora(commands.Cog):
reason, reason,
) )
await interaction.edit_original_response( await interaction.edit_original_response(
content=f"{target.mention} has been kicked! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`", content=f"{target.mention} has been kicked! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`"
) )
await log(interaction, moderation_id) await log(interaction, moderation_id)
@ -762,7 +750,7 @@ class Aurora(commands.Cog):
Choice(name="1 Day", value=86400), Choice(name="1 Day", value=86400),
Choice(name="3 Days", value=259200), Choice(name="3 Days", value=259200),
Choice(name="7 Days", value=604800), Choice(name="7 Days", value=604800),
], ]
) )
async def ban( async def ban(
self, self,
@ -798,8 +786,7 @@ class Aurora(commands.Cog):
try: try:
await interaction.guild.fetch_ban(target) await interaction.guild.fetch_ban(target)
await interaction.response.send_message( await interaction.response.send_message(
content=error(f"{target.mention} is already banned!"), content=error(f"{target.mention} is already banned!"), ephemeral=True
ephemeral=True,
) )
return return
except discord.errors.NotFound: except discord.errors.NotFound:
@ -809,21 +796,19 @@ class Aurora(commands.Cog):
parsed_time = parse_relativedelta(duration) parsed_time = parse_relativedelta(duration)
if parsed_time is None: if parsed_time is None:
await interaction.response.send_message( await interaction.response.send_message(
content=error("Please provide a valid duration!"), content=error("Please provide a valid duration!"), ephemeral=True
ephemeral=True,
) )
return return
try: try:
parsed_time = timedelta_from_relativedelta(parsed_time) parsed_time = timedelta_from_relativedelta(parsed_time)
except ValueError: except ValueError:
await interaction.response.send_message( await interaction.response.send_message(
content=error("Please provide a valid duration!"), content=error("Please provide a valid duration!"), ephemeral=True
ephemeral=True,
) )
return return
await interaction.response.send_message( await interaction.response.send_message(
content=f"{target.mention} has been banned for {humanize_timedelta(timedelta=parsed_time)}!\n**Reason** - `{reason}`", content=f"{target.mention} has been banned for {humanize_timedelta(timedelta=parsed_time)}!\n**Reason** - `{reason}`"
) )
try: try:
@ -857,7 +842,7 @@ class Aurora(commands.Cog):
reason, reason,
) )
await interaction.edit_original_response( await interaction.edit_original_response(
content=f"{target.mention} has been banned for {humanize_timedelta(timedelta=parsed_time)}! (Case `#{moderation_id}`)\n**Reason** - `{reason}`", content=f"{target.mention} has been banned for {humanize_timedelta(timedelta=parsed_time)}! (Case `#{moderation_id}`)\n**Reason** - `{reason}`"
) )
await log(interaction, moderation_id) await log(interaction, moderation_id)
@ -865,14 +850,14 @@ class Aurora(commands.Cog):
await send_evidenceformat(interaction, case) await send_evidenceformat(interaction, case)
else: else:
await interaction.response.send_message( await interaction.response.send_message(
content=f"{target.mention} has been banned!\n**Reason** - `{reason}`", content=f"{target.mention} has been banned!\n**Reason** - `{reason}`"
) )
if silent is None: if silent is None:
silent = not await config.guild(interaction.guild).dm_users() silent = not await config.guild(interaction.guild).dm_users()
if silent is False: if silent is False:
try: try:
embed = await message_factory( embed = embed = await message_factory(
await self.bot.get_embed_color(interaction.channel), await self.bot.get_embed_color(interaction.channel),
guild=interaction.guild, guild=interaction.guild,
moderator=interaction.user, moderator=interaction.user,
@ -901,7 +886,7 @@ class Aurora(commands.Cog):
reason, reason,
) )
await interaction.edit_original_response( await interaction.edit_original_response(
content=f"{target.mention} has been banned! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`", content=f"{target.mention} has been banned! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`"
) )
await log(interaction, moderation_id) await log(interaction, moderation_id)
@ -933,25 +918,22 @@ class Aurora(commands.Cog):
await interaction.guild.fetch_ban(target) await interaction.guild.fetch_ban(target)
except discord.errors.NotFound: except discord.errors.NotFound:
await interaction.response.send_message( await interaction.response.send_message(
content=error(f"{target.mention} is not banned!"), content=error(f"{target.mention} is not banned!"), ephemeral=True
ephemeral=True,
) )
return return
if reason: if reason:
await interaction.guild.unban( await interaction.guild.unban(
target, target, reason=f"Unbanned by {interaction.user.id} for: {reason}"
reason=f"Unbanned by {interaction.user.id} for: {reason}",
) )
else: else:
await interaction.guild.unban( await interaction.guild.unban(
target, target, reason=f"Unbanned by {interaction.user.id}"
reason=f"Unbanned by {interaction.user.id}",
) )
reason = "No reason given." reason = "No reason given."
await interaction.response.send_message( await interaction.response.send_message(
content=f"{target.mention} has been unbanned!\n**Reason** - `{reason}`", content=f"{target.mention} has been unbanned!\n**Reason** - `{reason}`"
) )
if silent is None: if silent is None:
@ -981,7 +963,7 @@ class Aurora(commands.Cog):
reason, reason,
) )
await interaction.edit_original_response( await interaction.edit_original_response(
content=f"{target.mention} has been unbanned! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`", content=f"{target.mention} has been unbanned! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`"
) )
await log(interaction, moderation_id) await log(interaction, moderation_id)
@ -1019,28 +1001,42 @@ class Aurora(commands.Cog):
export: bool export: bool
Exports the server's entire moderation history to a JSON file""" Exports the server's entire moderation history to a JSON file"""
if ephemeral is None: if ephemeral is None:
ephemeral = await config.user(interaction.user).history_ephemeral() or await config.guild(interaction.guild).history_ephemeral() or False ephemeral = (
await config.user(interaction.user).history_ephemeral()
or await config.guild(interaction.guild).history_ephemeral()
or False
)
if inline is None: if inline is None:
inline = await config.user(interaction.user).history_inline() or await config.guild(interaction.guild).history_inline() or False inline = (
await config.user(interaction.user).history_inline()
or await config.guild(interaction.guild).history_inline()
or False
)
if pagesize is None: if pagesize is None:
if inline is True: if inline is True:
pagesize = await config.user(interaction.user).history_inline_pagesize() or await config.guild(interaction.guild).history_inline_pagesize() or 6 pagesize = (
await config.user(interaction.user).history_inline_pagesize()
or await config.guild(interaction.guild).history_inline_pagesize()
or 6
)
else: else:
pagesize = await config.user(interaction.user).history_pagesize() or await config.guild(interaction.guild).history_pagesize() or 5 pagesize = (
await config.user(interaction.user).history_pagesize()
or await config.guild(interaction.guild).history_pagesize()
or 5
)
await interaction.response.defer(ephemeral=ephemeral) await interaction.response.defer(ephemeral=ephemeral)
permissions = check_permissions( permissions = check_permissions(
interaction.client.user, interaction.client.user, ["embed_links"], interaction
["embed_links"],
interaction,
) )
if permissions: if permissions:
await interaction.followup.send( await interaction.followup.send(
error( error(
f"I do not have the `{permissions}` permission, required for this action.", f"I do not have the `{permissions}` permission, required for this action."
), ),
ephemeral=True, ephemeral=True,
) )
@ -1065,15 +1061,18 @@ class Aurora(commands.Cog):
cases.append(case) cases.append(case)
try: try:
filename = str(data_manager.cog_data_path(cog_instance=self)) + str(os.sep) + f"moderation_{interaction.guild.id}.json" filename = (
str(data_manager.cog_data_path(cog_instance=self))
+ str(os.sep)
+ f"moderation_{interaction.guild.id}.json"
)
with open(filename, "w", encoding="utf-8") as f: with open(filename, "w", encoding="utf-8") as f:
json.dump(cases, f, indent=2) json.dump(cases, f, indent=2)
await interaction.followup.send( await interaction.followup.send(
file=discord.File( file=discord.File(
filename, filename, f"moderation_{interaction.guild.id}.json"
f"moderation_{interaction.guild.id}.json",
), ),
ephemeral=ephemeral, ephemeral=ephemeral,
) )
@ -1082,7 +1081,7 @@ class Aurora(commands.Cog):
except json.JSONDecodeError as e: except json.JSONDecodeError as e:
await interaction.followup.send( await interaction.followup.send(
content=error( content=error(
"An error occured while exporting the moderation history.\nError:\n", "An error occured while exporting the moderation history.\nError:\n"
) )
+ box(e, "py"), + box(e, "py"),
ephemeral=ephemeral, ephemeral=ephemeral,
@ -1128,7 +1127,7 @@ class Aurora(commands.Cog):
embed = discord.Embed(color=await self.bot.get_embed_color(interaction.channel)) embed = discord.Embed(color=await self.bot.get_embed_color(interaction.channel))
embed.set_author(icon_url=interaction.guild.icon.url, name="Infraction History") embed.set_author(icon_url=interaction.guild.icon.url, name="Infraction History")
embed.set_footer( embed.set_footer(
text=f"Page {page:,}/{page_quantity:,} | {case_quantity:,} Results", text=f"Page {page:,}/{page_quantity:,} | {case_quantity:,} Results"
) )
memory_dict = {} memory_dict = {}
@ -1137,30 +1136,33 @@ class Aurora(commands.Cog):
if case["target_id"] not in memory_dict: if case["target_id"] not in memory_dict:
if case["target_type"] == "USER": if case["target_type"] == "USER":
memory_dict[str(case["target_id"])] = await fetch_user_dict( memory_dict[str(case["target_id"])] = await fetch_user_dict(
interaction.client, interaction.client, case["target_id"]
case["target_id"],
) )
elif case["target_type"] == "CHANNEL": elif case["target_type"] == "CHANNEL":
memory_dict[str(case["target_id"])] = await fetch_channel_dict( memory_dict[str(case["target_id"])] = await fetch_channel_dict(
interaction.guild, interaction.guild, case["target_id"]
case["target_id"],
) )
target_user = memory_dict[str(case["target_id"])] target_user = memory_dict[str(case["target_id"])]
if case["target_type"] == "USER": if case["target_type"] == "USER":
target_name = f"`{target_user['name']}`" if target_user["discriminator"] == "0" else f"`{target_user['name']}#{target_user['discriminator']}`" target_name = (
f"`{target_user['name']}`"
if target_user["discriminator"] == "0"
else f"`{target_user['name']}#{target_user['discriminator']}`"
)
elif case["target_type"] == "CHANNEL": elif case["target_type"] == "CHANNEL":
target_name = f"`{target_user['mention']}`" target_name = f"`{target_user['mention']}`"
else:
target_name = ""
if case["moderator_id"] not in memory_dict: if case["moderator_id"] not in memory_dict:
memory_dict[str(case["moderator_id"])] = await fetch_user_dict( memory_dict[str(case["moderator_id"])] = await fetch_user_dict(
interaction.client, interaction.client, case["moderator_id"]
case["moderator_id"],
) )
moderator_user = memory_dict[str(case["moderator_id"])] moderator_user = memory_dict[str(case["moderator_id"])]
moderator_name = f"`{moderator_user['name']}`" if moderator_user["discriminator"] == "0" else f"`{moderator_user['name']}#{moderator_user['discriminator']}`" moderator_name = (
f"`{moderator_user['name']}`"
if moderator_user["discriminator"] == "0"
else f"`{moderator_user['name']}#{moderator_user['discriminator']}`"
)
field_name = f"Case #{case['moderation_id']:,} ({str.title(case['moderation_type'])})" field_name = f"Case #{case['moderation_id']:,} ({str.title(case['moderation_type'])})"
field_value = f"**Target:** {target_name} ({target_user['id']})\n**Moderator:** {moderator_name} ({moderator_user['id']})" field_value = f"**Target:** {target_name} ({target_user['id']})\n**Moderator:** {moderator_name} ({moderator_user['id']})"
@ -1175,15 +1177,20 @@ class Aurora(commands.Cog):
**{ **{
unit: int(val) unit: int(val)
for unit, val in zip( for unit, val in zip(
["hours", "minutes", "seconds"], ["hours", "minutes", "seconds"], case["duration"].split(":")
case["duration"].split(":"),
) )
}, }
)
duration_embed = (
f"{humanize_timedelta(timedelta=td)} | <t:{case['end_timestamp']}:R>"
if bool(case["expired"]) is False
else f"{humanize_timedelta(timedelta=td)} | Expired"
) )
duration_embed = f"{humanize_timedelta(timedelta=td)} | <t:{case['end_timestamp']}:R>" if bool(case["expired"]) is False else f"{humanize_timedelta(timedelta=td)} | Expired"
field_value += f"\n**Duration:** {duration_embed}" field_value += f"\n**Duration:** {duration_embed}"
field_value += f"\n**Timestamp:** <t:{case['timestamp']}> | <t:{case['timestamp']}:R>" field_value += (
f"\n**Timestamp:** <t:{case['timestamp']}> | <t:{case['timestamp']}:R>"
)
if case["role_id"] != "0": if case["role_id"] != "0":
role = interaction.guild.get_role(int(case["role_id"])) role = interaction.guild.get_role(int(case["role_id"]))
@ -1201,10 +1208,7 @@ class Aurora(commands.Cog):
@app_commands.command(name="resolve") @app_commands.command(name="resolve")
async def resolve( async def resolve(
self, self, interaction: discord.Interaction, case: int, reason: str = None
interaction: discord.Interaction,
case: int,
reason: str = None,
): ):
"""Resolve a specific case. """Resolve a specific case.
@ -1222,7 +1226,7 @@ class Aurora(commands.Cog):
if permissions: if permissions:
await interaction.response.send_message( await interaction.response.send_message(
error( error(
f"I do not have the `{permissions}` permission, required for this action.", f"I do not have the `{permissions}` permission, required for this action."
), ),
ephemeral=True, ephemeral=True,
) )
@ -1231,7 +1235,9 @@ class Aurora(commands.Cog):
database = connect() database = connect()
cursor = database.cursor() cursor = database.cursor()
query_1 = f"SELECT * FROM moderation_{interaction.guild.id} WHERE moderation_id = ?;" query_1 = (
f"SELECT * FROM moderation_{interaction.guild.id} WHERE moderation_id = ?;"
)
cursor.execute(query_1, (case,)) cursor.execute(query_1, (case,))
result_1 = cursor.fetchone() result_1 = cursor.fetchone()
if result_1 is None or case == 0: if result_1 is None or case == 0:
@ -1247,7 +1253,7 @@ class Aurora(commands.Cog):
if result_2 is None: if result_2 is None:
await interaction.response.send_message( await interaction.response.send_message(
content=error( content=error(
f"This moderation has already been resolved!\nUse `/case {case}` for more information.", f"This moderation has already been resolved!\nUse `/case {case}` for more information."
), ),
ephemeral=True, ephemeral=True,
) )
@ -1261,7 +1267,7 @@ class Aurora(commands.Cog):
if len(changes) > 25: if len(changes) > 25:
await interaction.response.send_message( await interaction.response.send_message(
content=error( content=error(
"Due to limitations with Discord's embed system, you cannot edit a case more than 25 times.", "Due to limitations with Discord's embed system, you cannot edit a case more than 25 times."
), ),
ephemeral=True, ephemeral=True,
) )
@ -1273,7 +1279,7 @@ class Aurora(commands.Cog):
"timestamp": case_dict["timestamp"], "timestamp": case_dict["timestamp"],
"reason": case_dict["reason"], "reason": case_dict["reason"],
"user_id": case_dict["moderator_id"], "user_id": case_dict["moderator_id"],
}, }
) )
changes.append( changes.append(
{ {
@ -1281,7 +1287,7 @@ class Aurora(commands.Cog):
"timestamp": int(time.time()), "timestamp": int(time.time()),
"reason": reason, "reason": reason,
"user_id": interaction.user.id, "user_id": interaction.user.id,
}, }
) )
if case_dict["moderation_type"] in ["UNMUTE", "UNBAN"]: if case_dict["moderation_type"] in ["UNMUTE", "UNBAN"]:
@ -1295,12 +1301,11 @@ class Aurora(commands.Cog):
if case_dict["moderation_type"] == "MUTE": if case_dict["moderation_type"] == "MUTE":
try: try:
member = await interaction.guild.fetch_member( member = await interaction.guild.fetch_member(
case_dict["target_id"], case_dict["target_id"]
) )
await member.timeout( await member.timeout(
None, None, reason=f"Case #{case:,} resolved by {interaction.user.id}"
reason=f"Case #{case:,} resolved by {interaction.user.id}",
) )
except discord.NotFound: except discord.NotFound:
pass pass
@ -1310,8 +1315,7 @@ class Aurora(commands.Cog):
user = await interaction.client.fetch_user(case_dict["target_id"]) user = await interaction.client.fetch_user(case_dict["target_id"])
await interaction.guild.unban( await interaction.guild.unban(
user, user, reason=f"Case #{case} resolved by {interaction.user.id}"
reason=f"Case #{case} resolved by {interaction.user.id}",
) )
except discord.NotFound: except discord.NotFound:
pass pass
@ -1336,8 +1340,7 @@ class Aurora(commands.Cog):
case_dict=await fetch_case(case, interaction.guild.id), case_dict=await fetch_case(case, interaction.guild.id),
) )
await interaction.response.send_message( await interaction.response.send_message(
content=f"✅ Moderation #{case:,} resolved!", content=f"✅ Moderation #{case:,} resolved!", embed=embed
embed=embed,
) )
await log(interaction, case, resolved=True) await log(interaction, case, resolved=True)
@ -1349,7 +1352,7 @@ class Aurora(commands.Cog):
export=[ export=[
Choice(name="Export as File", value="file"), Choice(name="Export as File", value="file"),
Choice(name="Export as Codeblock", value="codeblock"), Choice(name="Export as Codeblock", value="codeblock"),
], ]
) )
async def case( async def case(
self, self,
@ -1373,35 +1376,41 @@ class Aurora(commands.Cog):
export: bool export: bool
Export the case to a JSON file or codeblock""" Export the case to a JSON file or codeblock"""
permissions = check_permissions( permissions = check_permissions(
interaction.client.user, interaction.client.user, ["embed_links"], interaction
["embed_links"],
interaction,
) )
if permissions: if permissions:
await interaction.response.send_message( await interaction.response.send_message(
error( error(
f"I do not have the `{permissions}` permission, required for this action.", f"I do not have the `{permissions}` permission, required for this action."
), ),
ephemeral=True, ephemeral=True,
) )
return return
if ephemeral is None: if ephemeral is None:
ephemeral = await config.user(interaction.user).history_ephemeral() or await config.guild(interaction.guild).history_ephemeral() or False ephemeral = (
await config.user(interaction.user).history_ephemeral()
or await config.guild(interaction.guild).history_ephemeral()
or False
)
if case != 0: if case != 0:
case_dict = await fetch_case(case, interaction.guild.id) case_dict = await fetch_case(case, interaction.guild.id)
if case_dict: if case_dict:
if export: if export:
if export.value == "file" or len(str(case_dict)) > 1800: if export.value == "file" or len(str(case_dict)) > 1800:
filename = str(data_manager.cog_data_path(cog_instance=self)) + str(os.sep) + f"moderation_{interaction.guild.id}_case_{case}.json" filename = (
str(data_manager.cog_data_path(cog_instance=self))
+ str(os.sep)
+ f"moderation_{interaction.guild.id}_case_{case}.json"
)
with open(filename, "w", encoding="utf-8") as f: with open(filename, "w", encoding="utf-8") as f:
json.dump(case_dict, f, indent=2) json.dump(case_dict, f, indent=2)
if export.value == "codeblock": if export.value == "codeblock":
content = f"Case #{case:,} exported.\n" + warning( content = f"Case #{case:,} exported.\n" + warning(
"Case was too large to export as codeblock, so it has been uploaded as a `.json` file.", "Case was too large to export as codeblock, so it has been uploaded as a `.json` file."
) )
else: else:
content = f"Case #{case:,} exported." content = f"Case #{case:,} exported."
@ -1418,41 +1427,34 @@ class Aurora(commands.Cog):
os.remove(filename) os.remove(filename)
return return
await interaction.response.send_message( await interaction.response.send_message(
content=box(json.dumps(case_dict, indent=2), "json"), content=box(json.dumps(case_dict, indent=2), 'json'),
ephemeral=ephemeral, ephemeral=ephemeral,
) )
return return
if changes: if changes:
embed = await changes_factory( embed = await changes_factory(
interaction=interaction, interaction=interaction, case_dict=case_dict
case_dict=case_dict,
) )
await interaction.response.send_message( await interaction.response.send_message(
embed=embed, embed=embed, ephemeral=ephemeral
ephemeral=ephemeral,
) )
elif evidenceformat: elif evidenceformat:
content = await evidenceformat_factory( content = await evidenceformat_factory(
interaction=interaction, interaction=interaction, case_dict=case_dict
case_dict=case_dict,
) )
await interaction.response.send_message( await interaction.response.send_message(
content=content, content=content, ephemeral=ephemeral
ephemeral=ephemeral,
) )
else: else:
embed = await case_factory( embed = await case_factory(
interaction=interaction, interaction=interaction, case_dict=case_dict
case_dict=case_dict,
) )
await interaction.response.send_message( await interaction.response.send_message(
embed=embed, embed=embed, ephemeral=ephemeral
ephemeral=ephemeral,
) )
return return
await interaction.response.send_message( await interaction.response.send_message(
content=f"No case with case number `{case}` found.", content=f"No case with case number `{case}` found.", ephemeral=True
ephemeral=True,
) )
@app_commands.command(name="edit") @app_commands.command(name="edit")
@ -1474,16 +1476,13 @@ class Aurora(commands.Cog):
duration: str duration: str
What is the new duration? Does not reapply the moderation if it has already expired. What is the new duration? Does not reapply the moderation if it has already expired.
""" """
end_timestamp = None
permissions = check_permissions( permissions = check_permissions(
interaction.client.user, interaction.client.user, ["embed_links"], interaction
["embed_links"],
interaction,
) )
if permissions: if permissions:
await interaction.response.send_message( await interaction.response.send_message(
error( error(
f"I do not have the `{permissions}` permission, required for this action.", f"I do not have the `{permissions}` permission, required for this action."
), ),
ephemeral=True, ephemeral=True,
) )
@ -1497,25 +1496,26 @@ class Aurora(commands.Cog):
parsed_time = parse_timedelta(duration) parsed_time = parse_timedelta(duration)
if parsed_time is None: if parsed_time is None:
await interaction.response.send_message( await interaction.response.send_message(
error("Please provide a valid duration!"), error("Please provide a valid duration!"), ephemeral=True
ephemeral=True,
) )
return return
end_timestamp = case_dict["timestamp"] + parsed_time.total_seconds() end_timestamp = case_dict["timestamp"] + parsed_time.total_seconds()
if case_dict["moderation_type"] == "MUTE": if case_dict["moderation_type"] == "MUTE":
if (time.time() - case_dict["timestamp"]) + parsed_time.total_seconds() > 2419200: if (
time.time() - case_dict["timestamp"]
) + parsed_time.total_seconds() > 2419200:
await interaction.response.send_message( await interaction.response.send_message(
error( error(
"Please provide a duration that is less than 28 days from the initial moderation.", "Please provide a duration that is less than 28 days from the initial moderation."
), )
) )
return return
try: try:
member = await interaction.guild.fetch_member( member = await interaction.guild.fetch_member(
case_dict["target_id"], case_dict["target_id"]
) )
await member.timeout( await member.timeout(
@ -1529,7 +1529,7 @@ class Aurora(commands.Cog):
if len(changes) > 25: if len(changes) > 25:
await interaction.response.send_message( await interaction.response.send_message(
content=error( content=error(
"Due to limitations with Discord's embed system, you cannot edit a case more than 25 times.", "Due to limitations with Discord's embed system, you cannot edit a case more than 25 times."
), ),
ephemeral=True, ephemeral=True,
) )
@ -1543,10 +1543,9 @@ class Aurora(commands.Cog):
"user_id": case_dict["moderator_id"], "user_id": case_dict["moderator_id"],
"duration": case_dict["duration"], "duration": case_dict["duration"],
"end_timestamp": case_dict["end_timestamp"], "end_timestamp": case_dict["end_timestamp"],
}, }
) )
if parsed_time: if parsed_time:
assert end_timestamp is not None
changes.append( changes.append(
{ {
"type": "EDIT", "type": "EDIT",
@ -1555,7 +1554,7 @@ class Aurora(commands.Cog):
"user_id": interaction.user.id, "user_id": interaction.user.id,
"duration": convert_timedelta_to_str(parsed_time), "duration": convert_timedelta_to_str(parsed_time),
"end_timestamp": end_timestamp, "end_timestamp": end_timestamp,
}, }
) )
else: else:
changes.append( changes.append(
@ -1566,7 +1565,7 @@ class Aurora(commands.Cog):
"user_id": interaction.user.id, "user_id": interaction.user.id,
"duration": case_dict["duration"], "duration": case_dict["duration"],
"end_timestamp": case_dict["end_timestamp"], "end_timestamp": case_dict["end_timestamp"],
}, }
) )
database = connect() database = connect()
@ -1603,8 +1602,7 @@ class Aurora(commands.Cog):
database.close() database.close()
return return
await interaction.response.send_message( await interaction.response.send_message(
content=error(f"No case with case number `{case}` found."), content=error(f"No case with case number `{case}` found."), ephemeral=True
ephemeral=True,
) )
@tasks.loop(minutes=1) @tasks.loop(minutes=1)
@ -1636,11 +1634,14 @@ class Aurora(commands.Cog):
unban_num = 0 unban_num = 0
for target_id, moderation_id in zip(target_ids, moderation_ids): for target_id, moderation_id in zip(target_ids, moderation_ids):
user: discord.User = await self.bot.fetch_user(target_id) user: discord.User = await self.bot.fetch_user(target_id)
name = f"{user.name}#{user.discriminator}" if user.discriminator != "0" else user.name name = (
f"{user.name}#{user.discriminator}"
if user.discriminator != "0"
else user.name
)
try: try:
await guild.unban( await guild.unban(
user, user, reason=f"Automatic unban from case #{moderation_id}"
reason=f"Automatic unban from case #{moderation_id}",
) )
embed = await message_factory( embed = await message_factory(
@ -1689,16 +1690,13 @@ class Aurora(commands.Cog):
role_ids = [row[2] for row in result] role_ids = [row[2] for row in result]
for target_id, moderation_id, role_id in zip( for target_id, moderation_id, role_id in zip(
target_ids, target_ids, moderation_ids, role_ids
moderation_ids,
role_ids,
): ):
try: try:
member = await guild.fetch_member(target_id) member = await guild.fetch_member(target_id)
await member.remove_roles( await member.remove_roles(
Object(role_id), Object(role_id), reason=f"Automatic role removal from case #{moderation_id}"
reason=f"Automatic role removal from case #{moderation_id}",
) )
removerole_num = removerole_num + 1 removerole_num = removerole_num + 1
@ -1727,16 +1725,13 @@ class Aurora(commands.Cog):
role_ids = [row[2] for row in result] role_ids = [row[2] for row in result]
for target_id, moderation_id, role_id in zip( for target_id, moderation_id, role_id in zip(
target_ids, target_ids, moderation_ids, role_ids
moderation_ids,
role_ids,
): ):
try: try:
member = await guild.fetch_member(target_id) member = await guild.fetch_member(target_id)
await member.add_roles( await member.add_roles(
Object(role_id), Object(role_id), reason=f"Automatic role addition from case #{moderation_id}"
reason=f"Automatic role addition from case #{moderation_id}",
) )
addrole_num = addrole_num + 1 addrole_num = addrole_num + 1
@ -1832,11 +1827,15 @@ class Aurora(commands.Cog):
@commands.admin() @commands.admin()
async def aurora_import_aurora(self, ctx: commands.Context): async def aurora_import_aurora(self, ctx: commands.Context):
"""Import moderation history from another bot using Aurora.""" """Import moderation history from another bot using Aurora."""
if ctx.message.attachments and ctx.message.attachments[0].content_type == "application/json; charset=utf-8": if (
ctx.message.attachments
and ctx.message.attachments[0].content_type
== "application/json; charset=utf-8"
):
message = await ctx.send( message = await ctx.send(
warning( warning(
"Are you sure you want to import moderations from another bot?\n**This will overwrite any moderations that already exist in this guild's moderation table.**\n*The import process will block the rest of your bot until it is complete.*", "Are you sure you want to import moderations from another bot?\n**This will overwrite any moderations that already exist in this guild's moderation table.**\n*The import process will block the rest of your bot until it is complete.*"
), )
) )
await message.edit(view=ImportAuroraView(60, ctx, message)) await message.edit(view=ImportAuroraView(60, ctx, message))
else: else:
@ -1846,16 +1845,20 @@ class Aurora(commands.Cog):
@commands.admin() @commands.admin()
async def aurora_import_galacticbot(self, ctx: commands.Context): async def aurora_import_galacticbot(self, ctx: commands.Context):
"""Import moderation history from GalacticBot.""" """Import moderation history from GalacticBot."""
if ctx.message.attachments and ctx.message.attachments[0].content_type == "application/json; charset=utf-8": if (
ctx.message.attachments
and ctx.message.attachments[0].content_type
== "application/json; charset=utf-8"
):
message = await ctx.send( message = await ctx.send(
warning( warning(
"Are you sure you want to import GalacticBot moderations?\n**This will overwrite any moderations that already exist in this guild's moderation table.**\n*The import process will block the rest of your bot until it is complete.*", "Are you sure you want to import GalacticBot moderations?\n**This will overwrite any moderations that already exist in this guild's moderation table.**\n*The import process will block the rest of your bot until it is complete.*"
), )
) )
await message.edit(view=ImportGalacticBotView(60, ctx, message)) await message.edit(view=ImportGalacticBotView(60, ctx, message))
else: else:
await ctx.send( await ctx.send(
error("Please provide a valid GalacticBot moderation export file."), error("Please provide a valid GalacticBot moderation export file.")
) )
@aurora.command(aliases=["tdc", "td", "timedeltaconvert"]) @aurora.command(aliases=["tdc", "td", "timedeltaconvert"])

View file

@ -17,9 +17,13 @@ class ImportAuroraView(ui.View):
self.message: Message = message self.message: Message = message
@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() database = connect()
cursor = database.cursor() cursor = database.cursor()
@ -97,10 +101,16 @@ class ImportAuroraView(ui.View):
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)) await interaction.edit_original_response(
content="Import complete.\n"
+ warning("Failed to import the following cases:\n")
+ box(failed_cases)
)
@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
await self.message.edit(content="Import cancelled.", view=None) await self.message.edit(content="Import cancelled.", view=None)
await self.message.delete(10) await self.message.delete(10)
await self.ctx.message.delete(10) await self.ctx.message.delete(10)

View file

@ -16,9 +16,13 @@ class ImportGalacticBotView(ui.View):
self.message: Message = message self.message: Message = message
@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() database = connect()
cursor = database.cursor() cursor = database.cursor()
@ -88,7 +92,9 @@ class ImportGalacticBotView(ui.View):
if resolved_by is None: if resolved_by is None:
resolved_by = "?" resolved_by = "?"
if resolved_reason is None: if resolved_reason is None:
resolved_reason = "Could not get resolve reason during moderation import." resolved_reason = (
"Could not get resolve reason during moderation import."
)
if resolved_timestamp is None: if resolved_timestamp is None:
resolved_timestamp = timestamp resolved_timestamp = timestamp
changes = [ changes = [
@ -136,10 +142,16 @@ class ImportGalacticBotView(ui.View):
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)) await interaction.edit_original_response(
content="Import complete.\n"
+ warning("Failed to import the following cases:\n")
+ box(failed_cases)
)
@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
await self.message.edit(content="Import cancelled.", view=None) await self.message.edit(content="Import cancelled.", view=None)
await self.message.delete(10) await self.message.delete(10)
await self.ctx.message.delete(10) await self.ctx.message.delete(10)

View file

@ -23,7 +23,7 @@ class Addrole(ui.View):
return return
await interaction.response.defer() await interaction.response.defer()
async with config.guild(self.ctx.guild).addrole_whitelist() as addrole_whitelist: async with config.guild(self.ctx.guild).addrole_whitelist() as addrole_whitelist:
addrole_whitelist: list # type hint addrole_whitelist: list # type hint
for value in select.values: for value in select.values:
if value.id in addrole_whitelist: if value.id in addrole_whitelist:
addrole_whitelist.remove(value.id) addrole_whitelist.remove(value.id)
@ -32,7 +32,7 @@ class Addrole(ui.View):
await interaction.message.edit(embed=await addrole_embed(self.ctx)) await interaction.message.edit(embed=await addrole_embed(self.ctx))
@ui.button(label="Clear", style=ButtonStyle.red, row=1) @ui.button(label="Clear", style=ButtonStyle.red, row=1)
async def clear(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument async def clear(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(error("You must have the manage guild permission to clear the guild's addrole whitelist."), ephemeral=True) await interaction.response.send_message(error("You must have the manage guild permission to clear the guild's addrole whitelist."), ephemeral=True)
return return
@ -41,7 +41,7 @@ class Addrole(ui.View):
await interaction.message.edit(embed=await addrole_embed(self.ctx)) await interaction.message.edit(embed=await addrole_embed(self.ctx))
@ui.button(label="Close", style=ButtonStyle.gray) @ui.button(label="Close", style=ButtonStyle.gray)
async def close(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument async def close(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(error("You can't do that!"), ephemeral=True) await interaction.response.send_message(error("You can't do that!"), ephemeral=True)
return return

View file

@ -17,7 +17,7 @@ class Guild(ui.View):
await self.message.edit(view=None) await self.message.edit(view=None)
@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
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
@ -27,7 +27,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="Use Discord Permissions", style=ButtonStyle.green, row=0) @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 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: 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
@ -37,7 +37,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_heirarchy(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
@ -47,7 +47,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="Ignore Modlog", style=ButtonStyle.green, row=0) @ui.button(label="Ignore Modlog", style=ButtonStyle.green, row=0)
async def ignore_modlog(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument async def ignore_modlog(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
@ -57,7 +57,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="Ignore Other Bots", style=ButtonStyle.green, row=0) @ui.button(label="Ignore Other Bots", style=ButtonStyle.green, row=0)
async def ignore_other_bots(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument async def ignore_other_bots(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
@ -67,7 +67,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="DM Users", style=ButtonStyle.green, row=1) @ui.button(label="DM Users", style=ButtonStyle.green, row=1)
async def dm_users(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument 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: 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
@ -77,7 +77,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="Auto Evidence Format", style=ButtonStyle.green, row=1) @ui.button(label="Auto Evidence Format", style=ButtonStyle.green, row=1)
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
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
@ -87,7 +87,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="Ephemeral", style=ButtonStyle.green, row=1) @ui.button(label="Ephemeral", style=ButtonStyle.green, row=1)
async def ephemeral(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument async def ephemeral(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
@ -97,7 +97,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="History Inline", style=ButtonStyle.green, row=1) @ui.button(label="History Inline", style=ButtonStyle.green, row=1)
async def inline(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument async def inline(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
@ -107,11 +107,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.select(placeholder="History Pagesize", options=create_pagesize_options(), row=2) @ui.select(placeholder="History Pagesize", options=create_pagesize_options(), row=2)
async def pagesize( async def pagesize(self, interaction: Interaction, select: ui.Select,):
self,
interaction: Interaction,
select: ui.Select,
):
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
@ -123,11 +119,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.select(placeholder="History Inline Pagesize", options=create_pagesize_options(), row=3) @ui.select(placeholder="History Inline Pagesize", options=create_pagesize_options(), row=3)
async def inline_pagesize( async def inline_pagesize(self, interaction: Interaction, select: ui.Select,):
self,
interaction: Interaction,
select: ui.Select,
):
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

@ -23,7 +23,7 @@ class Immune(ui.View):
return return
await interaction.response.defer() await interaction.response.defer()
async with config.guild(self.ctx.guild).immune_roles() as immune_roles: async with config.guild(self.ctx.guild).immune_roles() as immune_roles:
immune_roles: list # type hint immune_roles: list # type hint
for value in select.values: for value in select.values:
if value.id in immune_roles: if value.id in immune_roles:
immune_roles.remove(value.id) immune_roles.remove(value.id)
@ -32,7 +32,7 @@ class Immune(ui.View):
await interaction.message.edit(embed=await immune_embed(self.ctx)) await interaction.message.edit(embed=await immune_embed(self.ctx))
@ui.button(label="Clear", style=ButtonStyle.red, row=1) @ui.button(label="Clear", style=ButtonStyle.red, row=1)
async def clear(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument async def clear(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(error("You must have the manage guild permission to clear the guild's immune roles."), ephemeral=True) await interaction.response.send_message(error("You must have the manage guild permission to clear the guild's immune roles."), ephemeral=True)
return return
@ -41,7 +41,7 @@ class Immune(ui.View):
await interaction.message.edit(embed=await immune_embed(self.ctx)) await interaction.message.edit(embed=await immune_embed(self.ctx))
@ui.button(label="Close", style=ButtonStyle.gray) @ui.button(label="Close", style=ButtonStyle.gray)
async def close(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument async def close(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(error("You can't do that!"), ephemeral=True) await interaction.response.send_message(error("You can't do that!"), ephemeral=True)
return return

View file

@ -17,7 +17,7 @@ class Overrides(ui.View):
await self.message.edit(view=None) await self.message.edit(view=None)
@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
if self.ctx.author != interaction.user: if self.ctx.author != interaction.user:
await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True) await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True)
return return
@ -32,7 +32,7 @@ class Overrides(ui.View):
await interaction.message.edit(embed=await overrides_embed(self.ctx)) await interaction.message.edit(embed=await overrides_embed(self.ctx))
@ui.button(label="Ephemeral", style=ButtonStyle.green, row=0) @ui.button(label="Ephemeral", style=ButtonStyle.green, row=0)
async def ephemeral(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument async def ephemeral(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
if self.ctx.author != interaction.user: if self.ctx.author != interaction.user:
await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True) await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True)
return return
@ -47,7 +47,7 @@ class Overrides(ui.View):
await interaction.message.edit(embed=await overrides_embed(self.ctx)) await interaction.message.edit(embed=await overrides_embed(self.ctx))
@ui.button(label="Inline", style=ButtonStyle.green, row=0) @ui.button(label="Inline", style=ButtonStyle.green, row=0)
async def inline(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument async def inline(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
if self.ctx.author != interaction.user: if self.ctx.author != interaction.user:
await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True) await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True)
return return
@ -62,11 +62,7 @@ class Overrides(ui.View):
await interaction.message.edit(embed=await overrides_embed(self.ctx)) await interaction.message.edit(embed=await overrides_embed(self.ctx))
@ui.select(placeholder="Inline Pagesize", options=create_pagesize_options(), row=1) @ui.select(placeholder="Inline Pagesize", options=create_pagesize_options(), row=1)
async def inline_pagesize( async def inline_pagesize(self, interaction: Interaction, select: ui.Select,):
self,
interaction: Interaction,
select: ui.Select,
):
if self.ctx.author != interaction.user: if self.ctx.author != interaction.user:
await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True) await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True)
return return
@ -78,11 +74,7 @@ class Overrides(ui.View):
await interaction.message.edit(embed=await overrides_embed(self.ctx)) await interaction.message.edit(embed=await overrides_embed(self.ctx))
@ui.select(placeholder="Pagesize", options=create_pagesize_options(), row=2) @ui.select(placeholder="Pagesize", options=create_pagesize_options(), row=2)
async def pagesize( async def pagesize(self, interaction: Interaction, select: ui.Select,):
self,
interaction: Interaction,
select: ui.Select,
):
if self.ctx.author != interaction.user: if self.ctx.author != interaction.user:
await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True) await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True)
return return

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

@ -75,9 +75,7 @@ async def message_factory(
if await config.guild(guild).show_moderator() and moderator is not None: if await config.guild(guild).show_moderator() and moderator is not None:
embed.add_field( embed.add_field(
name="Moderator", name="Moderator", value=f"`{moderator.name} ({moderator.id})`", inline=False
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)
@ -96,9 +94,7 @@ async def message_factory(
async def log_factory( async def log_factory(
interaction: Interaction, interaction: Interaction, case_dict: dict, resolved: bool = False
case_dict: dict,
resolved: bool = False,
) -> Embed: ) -> 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.
@ -107,11 +103,14 @@ async def log_factory(
case_dict (dict): The case dictionary. case_dict (dict): The case dictionary.
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 = ""
if resolved: if resolved:
if case_dict["target_type"] == "USER": if case_dict["target_type"] == "USER":
target_user = await fetch_user_dict(interaction.client, case_dict["target_id"]) 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']}`" 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": elif case_dict["target_type"] == "CHANNEL":
target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"]) target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"])
if target_user["mention"]: if target_user["mention"]:
@ -120,7 +119,11 @@ async def log_factory(
target_name = f"`{target_user['name']}`" target_name = f"`{target_user['name']}`"
moderator_user = await fetch_user_dict(interaction.client, case_dict["moderator_id"]) 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']}`" 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 #{case_dict['moderation_id']:,} Resolved",
@ -137,24 +140,40 @@ async def log_factory(
["hours", "minutes", "seconds"], ["hours", "minutes", "seconds"],
case_dict["duration"].split(":"), 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'])}"
) )
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) embed.add_field(name="Reason", value=box(case_dict["reason"]), inline=False)
resolved_user = await fetch_user_dict(interaction.client, case_dict["resolved_by"]) 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']}" 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_name}` ({resolved_user['id']}) for:\n"
+ box(case_dict["resolve_reason"]),
inline=False, inline=False,
) )
else: else:
if case_dict["target_type"] == "USER": if case_dict["target_type"] == "USER":
target_user = await fetch_user_dict(interaction.client, case_dict["target_id"]) 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']}`" 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": elif case_dict["target_type"] == "CHANNEL":
target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"]) target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"])
if target_user["mention"]: if target_user["mention"]:
@ -163,7 +182,11 @@ async def log_factory(
target_name = f"`{target_user['name']}`" target_name = f"`{target_user['name']}`"
moderator_user = await fetch_user_dict(interaction.client, case_dict["moderator_id"]) 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']}`" 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 #{case_dict['moderation_id']:,}",
@ -179,9 +202,12 @@ async def log_factory(
["hours", "minutes", "seconds"], ["hours", "minutes", "seconds"],
case_dict["duration"].split(":"), case_dict["duration"].split(":"),
) )
}, }
)
embed.description = (
embed.description
+ f"\n**Duration:** {humanize_timedelta(timedelta=td)} | <t:{case_dict['end_timestamp']}:R>"
) )
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) embed.add_field(name="Reason", value=box(case_dict["reason"]), inline=False)
return embed return embed
@ -194,10 +220,13 @@ async def case_factory(interaction: Interaction, case_dict: dict) -> Embed:
interaction (Interaction): The interaction object. interaction (Interaction): The interaction object.
case_dict (dict): The case dictionary. case_dict (dict): The case dictionary.
""" """
target_name = ""
if case_dict["target_type"] == "USER": if case_dict["target_type"] == "USER":
target_user = await fetch_user_dict(interaction.client, case_dict["target_id"]) 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']}`" 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": elif case_dict["target_type"] == "CHANNEL":
target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"]) target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"])
if target_user["mention"]: if target_user["mention"]:
@ -206,7 +235,11 @@ async def case_factory(interaction: Interaction, case_dict: dict) -> Embed:
target_name = f"`{target_user['name']}`" target_name = f"`{target_user['name']}`"
moderator_user = await fetch_user_dict(interaction.client, case_dict["moderator_id"]) 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']}`" 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 #{case_dict['moderation_id']:,}",
@ -219,28 +252,41 @@ async def case_factory(interaction: Interaction, case_dict: dict) -> Embed:
**{ **{
unit: int(val) unit: int(val)
for unit, val in zip( for unit, val in zip(
["hours", "minutes", "seconds"], ["hours", "minutes", "seconds"], case_dict["duration"].split(":")
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))
) )
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**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(case_dict['changes']) - 1}"
if case_dict["changes"]
else "\n**Changes:** 0"
)
if case_dict["role_id"]: if case_dict["role_id"]:
embed.description += f"\n**Role:** <@&{case_dict['role_id']}>" embed.description += f"\n**Role:** <@&{case_dict['role_id']}>"
if case_dict["metadata"]: if case_dict["metadata"]:
if case_dict["metadata"]["imported_from"]: if case_dict["metadata"]["imported_from"]:
embed.description += f"\n**Imported From:** {case_dict['metadata']['imported_from']}" embed.description += (
f"\n**Imported From:** {case_dict['metadata']['imported_from']}"
)
embed.add_field(name="Reason", value=box(case_dict["reason"]), inline=False) embed.add_field(name="Reason", value=box(case_dict["reason"]), inline=False)
if case_dict["resolved"] == 1: if case_dict["resolved"] == 1:
resolved_user = await fetch_user_dict(interaction.client, case_dict["resolved_by"]) resolved_user = await fetch_user_dict(interaction.client, case_dict["resolved_by"])
resolved_name = f"`{resolved_user['name']}`" if resolved_user["discriminator"] == "0" else f"`{resolved_user['name']}#{resolved_user['discriminator']}`" resolved_name = (
f"`{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_name} ({resolved_user['id']}) for:\n{box(case_dict['resolve_reason'])}",
@ -268,12 +314,15 @@ async def changes_factory(interaction: Interaction, case_dict: dict) -> Embed:
for change in case_dict["changes"]: for change in case_dict["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 fetch_user_dict(
interaction.client, interaction.client, change["user_id"]
change["user_id"],
) )
user = memory_dict[str(change["user_id"])] user = memory_dict[str(change["user_id"])]
name = user["name"] if user["discriminator"] == "0" else f"{user['name']}#{user['discriminator']}" 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['timestamp']}> | <t:{change['timestamp']}:R>"
@ -311,17 +360,24 @@ async def evidenceformat_factory(interaction: Interaction, case_dict: dict) -> s
interaction (Interaction): The interaction object. interaction (Interaction): The interaction object.
case_dict (dict): The case dictionary. case_dict (dict): The case dictionary.
""" """
target_name = ""
if case_dict["target_type"] == "USER": if case_dict["target_type"] == "USER":
target_user = await fetch_user_dict(interaction.client, case_dict["target_id"]) 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']}" target_name = (
target_user["name"]
if target_user["discriminator"] == "0"
else f"{target_user['name']}#{target_user['discriminator']}"
)
elif case_dict["target_type"] == "CHANNEL": elif case_dict["target_type"] == "CHANNEL":
target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"]) target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"])
target_name = target_user["name"] target_name = target_user["name"]
moderator_user = await fetch_user_dict(interaction.client, case_dict["moderator_id"]) moderator_user = await fetch_user_dict(interaction.client, case_dict["moderator_id"])
moderator_name = moderator_user["name"] if moderator_user["discriminator"] == "0" else f"{moderator_user['name']}#{moderator_user['discriminator']}" moderator_name = (
moderator_user["name"]
if moderator_user["discriminator"] == "0"
else f"{moderator_user['name']}#{moderator_user['discriminator']}"
)
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']})" 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']})"
@ -363,11 +419,17 @@ async def overrides_embed(ctx: commands.Context) -> Embed:
} }
override_str = [ override_str = [
"- " + bold("Auto Evidence Format: ") + get_bool_emoji(override_settings["auto_evidenceformat"]), "- "
+ bold("Auto Evidence Format: ")
+ get_bool_emoji(override_settings["auto_evidenceformat"]),
"- " + bold("Ephemeral: ") + get_bool_emoji(override_settings["ephemeral"]), "- " + bold("Ephemeral: ") + get_bool_emoji(override_settings["ephemeral"]),
"- " + bold("History Inline: ") + get_bool_emoji(override_settings["inline"]), "- " + bold("History Inline: ") + get_bool_emoji(override_settings["inline"]),
"- " + bold("History Inline Pagesize: ") + get_pagesize_str(override_settings["inline_pagesize"]), "- "
"- " + bold("History Pagesize: ") + get_pagesize_str(override_settings["pagesize"]), + bold("History Inline Pagesize: ")
+ get_pagesize_str(override_settings["inline_pagesize"]),
"- "
+ bold("History Pagesize: ")
+ get_pagesize_str(override_settings["pagesize"]),
] ]
override_str = "\n".join(override_str) override_str = "\n".join(override_str)
@ -389,7 +451,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, ctx.guild
).use_discord_permissions(), ).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(),
@ -399,7 +461,7 @@ async def guild_embed(ctx: commands.Context) -> Embed:
"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, ctx.guild
).history_inline_pagesize(), ).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(),
@ -412,17 +474,37 @@ async def guild_embed(ctx: commands.Context) -> Embed:
channel = channel.mention channel = channel.mention
guild_str = [ guild_str = [
"- " + bold("Show Moderator: ") + get_bool_emoji(guild_settings["show_moderator"]), "- "
"- " + bold("Use Discord Permissions: ") + get_bool_emoji(guild_settings["use_discord_permissions"]), + bold("Show Moderator: ")
"- " + bold("Respect Hierarchy: ") + get_bool_emoji(guild_settings["respect_hierarchy"]), + get_bool_emoji(guild_settings["show_moderator"]),
"- " + bold("Ignore Modlog: ") + get_bool_emoji(guild_settings["ignore_modlog"]), "- "
"- " + bold("Ignore Other Bots: ") + get_bool_emoji(guild_settings["ignore_other_bots"]), + bold("Use Discord Permissions: ")
+ get_bool_emoji(guild_settings["use_discord_permissions"]),
"- "
+ bold("Respect Hierarchy: ")
+ get_bool_emoji(guild_settings["respect_hierarchy"]),
"- "
+ bold("Ignore Modlog: ")
+ get_bool_emoji(guild_settings["ignore_modlog"]),
"- "
+ bold("Ignore Other Bots: ")
+ get_bool_emoji(guild_settings["ignore_other_bots"]),
"- " + bold("DM Users: ") + get_bool_emoji(guild_settings["dm_users"]), "- " + bold("DM Users: ") + get_bool_emoji(guild_settings["dm_users"]),
"- " + bold("Auto Evidence Format: ") + get_bool_emoji(guild_settings["auto_evidenceformat"]), "- "
"- " + bold("Ephemeral: ") + get_bool_emoji(guild_settings["history_ephemeral"]), + bold("Auto Evidence Format: ")
"- " + bold("History Inline: ") + get_bool_emoji(guild_settings["history_inline"]), + get_bool_emoji(guild_settings["auto_evidenceformat"]),
"- " + bold("History Pagesize: ") + get_pagesize_str(guild_settings["history_pagesize"]), "- "
"- " + bold("History Inline Pagesize: ") + get_pagesize_str(guild_settings["history_inline_pagesize"]), + bold("Ephemeral: ")
+ get_bool_emoji(guild_settings["history_ephemeral"]),
"- "
+ bold("History Inline: ")
+ get_bool_emoji(guild_settings["history_inline"]),
"- "
+ bold("History Pagesize: ")
+ get_pagesize_str(guild_settings["history_pagesize"]),
"- "
+ bold("History Inline Pagesize: ")
+ get_pagesize_str(guild_settings["history_inline_pagesize"]),
"- " + bold("Log Channel: ") + channel, "- " + bold("Log Channel: ") + channel,
] ]
guild_str = "\n".join(guild_str) guild_str = "\n".join(guild_str)
@ -446,21 +528,17 @@ async def addrole_embed(ctx: commands.Context) -> Embed:
for role in whitelist: for role in whitelist:
evalulated_role = ctx.guild.get_role(role) or error(f"`{role}` (Not Found)") evalulated_role = ctx.guild.get_role(role) or error(f"`{role}` (Not Found)")
if isinstance(evalulated_role, Role): if isinstance(evalulated_role, Role):
roles.append( roles.append({
{ "id": evalulated_role.id,
"id": evalulated_role.id, "mention": evalulated_role.mention,
"mention": evalulated_role.mention, "position": evalulated_role.position
"position": evalulated_role.position, })
},
)
else: else:
roles.append( roles.append({
{ "id": role,
"id": role, "mention": error(f"`{role}` (Not Found)"),
"mention": error(f"`{role}` (Not Found)"), "position": 0
"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)
@ -471,7 +549,9 @@ async def addrole_embed(ctx: commands.Context) -> Embed:
e = await _config(ctx) e = await _config(ctx)
e.title += ": Addrole Whitelist" e.title += ": Addrole Whitelist"
e.description = "Use the select menu below to manage this guild's addrole whitelist." e.description = (
"Use the select menu below to manage this guild's addrole whitelist."
)
if len(whitelist_str) > 4000 and len(whitelist_str) < 5000: if len(whitelist_str) > 4000 and len(whitelist_str) < 5000:
lines = whitelist_str.split("\n") lines = whitelist_str.split("\n")
@ -501,21 +581,17 @@ async def immune_embed(ctx: commands.Context) -> Embed:
for role in immune_roles: for role in immune_roles:
evalulated_role = ctx.guild.get_role(role) or error(f"`{role}` (Not Found)") evalulated_role = ctx.guild.get_role(role) or error(f"`{role}` (Not Found)")
if isinstance(evalulated_role, Role): if isinstance(evalulated_role, Role):
roles.append( roles.append({
{ "id": evalulated_role.id,
"id": evalulated_role.id, "mention": evalulated_role.mention,
"mention": evalulated_role.mention, "position": evalulated_role.position
"position": evalulated_role.position, })
},
)
else: else:
roles.append( roles.append({
{ "id": role,
"id": role, "mention": error(f"`{role}` (Not Found)"),
"mention": error(f"`{role}` (Not Found)"), "position": 0
"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)

View file

@ -32,17 +32,24 @@ def check_permissions(
raise (KeyError) raise (KeyError)
for permission in permissions: for permission in permissions:
if not getattr(resolved_permissions, permission, False) and resolved_permissions.administrator is not True: if (
not getattr(resolved_permissions, permission, False)
and resolved_permissions.administrator is not True
):
return permission return permission
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], interaction: Interaction, permissions: list
) -> 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): if check_permissions(interaction.client.user, permissions, guild=interaction.guild):
await interaction.response.send_message( await interaction.response.send_message(
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
@ -50,30 +57,43 @@ async def check_moddable(target: Union[User, Member], interaction: Interaction,
if await config.guild(interaction.guild).use_discord_permissions() is True: if await config.guild(interaction.guild).use_discord_permissions() is True:
if check_permissions(interaction.user, permissions, guild=interaction.guild): if check_permissions(interaction.user, permissions, guild=interaction.guild):
await interaction.response.send_message( await interaction.response.send_message(
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 interaction.user.id == target.id:
await interaction.response.send_message(content="You cannot moderate yourself!", ephemeral=True) await interaction.response.send_message(
content="You cannot moderate yourself!", ephemeral=True
)
return False return False
if target.bot: if target.bot:
await interaction.response.send_message(content="You cannot moderate bots!", ephemeral=True) await interaction.response.send_message(
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 interaction.user.top_role <= target.top_role and await config.guild(interaction.guild).respect_hierarchy() is True:
await interaction.response.send_message( await interaction.response.send_message(
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 (
interaction.guild.get_member(interaction.client.user.id).top_role
<= target.top_role
):
await interaction.response.send_message( await interaction.response.send_message(
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,
) )
return False return False
@ -98,13 +118,15 @@ async def get_next_case_number(guild_id: str, cursor=None) -> int:
if not cursor: if not cursor:
database = connect() database = connect()
cursor = database.cursor() cursor = database.cursor()
cursor.execute(f"SELECT moderation_id FROM `moderation_{guild_id}` ORDER BY moderation_id DESC LIMIT 1") cursor.execute(
f"SELECT moderation_id FROM `moderation_{guild_id}` ORDER BY moderation_id DESC LIMIT 1"
)
result = cursor.fetchone() result = cursor.fetchone()
return (result[0] + 1) if result else 1 return (result[0] + 1) if result else 1
def generate_dict(result) -> dict: def generate_dict(result) -> dict:
return { case = {
"moderation_id": result[0], "moderation_id": result[0],
"timestamp": result[1], "timestamp": result[1],
"moderation_type": result[2], "moderation_type": result[2],
@ -122,6 +144,7 @@ def generate_dict(result) -> dict:
"changes": json.loads(result[14]), "changes": json.loads(result[14]),
"metadata": json.loads(result[15]), "metadata": json.loads(result[15]),
} }
return case
async def fetch_user_dict(client: commands.Bot, user_id: str) -> dict: async def fetch_user_dict(client: commands.Bot, user_id: str) -> dict:
@ -148,6 +171,7 @@ async def fetch_user_dict(client: commands.Bot, user_id: str) -> dict:
"discriminator": "0", "discriminator": "0",
} }
return user_dict return user_dict
@ -174,9 +198,11 @@ 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.""" """This function returns a dictionary containing either role information or a standard deleted role template."""
role = guild.get_role(int(role_id)) role = guild.get_role(int(role_id))
if not role: if not role:
pass role_dict = {"id": role_id, "name": "Deleted Role"}
return {"id": role.id, "name": role.name} role_dict = {"id": role.id, "name": role.name}
return role_dict
async def log(interaction: Interaction, moderation_id: int, resolved: bool = False) -> None: async def log(interaction: Interaction, moderation_id: int, resolved: bool = False) -> None:
@ -190,7 +216,9 @@ async def log(interaction: Interaction, moderation_id: int, resolved: bool = Fal
case = await fetch_case(moderation_id, interaction.guild.id) case = await fetch_case(moderation_id, interaction.guild.id)
if case: if case:
embed = await log_factory(interaction=interaction, case_dict=case, resolved=resolved) embed = await log_factory(
interaction=interaction, case_dict=case, resolved=resolved
)
try: try:
await logging_channel.send(embed=embed) await logging_channel.send(embed=embed)
except Forbidden: except Forbidden:
@ -201,7 +229,11 @@ async def send_evidenceformat(interaction: Interaction, case_dict: dict) -> 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 .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(interaction.user).auto_evidenceformat()
or await config.guild(interaction.guild).auto_evidenceformat()
or False
)
if send_evidence_bool is False: if send_evidence_bool is False:
return return
@ -242,19 +274,24 @@ 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) -> td:
"""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 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"

View file

@ -17,16 +17,13 @@ from redbot.core.bot import Red
from redbot.core.utils.chat_formatting import bold, error, humanize_list, text_to_file from redbot.core.utils.chat_formatting import bold, error, humanize_list, text_to_file
# Disable Ruff & Pylint complaining about accessing private members
# That's kind of necessary for this cog to function because the Downloader cog has a limited public API
# ruff: noqa: SLF001 # Private member access
# pylint: disable=protected-access # pylint: disable=protected-access
class Backup(commands.Cog): class Backup(commands.Cog):
"""A utility to make reinstalling repositories and cogs after migrating the bot far easier.""" """A utility to make reinstalling repositories and cogs after migrating the bot far easier."""
__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.1"
__documentation__ = "https://seacogs.coastalcommits.com/backup/" __documentation__ = "https://seacogs.coastalcommits.com/backup/"
def __init__(self, bot: Red): def __init__(self, bot: Red):
@ -45,18 +42,22 @@ class Backup(commands.Cog):
] ]
return "\n".join(text) return "\n".join(text)
@commands.group(autohelp=True) # type: ignore @commands.group(autohelp=True)
@commands.is_owner() @commands.is_owner()
async def backup(self, ctx: commands.Context) -> None: async def backup(self, ctx: commands.Context):
"""Backup your installed cogs.""" """Backup your installed cogs."""
@backup.command(name="export") @backup.command(name="export")
@commands.is_owner() @commands.is_owner()
async def backup_export(self, ctx: commands.Context) -> None: async def backup_export(self, ctx: commands.Context):
"""Export your installed repositories and cogs to a file.""" """Export your installed repositories and cogs to a file."""
downloader = ctx.bot.get_cog("Downloader") downloader = ctx.bot.get_cog("Downloader")
if downloader is None: if downloader is None:
await ctx.send(error(f"You do not have the `Downloader` cog loaded. Please run `{ctx.prefix}load downloader` and try again.")) await ctx.send(
error(
f"You do not have the `Downloader` cog loaded. Please run `{ctx.prefix}load downloader` and try again."
)
)
return return
all_repos = list(downloader._repo_manager.repos) all_repos = list(downloader._repo_manager.repos)
@ -77,7 +78,7 @@ class Backup(commands.Cog):
if cog.repo_name == repo.name: if cog.repo_name == repo.name:
cog_dict = { cog_dict = {
"name": cog.name, "name": cog.name,
# "loaded": cog.name in ctx.bot.extensions.keys(), # noqa: ERA001 # "loaded": cog.name in ctx.bot.extensions.keys(),
# this functionality was planned but never implemented due to Red limitations # this functionality was planned but never implemented due to Red limitations
# and the possibility of restoration functionality being added to Core # and the possibility of restoration functionality being added to Core
"pinned": cog.pinned, "pinned": cog.pinned,
@ -87,24 +88,30 @@ class Backup(commands.Cog):
export_data.append(repo_dict) export_data.append(repo_dict)
await ctx.send(file=text_to_file(json.dumps(export_data, indent=4), "backup.json")) await ctx.send(
file=text_to_file(json.dumps(export_data, indent=4), "backup.json")
)
@backup.command(name="import") @backup.command(name="import")
@commands.is_owner() @commands.is_owner()
async def backup_import(self, ctx: commands.Context) -> None: async def backup_import(self, ctx: commands.Context):
"""Import your installed repositories and cogs from an export file.""" """Import your installed repositories and cogs from an export file."""
try: try:
export = json.loads(await ctx.message.attachments[0].read()) export = json.loads(await ctx.message.attachments[0].read())
except (json.JSONDecodeError, IndexError): except (json.JSONDecodeError, IndexError):
try: try:
export = json.loads(await ctx.message.reference.resolved.attachments[0].read()) # type: ignore - this is fine to let error because it gets handled export = json.loads(await ctx.message.reference.resolved.attachments[0].read())
except (json.JSONDecodeError, IndexError, AttributeError): except (json.JSONDecodeError, IndexError, AttributeError):
await ctx.send(error("Please provide a valid JSON export file.")) await ctx.send(error("Please provide a valid JSON export file."))
return return
downloader = ctx.bot.get_cog("Downloader") downloader = ctx.bot.get_cog("Downloader")
if downloader is None: if downloader is None:
await ctx.send(error(f"You do not have the `Downloader` cog loaded. Please run `{ctx.prefix}load downloader` and try again.")) await ctx.send(
error(
f"You do not have the `Downloader` cog loaded. Please run `{ctx.prefix}load downloader` and try again."
)
)
return return
repo_s = [] repo_s = []
@ -126,20 +133,32 @@ class Backup(commands.Cog):
repo_e.append("PyLav cogs are not supported.") repo_e.append("PyLav cogs are not supported.")
continue continue
if name.startswith(".") or name.endswith("."): if name.startswith(".") or name.endswith("."):
repo_e.append(f"Invalid repository name: {name}\nRepository names cannot start or end with a dot.") repo_e.append(
f"Invalid repository name: {name}\nRepository names cannot start or end with a dot."
)
continue continue
if re.match(r"^[a-zA-Z0-9_\-\.]+$", name) is None: if re.match(r"^[a-zA-Z0-9_\-\.]+$", name) is None:
repo_e.append(f"Invalid repository name: {name}\nRepository names may only contain letters, numbers, underscores, hyphens, and dots.") repo_e.append(
f"Invalid repository name: {name}\nRepository names may only contain letters, numbers, underscores, hyphens, and dots."
)
continue continue
try: try:
repository = await downloader._repo_manager.add_repo(url, name, branch) repository = await downloader._repo_manager.add_repo(
repo_s.append(f"Added repository {name} from {url} on branch {branch}.") url, name, branch
self.logger.debug("Added repository %s from %s on branch %s", name, url, branch) )
repo_s.append(
f"Added repository {name} from {url} on branch {branch}."
)
self.logger.debug(
"Added repository %s from %s on branch %s", name, url, branch
)
except errors.ExistingGitRepo: except errors.ExistingGitRepo:
repo_e.append(f"Repository {name} already exists.") repo_e.append(f"Repository {name} already exists.")
repository = downloader._repo_manager.get_repo(name) repository = downloader._repo_manager.get_repo(
name
)
self.logger.debug("Repository %s already exists", name) self.logger.debug("Repository %s already exists", name)
except errors.AuthenticationError as err: except errors.AuthenticationError as err:
@ -153,7 +172,9 @@ class Backup(commands.Cog):
continue continue
except errors.CloningError as err: except errors.CloningError as err:
repo_e.append(f"Cloning error while adding repository {name}. See logs for more information.") repo_e.append(
f"Cloning error while adding repository {name}. See logs for more information."
)
self.logger.exception( self.logger.exception(
"Something went wrong whilst cloning %s (to revision %s)", "Something went wrong whilst cloning %s (to revision %s)",
url, url,
@ -163,7 +184,9 @@ class Backup(commands.Cog):
continue continue
except OSError: except OSError:
repo_e.append(f"OS error while adding repository {name}. See logs for more information.") repo_e.append(
f"OS error while adding repository {name}. See logs for more information."
)
self.logger.exception( self.logger.exception(
"Something went wrong trying to add repo %s under name %s", "Something went wrong trying to add repo %s under name %s",
url, url,
@ -183,19 +206,23 @@ class Backup(commands.Cog):
continue continue
cog_modules.append(cog_module) cog_modules.append(cog_module)
for cog in {cog.name for cog in cog_modules}: for cog in set(cog.name for cog in cog_modules):
poss_installed_path = (await downloader.cog_install_path()) / cog poss_installed_path = (await downloader.cog_install_path()) / cog
if poss_installed_path.exists(): if poss_installed_path.exists():
with contextlib.suppress(commands.ExtensionNotLoaded): with contextlib.suppress(commands.ExtensionNotLoaded):
await ctx.bot.unload_extension(cog) await ctx.bot.unload_extension(cog)
await ctx.bot.remove_loaded_package(cog) await ctx.bot.remove_loaded_package(cog)
await downloader._delete_cog(poss_installed_path) await downloader._delete_cog(
poss_installed_path
)
uninstall_s.append(f"Uninstalled {cog}") uninstall_s.append(f"Uninstalled {cog}")
self.logger.debug("Uninstalled %s", cog) self.logger.debug("Uninstalled %s", cog)
else: else:
uninstall_e.append(f"Failed to uninstall {cog}") uninstall_e.append(f"Failed to uninstall {cog}")
self.logger.warning("Failed to uninstall %s", cog) self.logger.warning("Failed to uninstall %s", cog)
await downloader._remove_from_installed(cog_modules) await downloader._remove_from_installed(
cog_modules
)
for cog in cogs: for cog in cogs:
cog_name = cog["name"] cog_name = cog["name"]
@ -209,15 +236,25 @@ class Backup(commands.Cog):
if cog_name == "backup" and "cswimr/SeaCogs" in url: if cog_name == "backup" and "cswimr/SeaCogs" in url:
continue continue
async with repository.checkout(commit, exit_to_rev=repository.branch): async with repository.checkout(
cogs_c, message = await downloader._filter_incorrect_cogs_by_names(repository, [cog_name]) commit, exit_to_rev=repository.branch
):
cogs_c, message = (
await downloader._filter_incorrect_cogs_by_names(
repository, [cog_name]
)
)
if not cogs_c: if not cogs_c:
install_e.append(message) install_e.append(message)
self.logger.error(message) self.logger.error(message)
continue continue
failed_reqs = await downloader._install_requirements(cogs_c) failed_reqs = await downloader._install_requirements(
cogs_c
)
if failed_reqs: if failed_reqs:
install_e.append(f"Failed to install {cog_name} due to missing requirements: {failed_reqs}") install_e.append(
f"Failed to install {cog_name} due to missing requirements: {failed_reqs}"
)
self.logger.error( self.logger.error(
"Failed to install %s due to missing requirements: %s", "Failed to install %s due to missing requirements: %s",
cog_name, cog_name,
@ -225,37 +262,51 @@ class Backup(commands.Cog):
) )
continue continue
installed_cogs, failed_cogs = await downloader._install_cogs(cogs_c) installed_cogs, failed_cogs = await downloader._install_cogs(
cogs_c
)
if repository.available_libraries: if repository.available_libraries:
installed_libs, failed_libs = await repository.install_libraries( installed_libs, failed_libs = (
target_dir=downloader.SHAREDLIB_PATH, await repository.install_libraries(
req_target_dir=downloader.LIB_PATH, target_dir=downloader.SHAREDLIB_PATH,
req_target_dir=downloader.LIB_PATH,
)
) )
else: else:
installed_libs = None installed_libs = None
failed_libs = None failed_libs = None
if cog_pinned: if cog_pinned:
for cog in installed_cogs: # noqa: PLW2901 for cog in installed_cogs:
cog.pinned = True cog.pinned = True
await downloader._save_to_installed(installed_cogs + installed_libs if installed_libs else installed_cogs) await downloader._save_to_installed(
installed_cogs + installed_libs
if installed_libs
else installed_cogs
)
if installed_cogs: if installed_cogs:
installed_cog_name = installed_cogs[0].name installed_cog_name = installed_cogs[0].name
install_s.append(f"Installed {installed_cog_name}") install_s.append(f"Installed {installed_cog_name}")
self.logger.debug("Installed %s", installed_cog_name) self.logger.debug("Installed %s", installed_cog_name)
if installed_libs: if installed_libs:
for lib in installed_libs: for lib in installed_libs:
install_s.append(f"Installed {lib.name} required for {cog_name}") install_s.append(
self.logger.debug("Installed %s required for %s", lib.name, cog_name) f"Installed {lib.name} required for {cog_name}"
)
self.logger.debug(
"Installed %s required for %s", lib.name, cog_name
)
if failed_cogs: if failed_cogs:
failed_cog_name = failed_cogs[0].name failed_cog_name = failed_cogs[0].name
install_e.append(f"Failed to install {failed_cog_name}") install_e.append(f"Failed to install {failed_cog_name}")
self.logger.error("Failed to install %s", failed_cog_name) self.logger.error("Failed to install %s", failed_cog_name)
if failed_libs: if failed_libs:
for lib in failed_libs: for lib in failed_libs:
install_e.append(f"Failed to install {lib.name} required for {cog_name}") install_e.append(
f"Failed to install {lib.name} required for {cog_name}"
)
self.logger.error( self.logger.error(
"Failed to install %s required for %s", "Failed to install %s required for %s",
lib.name, lib.name,

View file

@ -1,22 +1,15 @@
{ {
"$schema": "https://raw.githubusercontent.com/Cog-Creators/Red-DiscordBot/refs/heads/V3/develop/schema/red_cog_repo.schema.json", "author" : ["cswimr"],
"author": [ "install_msg" : "Thank you for installing Backup!\nYou can find the source code of this cog [here](https://coastalcommits.com/cswimr/SeaCogs).",
"cswimr" "name" : "Backup",
], "short" : "A utility to make reinstalling repositories and cogs after migrating the bot far easier.",
"install_msg": "Thank you for installing Backup!\nYou can find the source code of this cog [here](https://coastalcommits.com/cswimr/SeaCogs).", "description" : "A utility to make reinstalling repositories and cogs after migrating the bot far easier.",
"name": "Backup", "end_user_data_statement" : "This cog does not store end user data.",
"short": "A utility to make reinstalling repositories and cogs after migrating the bot far easier.",
"description": "A utility to make reinstalling repositories and cogs after migrating the bot far easier.",
"end_user_data_statement": "This cog does not store end user data.",
"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.13",
"min_python_version": [ "min_python_version": [3, 9, 0],
3,
9,
0
],
"tags": [ "tags": [
"utility", "utility",
"backup", "backup",

View file

@ -6,7 +6,6 @@
# |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_| # |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_|
import random import random
from asyncio import create_task
from io import BytesIO from io import BytesIO
import aiohttp import aiohttp
@ -27,21 +26,20 @@ class Bible(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.1"
__documentation__ = "https://seacogs.coastalcommits.com/pterodactyl/" __documentation__ = "https://seacogs.coastalcommits.com/pterodactyl/"
def __init__(self, bot: Red): def __init__(self, bot: Red):
super().__init__() super().__init__()
self.bot = bot self.bot = bot
self.session = aiohttp.ClientSession() self.session = aiohttp.ClientSession()
self.config = Config.get_conf(self, identifier=481923957134912, force_registration=True) self.config = Config.get_conf(
self, identifier=481923957134912, force_registration=True
)
self.logger = getLogger("red.SeaCogs.Bible") self.logger = getLogger("red.SeaCogs.Bible")
self.config.register_global(bible="de4e12af7f28f599-02") self.config.register_global(bible="de4e12af7f28f599-02")
self.config.register_user(bible=None) self.config.register_user(bible=None)
async def cog_unload(self):
create_task(self.session.close())
def format_help_for_context(self, ctx: commands.Context) -> str: def format_help_for_context(self, ctx: commands.Context) -> str:
pre_processed = super().format_help_for_context(ctx) or "" pre_processed = super().format_help_for_context(ctx) or ""
n = "\n" if "\n\n" not in pre_processed else "" n = "\n" if "\n\n" not in pre_processed else ""
@ -53,13 +51,14 @@ class Bible(commands.Cog):
] ]
return "\n".join(text) return "\n".join(text)
def get_icon(self, color: Colour) -> File: def get_icon(self, color: Colour) -> File:
"""Get the docs.api.bible favicon with a given color.""" """Get the docs.api.bible favicon with a given color."""
image_path = data_manager.bundled_data_path(self) / "api.bible-logo.png" image_path = data_manager.bundled_data_path(self) / "api.bible-logo.png"
image = Image.open(image_path) image = Image.open(image_path)
image = image.convert("RGBA") image = image.convert("RGBA")
data = np.array(image) data = np.array(image)
red, green, blue, alpha = data.T # pylint: disable=unused-variable red, green, blue, alpha = data.T # pylint: disable=unused-variable
white_areas = (red == 255) & (blue == 255) & (green == 255) white_areas = (red == 255) & (blue == 255) & (green == 255)
data[..., :-1][white_areas.T] = color.to_rgb() data[..., :-1][white_areas.T] = color.to_rgb()
image = Image.fromarray(data) image = Image.fromarray(data)
@ -71,7 +70,9 @@ class Bible(commands.Cog):
async def translate_book_name(self, bible_id: str, book_name: str) -> str: async def translate_book_name(self, bible_id: str, book_name: str) -> str:
"""Translate a book name to a book ID.""" """Translate a book name to a book ID."""
book_name_list = [w.lower() if w.lower() == "of" else w.title() for w in book_name.split()] book_name_list = [
w.lower() if w.lower() == "of" else w.title() for w in book_name.split()
]
book_name = " ".join(book_name_list) book_name = " ".join(book_name_list)
books = await self._get_books(bible_id) books = await self._get_books(bible_id)
for book in books: for book in books:
@ -91,20 +92,20 @@ class Bible(commands.Cog):
response.status, response.status,
) )
if response.status == 401: if response.status == 401:
raise bible.errors.UnauthorizedError raise bible.errors.Unauthorized()
if response.status == 403: if response.status == 403:
raise bible.errors.BibleAccessError raise bible.errors.BibleAccessError()
if response.status == 503: if response.status == 503:
raise bible.errors.ServiceUnavailableError raise bible.errors.ServiceUnavailable()
return Version( return Version(
bible_id=bible_id, bible_id,
abbreviation=data["data"]["abbreviation"], data["data"]["abbreviation"],
language=data["data"]["language"]["name"], data["data"]["language"]["name"],
abbreviation_local=data["data"]["abbreviationLocal"], data["data"]["abbreviationLocal"],
language_local=data["data"]["language"]["nameLocal"], data["data"]["language"]["nameLocal"],
description=data["data"]["description"], data["data"]["description"],
description_local=data["data"]["descriptionLocal"], data["data"]["descriptionLocal"],
version_copyright=data["data"]["copyright"], data["data"]["copyright"],
) )
async def _get_passage( async def _get_passage(
@ -135,17 +136,16 @@ class Bible(commands.Cog):
response.status, response.status,
) )
if response.status == 400: if response.status == 400:
raise bible.errors.InexplicableError raise bible.errors.InexplicableError()
if response.status == 401: if response.status == 401:
raise bible.errors.UnauthorizedError raise bible.errors.Unauthorized()
if response.status == 403: if response.status == 403:
raise bible.errors.BibleAccessError raise bible.errors.BibleAccessError()
if response.status == 404: if response.status == 404:
raise bible.errors.NotFoundError raise bible.errors.NotFound()
if response.status == 503: if response.status == 503:
raise bible.errors.ServiceUnavailableError raise bible.errors.ServiceUnavailable()
assert self.bot.user is not None # bot will always be logged in
fums_url = "https://fums.api.bible/f3" fums_url = "https://fums.api.bible/f3"
fums_params = { fums_params = {
"t": data["meta"]["fumsToken"], "t": data["meta"]["fumsToken"],
@ -177,11 +177,11 @@ class Bible(commands.Cog):
response.status, response.status,
) )
if response.status == 401: if response.status == 401:
raise bible.errors.UnauthorizedError raise bible.errors.Unauthorized()
if response.status == 403: if response.status == 403:
raise bible.errors.BibleAccessError raise bible.errors.BibleAccessError()
if response.status == 503: if response.status == 503:
raise bible.errors.ServiceUnavailableError raise bible.errors.ServiceUnavailable()
return data["data"] return data["data"]
async def _get_chapters(self, bible_id: str, book_id: str) -> dict: async def _get_chapters(self, bible_id: str, book_id: str) -> dict:
@ -196,11 +196,11 @@ class Bible(commands.Cog):
response.status, response.status,
) )
if response.status == 401: if response.status == 401:
raise bible.errors.UnauthorizedError raise bible.errors.Unauthorized()
if response.status == 403: if response.status == 403:
raise bible.errors.BibleAccessError raise bible.errors.BibleAccessError()
if response.status == 503: if response.status == 503:
raise bible.errors.ServiceUnavailableError raise bible.errors.ServiceUnavailable()
return data["data"] return data["data"]
async def _get_verses(self, bible_id: str, book_id: str, chapter: int) -> dict: async def _get_verses(self, bible_id: str, book_id: str, chapter: int) -> dict:
@ -215,11 +215,11 @@ class Bible(commands.Cog):
response.status, response.status,
) )
if response.status == 401: if response.status == 401:
raise bible.errors.UnauthorizedError raise bible.errors.Unauthorized()
if response.status == 403: if response.status == 403:
raise bible.errors.BibleAccessError raise bible.errors.BibleAccessError()
if response.status == 503: if response.status == 503:
raise bible.errors.ServiceUnavailableError raise bible.errors.ServiceUnavailable()
return data["data"] return data["data"]
@commands.group(autohelp=True) @commands.group(autohelp=True)
@ -247,34 +247,41 @@ class Bible(commands.Cog):
from_verse, to_verse = passage.replace(":", ".").split("-") from_verse, to_verse = passage.replace(":", ".").split("-")
if "." not in to_verse: if "." not in to_verse:
to_verse = f"{from_verse.split('.')[0]}.{to_verse}" to_verse = f"{from_verse.split('.')[0]}.{to_verse}"
retrieved_passage = await self._get_passage(ctx, bible_id, f"{book_id}.{from_verse}-{book_id}.{to_verse}", True) passage = await self._get_passage(
ctx, bible_id, f"{book_id}.{from_verse}-{book_id}.{to_verse}", True
)
else: else:
retrieved_passage = await self._get_passage(ctx, bible_id, f"{book_id}.{passage.replace(':', '.')}", False) passage = await self._get_passage(
ctx, bible_id, f"{book_id}.{passage.replace(':', '.')}", False
)
except ( except (
bible.errors.BibleAccessError, bible.errors.BibleAccessError,
bible.errors.NotFoundError, bible.errors.NotFound,
bible.errors.InexplicableError, bible.errors.InexplicableError,
bible.errors.ServiceUnavailableError, bible.errors.ServiceUnavailable,
bible.errors.UnauthorizedError, bible.errors.Unauthorized,
) as e: ) as e:
await ctx.send(e.message) await ctx.send(e.message)
return return
if len(retrieved_passage["content"]) > 4096: if len(passage["content"]) > 4096:
await ctx.send("The passage is too long to send.") await ctx.send("The passage is too long to send.")
return return
if await ctx.embed_requested(): if await ctx.embed_requested():
icon = self.get_icon(await ctx.embed_color()) icon = self.get_icon(await ctx.embed_color())
embed = Embed( embed = Embed(
title=f"{retrieved_passage['reference']}", title=f"{passage['reference']}",
description=retrieved_passage["content"].replace("", ""), description=passage["content"].replace("", ""),
color=await ctx.embed_color(), color=await ctx.embed_color(),
) )
embed.set_footer(text=f"{ctx.prefix}bible passage - Powered by API.Bible - {version.abbreviation_local} ({version.language_local}, {version.description_local})", icon_url="attachment://icon.png") embed.set_footer(
text=f"{ctx.prefix}bible passage - Powered by API.Bible - {version.abbreviationLocal} ({version.languageLocal}, {version.descriptionLocal})",
icon_url="attachment://icon.png"
)
await ctx.send(embed=embed, file=icon) await ctx.send(embed=embed, file=icon)
else: else:
await ctx.send(f"## {retrieved_passage['reference']}\n{retrieved_passage['content']}") await ctx.send(f"## {passage['reference']}\n{passage['content']}")
@bible.command(name="random") @bible.command(name="random")
async def bible_random(self, ctx: commands.Context): async def bible_random(self, ctx: commands.Context):
@ -295,10 +302,10 @@ class Bible(commands.Cog):
passage = await self._get_passage(ctx, bible_id, verse, False) passage = await self._get_passage(ctx, bible_id, verse, False)
except ( except (
bible.errors.BibleAccessError, bible.errors.BibleAccessError,
bible.errors.NotFoundError, bible.errors.NotFound,
bible.errors.InexplicableError, bible.errors.InexplicableError,
bible.errors.ServiceUnavailableError, bible.errors.ServiceUnavailable,
bible.errors.UnauthorizedError, bible.errors.Unauthorized,
) as e: ) as e:
await ctx.send(e.message) await ctx.send(e.message)
return return
@ -310,7 +317,10 @@ class Bible(commands.Cog):
description=passage["content"].replace("", ""), description=passage["content"].replace("", ""),
color=await ctx.embed_color(), color=await ctx.embed_color(),
) )
embed.set_footer(text=f"{ctx.prefix}bible random - Powered by API.Bible - {version.abbreviation_local} ({version.language_local}, {version.description_local})", icon_url="attachment://icon.png") embed.set_footer(
text=f"{ctx.prefix}bible random - Powered by API.Bible - {version.abbreviationLocal} ({version.languageLocal}, {version.descriptionLocal})",
icon_url="attachment://icon.png"
)
await ctx.send(embed=embed, file=icon) await ctx.send(embed=embed, file=icon)
else: else:
await ctx.send(f"## {passage['reference']}\n{passage['content']}") await ctx.send(f"## {passage['reference']}\n{passage['content']}")

View file

@ -4,22 +4,26 @@ from redbot.core.utils.chat_formatting import error
class BibleAccessError(Exception): class BibleAccessError(Exception):
def __init__( def __init__(
self, self,
message: str = error("The provided API key cannot retrieve sections from the configured Bible. Please report this to the bot owner."), message: str = error(
"The provided API key cannot retrieve sections from the configured Bible. Please report this to the bot owner."
),
): ):
super().__init__(message) super().__init__(message)
self.message = message self.message = message
class UnauthorizedError(Exception): class Unauthorized(Exception):
def __init__( def __init__(
self, self,
message: str = error("The API key for API.Bible is missing or invalid. Please report this to the bot owner.\nIf you are the bot owner, please check the documentation [here](<https://seacogs.coastalcommits.com/bible/#setup>)."), message: str = error(
"The API key for API.Bible is missing or invalid. Please report this to the bot owner.\nIf you are the bot owner, please check the documentation [here](<https://seacogs.coastalcommits.com/bible/#setup>)."
),
): ):
super().__init__(message) super().__init__(message)
self.message = message self.message = message
class NotFoundError(Exception): class NotFound(Exception):
def __init__( def __init__(
self, self,
message: str = error("The requested passage was not found."), message: str = error("The requested passage was not found."),
@ -28,7 +32,7 @@ class NotFoundError(Exception):
self.message = message self.message = message
class ServiceUnavailableError(Exception): class ServiceUnavailable(Exception):
def __init__( def __init__(
self, self,
message: str = error("The API.Bible service is currently unavailable."), message: str = error("The API.Bible service is currently unavailable."),
@ -40,7 +44,9 @@ class ServiceUnavailableError(Exception):
class InexplicableError(Exception): class InexplicableError(Exception):
def __init__( def __init__(
self, self,
message: str = error("An inexplicable 'Bad Request' error occurred. This error happens occasionally with the API.Bible service. Please try again. If the error persists, please report this to the bot owner."), message: str = error(
"An inexplicable 'Bad Request' error occurred. This error happens occassionally with the API.Bible service. Please try again. If the error persists, please report this to the bot owner."
),
): ):
super().__init__(message) super().__init__(message)
self.message = message self.message = message

View file

@ -1,15 +1,18 @@
{ {
"$schema": "https://raw.githubusercontent.com/Cog-Creators/Red-DiscordBot/refs/heads/V3/develop/schema/red_cog_repo.schema.json", "author" : ["cswimr"],
"author": ["cswimr"], "install_msg" : "Thank you for installing Bible!\nThis cog requires setting an API key for API.Bible. Please read the [documentation](https://seacogs.coastalcommits.com/bible/#setup) for more information.\nYou can find the source code of this cog [here](https://coastalcommits.com/cswimr/SeaCogs).",
"install_msg": "Thank you for installing Bible!\nThis cog requires setting an API key for API.Bible. Please read the [documentation](https://seacogs.coastalcommits.com/bible/#setup) for more information.\nYou can find the source code of this cog [here](https://coastalcommits.com/cswimr/SeaCogs).", "name" : "Bible",
"name": "Bible", "short" : "Retrieve Bible verses from API.Bible.",
"short": "Retrieve Bible verses from API.Bible.", "description" : "Retrieve Bible verses from the API.Bible API. This cog requires an API.Bible api key.",
"description": "Retrieve Bible verses from the API.Bible API. This cog requires an API.Bible api key.", "end_user_data_statement" : "This cog does not store end user data, however it does send the following data to the API.Bible API:\n- The bot user's ID\n- The timestamp of the invoking message\n- The hashed user id of the invoking user",
"end_user_data_statement": "This cog does not store end user data, however it does send the following data to the API.Bible API:\n- The bot user's ID\n- The timestamp of the invoking message\n- The hashed user id of the invoking user",
"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, 10, 0],
"requirements": ["numpy", "pillow"], "requirements": ["numpy", "pillow"],
"tags": ["fun", "utility", "api"] "tags": [
"fun",
"utility",
"api"
]
} }

View file

@ -4,23 +4,23 @@ class Version:
bible_id, bible_id,
abbreviation, abbreviation,
language, language,
abbreviation_local, abbreviationLocal,
language_local, languageLocal,
description, description,
description_local, descriptionLocal,
version_copyright, version_copyright,
): ):
self.bible_id = bible_id self.bible_id = bible_id
self.abbreviation = abbreviation self.abbreviation = abbreviation
self.language = language self.language = language
self.abbreviation_local = abbreviation_local self.abbreviationLocal = abbreviationLocal
self.language_local = language_local self.languageLocal = languageLocal
self.description = description self.description = description
self.description_local = description_local self.descriptionLocal = descriptionLocal
self.copyright = version_copyright self.copyright = version_copyright
def __str__(self): def __str__(self):
return self.abbreviation_local return self.abbreviationLocal
def __repr__(self): def __repr__(self):
return f'bible.models.Version("{self.bible_id}", "{self.abbreviation}", "{self.language}", "{self.abbreviation_local}", "{self.language_local}", "{self.description}", "{self.description_local}", "{self.copyright}")' return f'bible.models.Version("{self.bible_id}", "{self.abbreviation}", "{self.language}", "{self.abbreviationLocal}", "{self.languageLocal}", "{self.description}", "{self.descriptionLocal}", "{self.copyright}")'

View file

@ -16,13 +16,13 @@ class EmojiInfo(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.0.3" __version__ = "1.0.1"
__documentation__ = "https://seacogs.coastalcommits.com/emojiinfo/" __documentation__ = "https://seacogs.coastalcommits.com/emojiinfo/"
def __init__(self, bot: Red) -> None: def __init__(self, bot: Red) -> None:
super().__init__() super().__init__()
self.bot: Red = bot self.bot: Red = bot
self.logger: RedTraceLogger = getLogger(name="red.SeaCogs.EmojiInfo") self.logger: RedTraceLogger = getLogger(name="red.SeaCogs.Emoji")
def format_help_for_context(self, ctx: commands.Context) -> str: def format_help_for_context(self, ctx: commands.Context) -> str:
pre_processed = super().format_help_for_context(ctx) or "" pre_processed = super().format_help_for_context(ctx) or ""
@ -35,12 +35,14 @@ class EmojiInfo(commands.Cog):
] ]
return "\n".join(text) return "\n".join(text)
async def fetch_twemoji(self, unicode_emoji) -> str: async def fetch_twemoji(self, unicode_emoji) -> str:
base_url = "https://cdn.jsdelivr.net/gh/jdecked/twemoji@latest/assets/72x72/" base_url = "https://cdn.jsdelivr.net/gh/jdecked/twemoji@latest/assets/72x72/"
emoji_codepoint = "-".join([hex(ord(char))[2:] for char in unicode_emoji]) emoji_codepoint = "-".join([hex(ord(char))[2:] for char in unicode_emoji])
segments = emoji_codepoint.split("-") segments = emoji_codepoint.split("-")
valid_segments = [seg for seg in segments if len(seg) >= 4] valid_segments = [seg for seg in segments if len(seg) >= 4]
return f"{base_url}{valid_segments[0]}.png" emoji_url = f"{base_url}{valid_segments[0]}.png"
return emoji_url
async def fetch_primary_color(self, emoji_url: str) -> discord.Color | None: async def fetch_primary_color(self, emoji_url: str) -> discord.Color | None:
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
@ -49,7 +51,8 @@ class EmojiInfo(commands.Cog):
return None return None
image = await response.read() image = await response.read()
dominant_color = ColorThief(io.BytesIO(image)).get_color(quality=1) dominant_color = ColorThief(io.BytesIO(image)).get_color(quality=1)
return discord.Color.from_rgb(*dominant_color) color = discord.Color.from_rgb(*dominant_color)
return color
async def get_emoji_info(self, emoji: PartialEmoji) -> tuple[str, str]: async def get_emoji_info(self, emoji: PartialEmoji) -> tuple[str, str]:
if emoji.is_unicode_emoji(): if emoji.is_unicode_emoji():
@ -69,51 +72,59 @@ class EmojiInfo(commands.Cog):
else: else:
emoji_id = "" emoji_id = ""
markdown = f"`{emoji}`" markdown = f"`{emoji}`"
name = f"{bold('Name:')} {emoji.aliases.pop(0) if emoji.aliases else emoji.name}\n" name = f"{bold('Name:')} {emoji.aliases.pop(0)}\n"
aliases = f"{bold('Aliases:')} {', '.join(emoji.aliases)}\n" if emoji.aliases else "" aliases = f"{bold('Aliases:')} {', '.join(emoji.aliases)}\n" if emoji.aliases else ""
group = f"{bold('Group:')} {emoji.group}\n" group = f"{bold('Group:')} {emoji.group}\n"
return (f"{name}{emoji_id}{bold('Native:')} {emoji.is_unicode_emoji()}\n{group}{aliases}{bold('Animated:')} {emoji.animated}\n{bold('Markdown:')} {markdown}\n{bold('URL:')} [Click Here]({emoji_url})"), emoji_url return (
f"{name}"
f"{emoji_id}"
f"{bold('Native:')} {emoji.is_unicode_emoji()}\n"
f"{group}"
f"{aliases}"
f"{bold('Animated:')} {emoji.animated}\n"
f"{bold('Markdown:')} {markdown}\n"
f"{bold('URL:')} [Click Here]({emoji_url})"
), emoji_url
@app_commands.command(name="emoji") @app_commands.command(name="emoji")
@app_commands.describe(emoji="What emoji would you like to get information on?", ephemeral="Would you like the response to be hidden?") @app_commands.describe(
emoji="What emoji would you like to get information on?",
ephemeral="Would you like the response to be hidden?"
)
async def emoji_slash(self, interaction: discord.Interaction, emoji: str, ephemeral: bool = True) -> None: async def emoji_slash(self, interaction: discord.Interaction, emoji: str, ephemeral: bool = True) -> None:
"""Retrieve information about an emoji.""" """Retrieve information about an emoji."""
await interaction.response.defer(ephemeral=ephemeral) await interaction.response.defer(ephemeral=ephemeral)
try: try:
retrieved_emoji: PartialEmoji = PartialEmoji.from_str(self, value=emoji) emoji: PartialEmoji = PartialEmoji.from_str(self, value=emoji)
string, emoji_url = await self.get_emoji_info(retrieved_emoji) string, emoji_url, = await self.get_emoji_info(emoji)
self.logger.verbose(f"Emoji:\n{string}") self.logger.verbose(f"Emoji:\n{string}")
except (IndexError, UnboundLocalError): except (IndexError, UnboundLocalError):
return await interaction.followup.send("Please provide a valid emoji!") return await interaction.followup.send("Please provide a valid emoji!")
assert isinstance(interaction.channel, discord.TextChannel)
if await self.bot.embed_requested(channel=interaction.channel): if await self.bot.embed_requested(channel=interaction.channel):
embed = discord.Embed(title="Emoji Information", description=string, color=await self.fetch_primary_color(emoji_url) or await self.bot.get_embed_color(interaction.channel)) embed = embed = discord.Embed(title="Emoji Information", description=string, color = await self.fetch_primary_color(emoji_url) or await self.bot.get_embed_color(interaction.channel))
embed.set_thumbnail(url=emoji_url) embed.set_thumbnail(url=emoji_url)
await interaction.followup.send(embed=embed) await interaction.followup.send(embed=embed)
return None else:
await interaction.followup.send(content=string) await interaction.followup.send(content=string)
return None
@commands.command(name="emoji") @commands.command(name="emoji")
async def emoji(self, ctx: commands.Context, *, emoji: str) -> None: async def emoji(self, ctx: commands.Context, *, emoji: str) -> None:
"""Retrieve information about an emoji.""" """Retrieve information about an emoji."""
try: try:
retrieved_emoji: PartialEmoji = PartialEmoji.from_str(self, value=emoji) emoji: PartialEmoji = PartialEmoji.from_str(self, value=emoji)
string, emoji_url = await self.get_emoji_info(retrieved_emoji) string, emoji_url, = await self.get_emoji_info(emoji)
self.logger.verbose(f"Emoji:\n{string}") self.logger.verbose(f"Emoji:\n{string}")
except (IndexError, UnboundLocalError): except (IndexError, UnboundLocalError):
await ctx.send("Please provide a valid emoji!") return await ctx.send("Please provide a valid emoji!")
return
if await ctx.embed_requested(): if await ctx.embed_requested():
embed = discord.Embed(title="Emoji Information", description=string, color=await self.fetch_primary_color(emoji_url) or await ctx.embed_color()) embed = embed = discord.Embed(title="Emoji Information", description=string, color = await self.fetch_primary_color(emoji_url) or await ctx.embed_color)
embed.set_thumbnail(url=emoji_url) embed.set_thumbnail(url=emoji_url)
await ctx.send(embed=embed) await ctx.send(embed=embed)
return else:
await ctx.send(content=string) await ctx.send(content=string)
return

View file

@ -1,15 +1,16 @@
{ {
"$schema": "https://raw.githubusercontent.com/Cog-Creators/Red-DiscordBot/refs/heads/V3/develop/schema/red_cog_repo.schema.json", "author" : ["cswimr"],
"author": ["cswimr"], "install_msg" : "Thank you for installing Emoji!",
"install_msg": "Thank you for installing Emoji!", "name" : "Emoji",
"name": "Emoji", "short" : "Retrieve information about emojis.",
"short": "Retrieve information about emojis.", "description" : "Retrieve information about emojis.",
"description": "Retrieve information about emojis.", "end_user_data_statement" : "This cog does not store end user data.",
"end_user_data_statement": "This cog does not store end user data.",
"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, 10, 0],
"requirements": ["colorthief"], "requirements": ["colorthief"],
"tags": ["utility"] "tags": [
"utility"
]
} }

View file

@ -39,7 +39,7 @@ class PartialEmoji(discord.PartialEmoji):
The group name of the emoji if it is a native emoji. The group name of the emoji if it is a native emoji.
""" """
def __init__(self, *, name: str, animated: bool = False, id: int | None = None, group: str | None = None, aliases: list | None = None) -> None: # pylint: disable=redefined-builtin # noqa: A002 def __init__(self, *, name: str, animated: bool = False, id: int | None = None, group: str | None = None, aliases: list | None = None) -> None: # pylint: disable=redefined-builtin
super().__init__(name=name, animated=animated, id=id) super().__init__(name=name, animated=animated, id=id)
self.group = group self.group = group
self.aliases = aliases self.aliases = aliases
@ -72,12 +72,12 @@ class PartialEmoji(discord.PartialEmoji):
match = cls._CUSTOM_EMOJI_RE.match(value) match = cls._CUSTOM_EMOJI_RE.match(value)
if match is not None: if match is not None:
groups = match.groupdict() groups = match.groupdict()
animated = bool(groups["animated"]) animated = bool(groups['animated'])
emoji_id = int(groups["id"]) emoji_id = int(groups['id'])
name = groups["name"] name = groups['name']
return cls(name=name, animated=animated, id=emoji_id) return cls(name=name, animated=animated, id=emoji_id)
path = data_manager.bundled_data_path(coginstance) / "emojis.json" path: data_manager.Path = data_manager.bundled_data_path(coginstance) / "emojis.json"
with open(path, "r", encoding="UTF-8") as file: with open(path, "r", encoding="UTF-8") as file:
emojis: dict = json.load(file) emojis: dict = json.load(file)
emoji_aliases = [] emoji_aliases = []

25
flake.lock generated
View file

@ -1,25 +0,0 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1738680400,
"narHash": "sha256-ooLh+XW8jfa+91F1nhf9OF7qhuA/y1ChLx6lXDNeY5U=",
"rev": "799ba5bffed04ced7067a91798353d360788b30d",
"revCount": 747653,
"type": "tarball",
"url": "https://api.flakehub.com/f/pinned/NixOS/nixpkgs/0.1.747653%2Brev-799ba5bffed04ced7067a91798353d360788b30d/0194d302-29da-7009-8f43-5b8a58825954/source.tar.gz"
},
"original": {
"type": "tarball",
"url": "https://flakehub.com/f/NixOS/nixpkgs/0.1.%2A.tar.gz"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}

View file

@ -1,72 +0,0 @@
{
description = "SeaCogs Nix Flake";
inputs.nixpkgs.url = "https://flakehub.com/f/NixOS/nixpkgs/0.1.*.tar.gz";
outputs =
{ self, nixpkgs }:
let
supportedSystems = [
"x86_64-linux"
"aarch64-linux"
"x86_64-darwin"
"aarch64-darwin"
];
forEachSupportedSystem =
f:
nixpkgs.lib.genAttrs supportedSystems (
system:
f {
pkgs = import nixpkgs { inherit system; };
lib = nixpkgs.lib;
}
);
in
{
devShells = forEachSupportedSystem (
{ pkgs, lib }:
let
myPython = pkgs.python311;
lib-path =
with pkgs;
lib.makeLibraryPath [
stdenv.cc.cc
# Red-DiscordBot dependencies
libffi
libsodium
# PyLav dependency
libaio
# Material for MkDocs dependency
cairo
];
in
{
default = pkgs.mkShell {
lib-path = lib-path;
packages = with pkgs; [
myPython
uv
ruff # the ruff pip package installs a dynamically linked binary that cannot run on NixOS
forgejo-runner
# Red-DiscordBot dependencies
git
jdk17
# Material for MkDocs dependencies
pngquant
# SeaCogs dependencies
dig
];
shellHook = # bash
''
export "LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${lib-path}"
export "UV_PYTHON_PREFERENCE=only-system"
export "UV_PYTHON_DOWNLOADS=never"
uv sync --all-groups
source ./.venv/bin/activate
export "PYTHONPATH=`pwd`/.venv/${myPython.sitePackages}/:$PYTHONPATH"
export "PATH=${pkgs.ruff}/bin:$PATH"
'';
};
}
);
};
}

View file

@ -1,5 +0,0 @@
from .hotreload import HotReload
async def setup(bot):
await bot.add_cog(HotReload(bot))

View file

@ -1,192 +0,0 @@
import py_compile
from asyncio import run_coroutine_threadsafe
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import Generator, List, Sequence
import discord
from red_commons.logging import RedTraceLogger, getLogger
from redbot.core import Config, checks, commands
from redbot.core.bot import Red
from redbot.core.core_commands import CoreLogic
from redbot.core.utils.chat_formatting import bold, box, humanize_list
from typing_extensions import override
from watchdog.events import FileSystemEvent, FileSystemMovedEvent, RegexMatchingEventHandler
from watchdog.observers import Observer
from watchdog.observers.api import BaseObserver
class HotReload(commands.Cog):
"""Automatically reload cogs in local cog paths on file change."""
__author__ = ["[cswimr](https://www.coastalcommits.com/cswimr)"]
__git__ = "https://www.coastalcommits.com/cswimr/SeaCogs"
__version__ = "1.4.2"
__documentation__ = "https://seacogs.coastalcommits.com/hotreload/"
def __init__(self, bot: Red) -> None:
super().__init__()
self.bot: Red = bot
self.config: Config = Config.get_conf(cog_instance=self, identifier=294518358420750336, force_registration=True)
self.logger: RedTraceLogger = getLogger(name="red.SeaCogs.HotReload")
self.observers: List[BaseObserver] = []
self.config.register_global(notify_channel=None, compile_before_reload=False)
watchdog_loggers = [getLogger(name="watchdog.observers.inotify_buffer")]
for watchdog_logger in watchdog_loggers:
watchdog_logger.setLevel("INFO") # SHUT UP!!!!
@override
async def cog_load(self) -> None:
"""Start the observer when the cog is loaded."""
_ = self.bot.loop.create_task(self.start_observer())
@override
async def cog_unload(self) -> None:
"""Stop the observer when the cog is unloaded."""
for observer in self.observers:
observer.stop()
observer.join()
self.logger.info("Stopped observer. No longer watching for file changes.")
@override
def format_help_for_context(self, ctx: commands.Context) -> str:
pre_processed = super().format_help_for_context(ctx) or ""
n = "\n" if "\n\n" not in pre_processed else ""
text = [
f"{pre_processed}{n}",
f"{bold('Cog Version:')} [{self.__version__}]({self.__git__})",
f"{bold('Author:')} {humanize_list(self.__author__)}",
f"{bold('Documentation:')} {self.__documentation__}",
]
return "\n".join(text)
# pylint: disable=protected-access
async def get_paths(self) -> Generator[Path, None, None]:
"""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_paths = await cog_manager.user_defined_paths()
return (Path(path) for path in cog_paths)
async def start_observer(self) -> None:
"""Start the observer to watch for file changes."""
self.observers.append(Observer())
paths = await self.get_paths()
is_first = True
for observer in self.observers:
if not is_first:
observer.stop()
observer.join()
self.logger.debug("Stopped hanging observer.")
continue
for path in paths:
if not path.exists():
self.logger.warning("Path %s does not exist. Skipping.", path)
continue
self.logger.debug("Adding observer schedule for path %s.", path)
observer.schedule(event_handler=HotReloadHandler(cog=self, path=path), path=str(path), recursive=True)
observer.start()
self.logger.info("Started observer. Watching for file changes.")
is_first = False
@checks.is_owner()
@commands.group(name="hotreload")
async def hotreload_group(self, ctx: commands.Context) -> None:
"""HotReload configuration commands."""
@hotreload_group.command(name="notifychannel")
async def hotreload_notifychannel(self, ctx: commands.Context, channel: discord.TextChannel) -> None:
"""Set the channel to send notifications to."""
await self.config.notify_channel.set(channel.id)
await ctx.send(f"Notifications will be sent to {channel.mention}.")
@hotreload_group.command(name="compile") # type: ignore
async def hotreload_compile(self, ctx: commands.Context, compile_before_reload: bool) -> None:
"""Set whether to compile modified files before reloading."""
await self.config.compile_before_reload.set(compile_before_reload)
await ctx.send(f"I {'will' if compile_before_reload else 'will not'} compile modified files before hotreloading cogs.")
@hotreload_group.command(name="list") # type: ignore
async def hotreload_list(self, ctx: commands.Context) -> None:
"""List the currently active observers."""
if not self.observers:
await ctx.send("No observers are currently active.")
return
await ctx.send(f"Currently active observers (If there are more than one of these, report an issue): {box(humanize_list([str(o) for o in self.observers], style='unit'))}")
class HotReloadHandler(RegexMatchingEventHandler):
"""Handler for file changes."""
def __init__(self, cog: HotReload, path: Path) -> None:
super().__init__(regexes=[r".*\.py$"])
self.cog: HotReload = cog
self.path: Path = path
self.logger: RedTraceLogger = getLogger(name="red.SeaCogs.HotReload.Observer")
def on_any_event(self, event: FileSystemEvent) -> None:
"""Handle filesystem events."""
if event.is_directory:
return
allowed_events = ("moved", "deleted", "created", "modified")
if event.event_type not in allowed_events:
return
relative_src_path = Path(str(event.src_path)).relative_to(self.path)
src_package_name = relative_src_path.parts[0]
cogs_to_reload = [src_package_name]
if isinstance(event, FileSystemMovedEvent):
dest = f" to {event.dest_path}"
relative_dest_path = Path(str(event.dest_path)).relative_to(self.path)
dest_package_name = relative_dest_path.parts[0]
if dest_package_name != src_package_name:
cogs_to_reload.append(dest_package_name)
else:
dest = ""
self.logger.info("File %s has been %s%s.", event.src_path, event.event_type, dest)
run_coroutine_threadsafe(
coro=self.reload_cogs(
cog_names=cogs_to_reload,
paths=[Path(str(p)) for p in (event.src_path, getattr(event, "dest_path", None)) if p],
),
loop=self.cog.bot.loop,
)
# pylint: disable=protected-access
async def reload_cogs(self, cog_names: Sequence[str], paths: Sequence[Path]) -> None:
"""Reload modified cogs."""
if not self.compile_modified_files(cog_names, paths):
return
core_logic = CoreLogic(bot=self.cog.bot)
self.logger.info("Reloading cogs: %s", humanize_list(cog_names, style="unit"))
await core_logic._reload(pkg_names=cog_names) # noqa: SLF001 # We have to use this private method because there is no public API to reload other cogs
self.logger.info("Reloaded cogs: %s", humanize_list(cog_names, style="unit"))
channel = self.cog.bot.get_channel(await self.cog.config.notify_channel())
if channel and isinstance(channel, discord.TextChannel):
await channel.send(f"Reloaded cogs: {humanize_list(cog_names, style='unit')}")
def compile_modified_files(self, cog_names: Sequence[str], paths: Sequence[Path]) -> bool:
"""Compile modified files to ensure they are valid Python files."""
for path in paths:
if not path.exists() or path.suffix != ".py":
self.logger.debug("Path %s does not exist or does not point to a Python file. Skipping compilation step.", path)
continue
try:
with NamedTemporaryFile() as temp_file:
self.logger.debug("Attempting to compile %s", path)
py_compile.compile(file=str(path), cfile=temp_file.name, doraise=True)
self.logger.debug("Successfully compiled %s", path)
except py_compile.PyCompileError as e:
e.__suppress_context__ = True
self.logger.exception("%s failed to compile. Not reloading cogs %s.", path, humanize_list(cog_names, style="unit"))
return False
except OSError:
self.logger.exception("Failed to create tempfile for compilation step. Skipping.")
return True

View file

@ -1,15 +0,0 @@
{
"$schema": "https://raw.githubusercontent.com/Cog-Creators/Red-DiscordBot/refs/heads/V3/develop/schema/red_cog_repo.schema.json",
"author": ["cswimr"],
"install_msg": "Thank you for installing HotReload! Please see the [documentation](https://seacogs.coastalcommits.com/hotreload) to get started.",
"name": "HotReload",
"short": "Automatically reload cogs in local cog paths on file change.",
"description": "Automatically reload cogs in local cog paths on file change.",
"end_user_data_statement": "This cog does not store end user data.",
"hidden": false,
"disabled": false,
"min_bot_version": "3.5.0",
"min_python_version": [3, 8, 0],
"requirements": ["watchdog"],
"tags": ["utility", "development"]
}

View file

@ -1,8 +1,9 @@
{ {
"$schema": "https://raw.githubusercontent.com/Cog-Creators/Red-DiscordBot/V3/develop/schema/red_cog_repo.schema.json", "author": [
"author": ["cswimr"], "cswimr"
"install_msg": "Thanks for installing my repo!\n\nIf you have any issues with any of the cogs, please create an issue [here](https://coastalcommits.com/cswimr/SeaCogs/issues) or join my [Discord Server](https://discord.gg/eMUMe77Yb8 ).", ],
"index_name": "sea-cogs", "install_msg": "Thanks for installing my repo!\n\nIf you have any issues with any of the cogs, please create an issue [here](https://coastalcommits.com/cswimr/SeaCogs/issues) or join my [Discord Server](https://discord.gg/eMUMe77Yb8 ).",
"short": "Various cogs for Red, by cswimr", "index_name": "sea-cogs",
"description": "Various cogs for Red, by cswimr" "short": "Various cogs for Red, by cswimr",
"description": "Various cogs for Red, by cswimr"
} }

View file

@ -1,8 +1,8 @@
site_name: SeaCogs Documentation site_name: SeaCogs Documentation
site_url: !ENV [SITE_URL, "https://seacogs.coastalcommits.com"] site_url: !ENV [SITE_URL, 'https://seacogs.coastalcommits.com']
repo_name: CoastalCommits repo_name: CoastalCommits
repo_url: https://coastalcommits.com/cswimr/SeaCogs repo_url: https://coastalcommits.com/cswimr/SeaCogs
edit_uri: !ENV [EDIT_URI, "src/branch/main/.docs"] edit_uri: !ENV [EDIT_URI, 'src/branch/main/.docs']
copyright: Copyright &copy; 2023-2024, cswimr copyright: Copyright &copy; 2023-2024, cswimr
docs_dir: .docs docs_dir: .docs
@ -12,21 +12,20 @@ site_description: Documentation for my Red-DiscordBot Cogs.
nav: nav:
- Home: index.md - Home: index.md
- Aurora: - Aurora:
- aurora/index.md - aurora/index.md
- Moderation Commands: aurora/moderation-commands.md - Moderation Commands: aurora/moderation-commands.md
- Case Commands: aurora/case-commands.md - Case Commands: aurora/case-commands.md
- Configuration: aurora/configuration.md - Configuration: aurora/configuration.md
- Bible: bible.md - Bible: bible.md
- Backup: backup.md - Backup: backup.md
- EmojiInfo: emojiinfo.md - EmojiInfo: emojiinfo.md
- HotReload: hotreload.md
- Nerdify: nerdify.md - Nerdify: nerdify.md
- Pterodactyl: - Pterodactyl:
- pterodactyl/index.md - pterodactyl/index.md
- Installing Red: pterodactyl/installing-red.md - Installing Red: pterodactyl/installing-red.md
- Getting Started: pterodactyl/getting-started.md - Getting Started: pterodactyl/getting-started.md
- Configuration: pterodactyl/configuration.md - Configuration: pterodactyl/configuration.md
- Regex Examples: pterodactyl/regex.md - Regex Examples: pterodactyl/regex.md
plugins: plugins:
- git-authors - git-authors
@ -73,7 +72,7 @@ markdown_extensions:
theme: theme:
name: material name: material
palette: palette:
- media: "(prefers-color-scheme: light)" - media: '(prefers-color-scheme: light)'
scheme: default scheme: default
primary: white primary: white
accent: light blue accent: light blue
@ -81,7 +80,7 @@ theme:
icon: material/toggle-switch icon: material/toggle-switch
name: Switch to dark mode name: Switch to dark mode
- media: "(prefers-color-scheme: dark)" - media: '(prefers-color-scheme: dark)'
scheme: slate scheme: slate
primary: black primary: black
accent: light blue accent: light blue

View file

@ -1,14 +1,17 @@
{ {
"$schema": "https://raw.githubusercontent.com/Cog-Creators/Red-DiscordBot/refs/heads/V3/develop/schema/red_cog_repo.schema.json", "author" : ["cswimr"],
"author": ["cswimr"], "install_msg" : "Thank you for installing Nerdify!\nYou can find the source code of this cog [here](https://coastalcommits.com/cswimr/SeaCogs). Based off of PhasecoreX's [UwU](<https://github.com/PhasecoreX/PCXCogs/tree/master/uwu>) cog.",
"install_msg": "Thank you for installing Nerdify!\nYou can find the source code of this cog [here](https://coastalcommits.com/cswimr/SeaCogs). Based off of PhasecoreX's [UwU](<https://github.com/PhasecoreX/PCXCogs/tree/master/uwu>) cog.", "name" : "Nerdify",
"name": "Nerdify", "short" : "Nerdify your text!",
"short": "Nerdify your text!", "description" : "Nerdify your text!",
"description": "Nerdify your text!", "end_user_data_statement" : "This cog does not store end user data.",
"end_user_data_statement": "This cog does not store end user data.",
"hidden": false, "hidden": false,
"disabled": false, "disabled": false,
"min_bot_version": "3.5.0", "min_bot_version": "3.5.0",
"min_python_version": [3, 8, 0], "min_python_version": [3, 8, 0],
"tags": ["fun", "text", "meme"] "tags": [
"fun",
"text",
"meme"
]
} }

View file

@ -37,20 +37,16 @@ class Nerdify(commands.Cog):
] ]
return "\n".join(text) return "\n".join(text)
@commands.command(aliases=["nerd"]) @commands.command(aliases=["nerd"])
async def nerdify( async def nerdify(
self, self, ctx: commands.Context, *, text: Optional[str] = None
ctx: commands.Context,
*,
text: Optional[str] = None,
) -> None: ) -> None:
"""Nerdify the replied to message, previous message, or your own text.""" """Nerdify the replied to message, previous message, or your own text."""
if not text: if not text:
if hasattr(ctx.message, "reference") and ctx.message.reference: if hasattr(ctx.message, "reference") and ctx.message.reference:
with suppress( with suppress(
discord.Forbidden, discord.Forbidden, discord.NotFound, discord.HTTPException
discord.NotFound,
discord.HTTPException,
): ):
message_id = ctx.message.reference.message_id message_id = ctx.message.reference.message_id
if message_id: if message_id:
@ -66,9 +62,7 @@ class Nerdify(commands.Cog):
ctx.channel, ctx.channel,
self.nerdify_text(text), self.nerdify_text(text),
allowed_mentions=discord.AllowedMentions( allowed_mentions=discord.AllowedMentions(
everyone=False, everyone=False, users=False, roles=False
users=False,
roles=False,
), ),
) )
@ -83,10 +77,7 @@ class Nerdify(commands.Cog):
return f'"{text}" 🤓' return f'"{text}" 🤓'
async def type_message( async def type_message(
self, self, destination: discord.abc.Messageable, content: str, **kwargs: Any
destination: discord.abc.Messageable,
content: str,
**kwargs: Any,
) -> Union[discord.Message, None]: ) -> Union[discord.Message, None]:
"""Simulate typing and sending a message to a destination. """Simulate typing and sending a message to a destination.

3749
poetry.lock generated Normal file

File diff suppressed because it is too large Load diff

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

@ -1,18 +1,19 @@
{ {
"$schema": "https://raw.githubusercontent.com/Cog-Creators/Red-DiscordBot/refs/heads/V3/develop/schema/red_cog_repo.schema.json", "author" : ["cswimr"],
"author": ["cswimr"], "install_msg" : "Thank you for installing Pterodactyl!\nYou can find the source code of this cog [here](https://coastalcommits.com/cswimr/SeaCogs).\nDocumentation can be found [here](https://seacogs.coastalcommits.com/pterodactyl ).",
"install_msg": "Thank you for installing Pterodactyl!\nYou can find the source code of this cog [here](https://coastalcommits.com/cswimr/SeaCogs).\nDocumentation can be found [here](https://seacogs.coastalcommits.com/pterodactyl ).", "name" : "Pterodactyl",
"name": "Pterodactyl", "short" : "Interface with Pterodactyl through websockets.",
"short": "Interface with Pterodactyl through websockets.", "description" : "Interface with Pterodactyl through websockets.",
"description": "Interface with Pterodactyl through websockets.", "end_user_data_statement" : "This cog does not store end user data.",
"end_user_data_statement": "This cog does not store end user data.",
"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", "tags": [
"websockets" "pterodactyl",
], "minecraft",
"tags": ["pterodactyl", "minecraft", "server", "management"] "server",
"management"
]
} }

View file

@ -1,8 +1,8 @@
from red_commons import logging from red_commons import logging
from red_commons.logging import getLogger from red_commons.logging import getLogger
logger = getLogger("red.SeaCogs.Pterodactyl") logger = getLogger('red.SeaCogs.Pterodactyl')
websocket_logger = getLogger("red.SeaCogs.Pterodactyl.Websocket") websocket_logger = getLogger('red.SeaCogs.Pterodactyl.websocket')
if logger.level >= logging.VERBOSE: if logger.level >= logging.VERBOSE:
websocket_logger.setLevel(logging.logging.INFO) websocket_logger.setLevel(logging.logging.INFO)
elif logger.level < logging.VERBOSE: elif logger.level < logging.VERBOSE:

View file

@ -2,17 +2,9 @@ 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()
if response["online"]: if response['online']:
return (True, response) return (True, response)
return (False, response) return (False, response)

View file

@ -1,6 +1,6 @@
import asyncio import asyncio
import json import json
from typing import AsyncIterable, Iterable, Mapping, Optional, Tuple, Union from typing import Mapping, Optional, Tuple, Union
import discord import discord
import websockets import websockets
@ -9,9 +9,8 @@ from pydactyl import PterodactylClient
from redbot.core import app_commands, commands from redbot.core import app_commands, commands
from redbot.core.app_commands import Choice from redbot.core.app_commands import Choice
from redbot.core.bot import Red from redbot.core.bot import Red
from redbot.core.utils.chat_formatting import bold, box, humanize_list from redbot.core.utils.chat_formatting import bold, box, error, humanize_list
from redbot.core.utils.views import ConfirmView from redbot.core.utils.views import ConfirmView
from typing_extensions import override
from pterodactyl import mcsrvstatus from pterodactyl import mcsrvstatus
from pterodactyl.config import config, register_config from pterodactyl.config import config, register_config
@ -23,20 +22,19 @@ 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.4"
__documentation__ = "https://seacogs.coastalcommits.com/pterodactyl/" __documentation__ = "https://seacogs.coastalcommits.com/pterodactyl/"
def __init__(self, bot: Red): def __init__(self, bot: Red):
self.bot = bot self.bot = bot
self.client: Optional[PterodactylClient] = None self.client: Optional[PterodactylClient] = None
self.task: Optional[asyncio.Task] = None self.task: Optional[asyncio.Task] = None
self.websocket: Optional[websockets.ClientConnection] = None self.websocket: Optional[websockets.WebSocketClientProtocol] = None
self.retry_counter: int = 0 self.retry_counter: int = 0
register_config(config) register_config(config)
self.task = self._get_task() self.task = self.get_task()
self.update_topic.start() self.update_topic.start()
@override
def format_help_for_context(self, ctx: commands.Context) -> str: def format_help_for_context(self, ctx: commands.Context) -> str:
pre_processed = super().format_help_for_context(ctx) or "" pre_processed = super().format_help_for_context(ctx) or ""
n = "\n" if "\n\n" not in pre_processed else "" n = "\n" if "\n\n" not in pre_processed else ""
@ -48,57 +46,47 @@ class Pterodactyl(commands.Cog):
] ]
return "\n".join(text) return "\n".join(text)
@override
async def cog_load(self) -> None: async def cog_load(self) -> None:
pterodactyl_keys = await self.bot.get_shared_api_tokens("pterodactyl") pterodactyl_keys = await self.bot.get_shared_api_tokens("pterodactyl")
api_key = pterodactyl_keys.get("api_key") api_key = pterodactyl_keys.get("api_key")
if api_key is None: if api_key is None:
self.maybe_cancel_task() self.task.cancel()
logger.error("Pterodactyl API key not set. Please set it using `[p]set api`.") raise ValueError("Pterodactyl API key not set. Please set it using `[p]set api`.")
return
base_url = await config.base_url() base_url = await config.base_url()
if base_url is None: if base_url is None:
self.maybe_cancel_task() self.task.cancel()
logger.error("Pterodactyl base URL not set. Please set it using `[p]pterodactyl config url`.") raise ValueError("Pterodactyl base URL not set. Please set it using `[p]pterodactyl config url`.")
return
server_id = await config.server_id() server_id = await config.server_id()
if server_id is None: if server_id is None:
self.maybe_cancel_task() self.task.cancel()
logger.error("Pterodactyl server ID not set. Please set it using `[p]pterodactyl config serverid`.") raise ValueError("Pterodactyl server ID not set. Please set it using `[p]pterodactyl config serverid`.")
return
self.client = PterodactylClient(base_url, api_key).client self.client = PterodactylClient(base_url, api_key).client
@override
async def cog_unload(self) -> None: async def cog_unload(self) -> None:
self.update_topic.cancel() self.update_topic.cancel()
self.maybe_cancel_task() self.task.cancel()
self.retry_counter = 0
await self.client._session.close() # pylint: disable=protected-access
def maybe_cancel_task(self, reset_retry_counter: bool = True) -> None: def get_task(self) -> asyncio.Task:
if self.task:
self.task.cancel()
if reset_retry_counter:
self.retry_counter = 0
def _get_task(self) -> asyncio.Task:
from pterodactyl.websocket import establish_websocket_connection from pterodactyl.websocket import establish_websocket_connection
task = self.bot.loop.create_task(establish_websocket_connection(self), name="Pterodactyl Websocket Connection") task = self.bot.loop.create_task(establish_websocket_connection(self), name="Pterodactyl Websocket Connection")
task.add_done_callback(self._error_callback) task.add_done_callback(self.error_callback)
return task return task
def _error_callback(self, fut) -> None: # NOTE Thanks flame442 and zephyrkul for helping me figure this out def error_callback(self, fut) -> None: #NOTE - Thanks flame442 and zephyrkul for helping me figure this out
try: try:
fut.result() fut.result()
except asyncio.CancelledError: except asyncio.CancelledError:
logger.info("WebSocket task has been cancelled.") logger.info("WebSocket task has been cancelled.")
except Exception as e: # pylint: disable=broad-exception-caught except Exception as e: # pylint: disable=broad-exception-caught
logger.error("WebSocket task has failed: %s", e, exc_info=e) logger.error("WebSocket task has failed: %s", e, exc_info=e)
self.maybe_cancel_task(reset_retry_counter=False) self.task.cancel()
if self.retry_counter < 5: if self.retry_counter < 5:
self.retry_counter += 1 self.retry_counter += 1
logger.info("Retrying in %s seconds...", 5 * self.retry_counter) logger.info("Retrying in %s seconds...", 5 * self.retry_counter)
self.task = self.bot.loop.call_later(5 * self.retry_counter, self._get_task) self.task = self.bot.loop.call_later(5 * self.retry_counter, self.get_task)
else: else:
logger.info("Retry limit reached. Stopping task.") logger.info("Retry limit reached. Stopping task.")
@ -109,9 +97,9 @@ class Pterodactyl(commands.Cog):
console = self.bot.get_channel(await config.console_channel()) console = self.bot.get_channel(await config.console_channel())
chat = self.bot.get_channel(await config.chat_channel()) chat = self.bot.get_channel(await config.chat_channel())
if console: if console:
await console.edit(topic=topic) # type: ignore await console.edit(topic=topic)
if chat: if chat:
await chat.edit(topic=topic) # type: ignore await chat.edit(topic=topic)
@commands.Cog.listener() @commands.Cog.listener()
async def on_message_without_command(self, message: discord.Message) -> None: async def on_message_without_command(self, message: discord.Message) -> None:
@ -122,7 +110,13 @@ class Pterodactyl(commands.Cog):
return return
logger.debug("Received console command from %s: %s", message.author.id, message.content) logger.debug("Received console command from %s: %s", message.author.id, message.content)
await message.channel.send(f"Received console command from {message.author.id}: {message.content[:1900]}", allowed_mentions=discord.AllowedMentions.none()) await message.channel.send(f"Received console command from {message.author.id}: {message.content[:1900]}", allowed_mentions=discord.AllowedMentions.none())
await self._send(json.dumps({"event": "send command", "args": [message.content]})) try:
await self.websocket.send(json.dumps({"event": "send command", "args": [message.content]}))
except websockets.exceptions.ConnectionClosed as e:
logger.error("WebSocket connection closed: %s", e)
self.task.cancel()
self.retry_counter = 0
self.task = self.get_task()
if message.channel.id == await config.chat_channel() and message.author.bot is False: if message.channel.id == await config.chat_channel() and message.author.bot is False:
logger.debug("Received chat message from %s: %s", message.author.id, message.content) logger.debug("Received chat message from %s: %s", message.author.id, message.content)
channel = self.bot.get_channel(await config.console_channel()) channel = self.bot.get_channel(await config.console_channel())
@ -130,22 +124,13 @@ class Pterodactyl(commands.Cog):
await channel.send(f"Received chat message from {message.author.id}: {message.content[:1900]}", allowed_mentions=discord.AllowedMentions.none()) await channel.send(f"Received chat message from {message.author.id}: {message.content[:1900]}", allowed_mentions=discord.AllowedMentions.none())
msg = json.dumps({"event": "send command", "args": [await self.get_chat_command(message)]}) msg = json.dumps({"event": "send command", "args": [await self.get_chat_command(message)]})
logger.debug("Sending chat message to server:\n%s", msg) logger.debug("Sending chat message to server:\n%s", msg)
await self._send(message=msg)
async def _send(self, message: Union[websockets.Data, Iterable[websockets.Data], AsyncIterable[websockets.Data]], text: bool = False):
"""Send a message through the websocket connection. Restarts the websocket connection task if it is closed, and reinvokes itself."""
try:
await self.websocket.send(message=message, text=text) # type: ignore - we want this to error if `self.websocket` is none
except websockets.exceptions.ConnectionClosed as e:
logger.error("WebSocket connection closed: %s", e)
self.maybe_cancel_task()
self.task = self._get_task()
try: try:
await asyncio.wait_for(fut=self.task, timeout=60) await self.websocket.send(msg)
await self._send(message=message, text=text) except websockets.exceptions.ConnectionClosed as e:
except asyncio.TimeoutError: logger.error("WebSocket connection closed: %s", e)
logger.error("Timeout while waiting for websocket connection") self.task.cancel()
raise self.retry_counter = 0
self.task = self.get_task()
async def get_topic(self) -> str: async def get_topic(self) -> str:
topic: str = await config.topic() topic: str = await config.topic()
@ -156,27 +141,23 @@ class Pterodactyl(commands.Cog):
if await config.api_endpoint() == "minecraft": if await config.api_endpoint() == "minecraft":
status, response = await mcsrvstatus.get_status(await config.topic_hostname(), await config.topic_port()) status, response = await mcsrvstatus.get_status(await config.topic_hostname(), await config.topic_port())
if status: if status:
placeholders.update( placeholders.update({
{ "I": response['ip'],
"I": response["ip"], "M": str(response['players']['max']),
"M": str(response["players"]["max"]), "P": str(response['players']['online']),
"P": str(response["players"]["online"]), "V": response['version'],
"V": response["version"], "D": response['motd']['clean'][0] if response['motd']['clean'] else "unset",
"D": response["motd"]["clean"][0] if response["motd"]["clean"] else "unset", })
},
)
else: else:
placeholders.update( placeholders.update({
{ "I": response['ip'],
"I": response["ip"], "M": "0",
"M": "0", "P": "0",
"P": "0", "V": "Server Offline",
"V": "Server Offline", "D": "Server Offline",
"D": "Server Offline", })
},
)
for key, value in placeholders.items(): for key, value in placeholders.items():
topic = topic.replace(".$" + key, value) topic = topic.replace('.$' + key, value)
return topic return topic
async def get_chat_command(self, message: discord.Message) -> str: async def get_chat_command(self, message: discord.Message) -> str:
@ -185,45 +166,42 @@ class Pterodactyl(commands.Cog):
"C": str(message.author.color), "C": str(message.author.color),
"D": message.author.discriminator, "D": message.author.discriminator,
"I": str(message.author.id), "I": str(message.author.id),
"M": message.content.replace('"', "").replace("\n", " "), "M": message.content.replace('"','').replace("\n", " "),
"N": message.author.display_name, "N": message.author.display_name,
"U": message.author.name, "U": message.author.name,
"V": await config.invite() or "use [p]pterodactyl config invite to change me", "V": await config.invite() or "use [p]pterodactyl config invite to change me",
} }
for key, value in placeholders.items(): for key, value in placeholders.items():
command = command.replace(".$" + key, value) command = command.replace('.$' + key, value)
return command return command
async def get_player_list(self) -> Optional[Tuple[str, list]]: async def get_player_list(self) -> Optional[Tuple[str, list]]:
if await config.api_endpoint() == "minecraft": if await config.api_endpoint() == "minecraft":
status, response = await mcsrvstatus.get_status(await config.topic_hostname(), await config.topic_port()) status, response = await mcsrvstatus.get_status(await config.topic_hostname(), await config.topic_port())
if status and "list" in response["players"]: if status and 'list' in response['players']:
output_str = "\n".join(response["players"]["list"]) output_str = '\n'.join(response['players']['list'])
return output_str, response["players"]["list"] return output_str, response['players']['list']
return None return None
return None
async def get_player_list_embed(self, ctx: Union[commands.Context, discord.Interaction]) -> Optional[discord.Embed]: async def get_player_list_embed(self, ctx: Union[commands.Context, discord.Interaction]) -> Optional[discord.Embed]:
player_list = await self.get_player_list() player_list = await self.get_player_list()
if player_list and isinstance(ctx.channel, discord.abc.Messageable): if player_list:
embed = discord.Embed(color=await self.bot.get_embed_color(ctx.channel), title="Players Online") embed = discord.Embed(color=await self.bot.get_embed_color(ctx.channel), title="Players Online")
embed.description = player_list[0] embed.description = player_list[0]
return embed return embed
return None return None
async def power(self, ctx: Union[discord.Interaction, commands.Context], action: str, action_ing: str, warning: str = "") -> None: async def power(self, ctx: Union[discord.Interaction, commands.Context], action: str, action_ing: str, warning: str = '') -> None:
if isinstance(ctx, discord.Interaction): if isinstance(ctx, discord.Interaction):
ctx = await self.bot.get_context(ctx) ctx = await self.bot.get_context(ctx)
current_status = await config.current_status() current_status = await config.current_status()
if current_status == action_ing: if current_status == action_ing:
await ctx.send(f"Server is already {action_ing}.", ephemeral=True) return await ctx.send(f"Server is already {action_ing}.", ephemeral=True)
return
if current_status in ["starting", "stopping"] and action != "kill": if current_status in ["starting", "stopping"] and action != "kill":
await ctx.send("Another power action is already in progress.", ephemeral=True) return await ctx.send("Another power action is already in progress.", ephemeral=True)
return
view = ConfirmView(ctx.author, disable_buttons=True) view = ConfirmView(ctx.author, disable_buttons=True)
@ -234,13 +212,12 @@ 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
await message.edit(content="Cancelled.", view=None) else:
return await message.edit(content="Cancelled.", view=None)
async def send_command(self, ctx: Union[discord.Interaction, commands.Context], command: str): async def send_command(self, ctx: Union[discord.Interaction, commands.Context], command: str):
channel = self.bot.get_channel(await config.console_channel()) channel = self.bot.get_channel(await config.console_channel())
@ -248,19 +225,27 @@ 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]})) try:
await ctx.send(f"Command sent to server. {box(command, 'json')}") await self.websocket.send(json.dumps({"event": "send command", "args": [command]}))
await ctx.send(f"Command sent to server. {box(command, 'json')}")
except websockets.exceptions.ConnectionClosed as e:
logger.error("WebSocket connection closed: %s", e)
await ctx.send(error("WebSocket connection closed."))
self.task.cancel()
self.retry_counter = 0
self.task = self.get_task()
@commands.Cog.listener() @commands.Cog.listener()
async def on_red_api_tokens_update(self, service_name: str, api_tokens: Mapping[str, str]): # pylint: disable=unused-argument async def on_red_api_tokens_update(self, service_name: str, api_tokens: Mapping[str,str]): # pylint: disable=unused-argument
if service_name == "pterodactyl": if service_name == "pterodactyl":
logger.info("Configuration value set: api_key\nRestarting task...") logger.info("Configuration value set: api_key\nRestarting task...")
self.maybe_cancel_task(reset_retry_counter=True) self.task.cancel()
self.task = self._get_task() self.retry_counter = 0
self.task = self.get_task()
slash_pterodactyl = app_commands.Group(name="pterodactyl", description="Pterodactyl allows you to manage your Pterodactyl Panel from Discord.") slash_pterodactyl = app_commands.Group(name="pterodactyl", description="Pterodactyl allows you to manage your Pterodactyl Panel from Discord.")
@slash_pterodactyl.command(name="command", description="Send a command to the server console.") @slash_pterodactyl.command(name = "command", description = "Send a command to the server console.")
async def slash_pterodactyl_command(self, interaction: discord.Interaction, command: str) -> None: async def slash_pterodactyl_command(self, interaction: discord.Interaction, command: str) -> None:
"""Send a command to the server console. """Send a command to the server console.
@ -270,7 +255,7 @@ class Pterodactyl(commands.Cog):
The command to send to the server.""" The command to send to the server."""
return await self.send_command(interaction, command) return await self.send_command(interaction, command)
@slash_pterodactyl.command(name="players", description="Retrieve a list of players on the server.") @slash_pterodactyl.command(name = "players", description = "Retrieve a list of players on the server.")
async def slash_pterodactyl_players(self, interaction: discord.Interaction) -> None: async def slash_pterodactyl_players(self, interaction: discord.Interaction) -> None:
"""Retrieve a list of players on the server.""" """Retrieve a list of players on the server."""
e = await self.get_player_list_embed(interaction) e = await self.get_player_list_embed(interaction)
@ -279,8 +264,13 @@ class Pterodactyl(commands.Cog):
else: else:
await interaction.response.send_message("No players online.", ephemeral=True) await interaction.response.send_message("No players online.", ephemeral=True)
@slash_pterodactyl.command(name="power", description="Send power actions to the server.") @slash_pterodactyl.command(name = "power", description = "Send power actions to the server.")
@app_commands.choices(action=[Choice(name="Start", value="start"), Choice(name="Stop", value="stop"), Choice(name="Restart", value="restart"), Choice(name="⚠️ Kill ⚠️", value="kill")]) @app_commands.choices(action=[
Choice(name="Start", value="start"),
Choice(name="Stop", value="stop"),
Choice(name="Restart", value="restart"),
Choice(name="⚠️ Kill ⚠️", value="kill")
])
async def slash_pterodactyl_power(self, interaction: discord.Interaction, action: app_commands.Choice[str]) -> None: async def slash_pterodactyl_power(self, interaction: discord.Interaction, action: app_commands.Choice[str]) -> None:
"""Send power actions to the server. """Send power actions to the server.
@ -294,11 +284,11 @@ class Pterodactyl(commands.Cog):
return await self.power(interaction, action.value, "stopping...") return await self.power(interaction, action.value, "stopping...")
return await self.power(interaction, action.value, f"{action.value}ing...") return await self.power(interaction, action.value, f"{action.value}ing...")
@commands.group(autohelp=True, name="pterodactyl", aliases=["ptero"]) @commands.group(autohelp = True, name = "pterodactyl", aliases = ["ptero"])
async def pterodactyl(self, ctx: commands.Context) -> None: async def pterodactyl(self, ctx: commands.Context) -> None:
"""Pterodactyl allows you to manage your Pterodactyl Panel from Discord.""" """Pterodactyl allows you to manage your Pterodactyl Panel from Discord."""
@pterodactyl.command(name="players", aliases=["list", "online", "playerlist", "who"]) @pterodactyl.command(name = "players", aliases=["list", "online", "playerlist", "who"])
async def pterodactyl_players(self, ctx: commands.Context) -> None: async def pterodactyl_players(self, ctx: commands.Context) -> None:
"""Retrieve a list of players on the server.""" """Retrieve a list of players on the server."""
e = await self.get_player_list_embed(ctx) e = await self.get_player_list_embed(ctx)
@ -307,43 +297,43 @@ class Pterodactyl(commands.Cog):
else: else:
await ctx.send("No players online.") await ctx.send("No players online.")
@pterodactyl.command(name="command", aliases=["cmd", "execute", "exec"]) @pterodactyl.command(name = "command", aliases = ["cmd", "execute", "exec"])
@commands.admin() @commands.admin()
async def pterodactyl_command(self, ctx: commands.Context, *, command: str) -> None: async def pterodactyl_command(self, ctx: commands.Context, *, command: str) -> None:
"""Send a command to the server console.""" """Send a command to the server console."""
return await self.send_command(ctx, command) return await self.send_command(ctx, command)
@pterodactyl.group(autohelp=True, name="power") @pterodactyl.group(autohelp = True, name = "power")
@commands.admin() @commands.admin()
async def pterodactyl_power(self, ctx: commands.Context) -> None: async def pterodactyl_power(self, ctx: commands.Context) -> None:
"""Send power actions to the server.""" """Send power actions to the server."""
@pterodactyl_power.command(name="start") @pterodactyl_power.command(name = "start")
async def pterodactyl_power_start(self, ctx: commands.Context) -> Optional[discord.Message]: async def pterodactyl_power_start(self, ctx: commands.Context) -> Optional[discord.Message]:
"""Start the server.""" """Start the server."""
return await self.power(ctx, "start", "starting...") return await self.power(ctx, "start", "starting...")
@pterodactyl_power.command(name="stop") @pterodactyl_power.command(name = "stop")
async def pterodactyl_power_stop(self, ctx: commands.Context) -> Optional[discord.Message]: async def pterodactyl_power_stop(self, ctx: commands.Context) -> Optional[discord.Message]:
"""Stop the server.""" """Stop the server."""
return await self.power(ctx, "stop", "stopping...") return await self.power(ctx, "stop", "stopping...")
@pterodactyl_power.command(name="restart") @pterodactyl_power.command(name = "restart")
async def pterodactyl_power_restart(self, ctx: commands.Context) -> Optional[discord.Message]: async def pterodactyl_power_restart(self, ctx: commands.Context) -> Optional[discord.Message]:
"""Restart the server.""" """Restart the server."""
return await self.power(ctx, "restart", "restarting...") return await self.power(ctx, "restart", "restarting...")
@pterodactyl_power.command(name="kill") @pterodactyl_power.command(name = "kill")
async def pterodactyl_power_kill(self, ctx: commands.Context) -> Optional[discord.Message]: async def pterodactyl_power_kill(self, ctx: commands.Context) -> Optional[discord.Message]:
"""Kill the server.""" """Kill the server."""
return await self.power(ctx, "kill", "stopping... (forcefully killed)", warning="**⚠️ Forcefully killing the server process can corrupt data in some cases. ⚠️**\n") return await self.power(ctx, "kill", "stopping... (forcefully killed)", warning="**⚠️ Forcefully killing the server process can corrupt data in some cases. ⚠️**\n")
@pterodactyl.group(autohelp=True, name="config", aliases=["settings", "set"]) @pterodactyl.group(autohelp = True, name = "config", aliases = ["settings", "set"])
@commands.is_owner() @commands.is_owner()
async def pterodactyl_config(self, ctx: commands.Context) -> None: async def pterodactyl_config(self, ctx: commands.Context) -> None:
"""Configure Pterodactyl settings.""" """Configure Pterodactyl settings."""
@pterodactyl_config.command(name="url") @pterodactyl_config.command(name = "url")
async def pterodactyl_config_base_url(self, ctx: commands.Context, *, base_url: str) -> None: async def pterodactyl_config_base_url(self, ctx: commands.Context, *, base_url: str) -> None:
"""Set the base URL of your Pterodactyl Panel. """Set the base URL of your Pterodactyl Panel.
@ -352,57 +342,59 @@ class Pterodactyl(commands.Cog):
await config.base_url.set(base_url) await config.base_url.set(base_url)
await ctx.send(f"Base URL set to {base_url}") await ctx.send(f"Base URL set to {base_url}")
logger.info("Configuration value set: base_url = %s\nRestarting task...", base_url) logger.info("Configuration value set: base_url = %s\nRestarting task...", base_url)
self.maybe_cancel_task(reset_retry_counter=True) self.task.cancel()
self.task = self._get_task() self.retry_counter = 0
self.task = self.get_task()
@pterodactyl_config.command(name="serverid") @pterodactyl_config.command(name = "serverid")
async def pterodactyl_config_server_id(self, ctx: commands.Context, *, server_id: str) -> None: async def pterodactyl_config_server_id(self, ctx: commands.Context, *, server_id: str) -> None:
"""Set the ID of your server.""" """Set the ID of your server."""
await config.server_id.set(server_id) await config.server_id.set(server_id)
await ctx.send(f"Server ID set to {server_id}") await ctx.send(f"Server ID set to {server_id}")
logger.info("Configuration value set: server_id = %s\nRestarting task...", server_id) logger.info("Configuration value set: server_id = %s\nRestarting task...", server_id)
self.maybe_cancel_task(reset_retry_counter=True) self.task.cancel()
self.task = self._get_task() self.retry_counter = 0
self.task = self.get_task()
@pterodactyl_config.group(name="console") @pterodactyl_config.group(name = "console")
async def pterodactyl_config_console(self, ctx: commands.Context): async def pterodactyl_config_console(self, ctx: commands.Context):
"""Configure console settings.""" """Configure console settings."""
@pterodactyl_config_console.command(name="channel") @pterodactyl_config_console.command(name = "channel")
async def pterodactyl_config_console_channel(self, ctx: commands.Context, channel: discord.TextChannel) -> None: async def pterodactyl_config_console_channel(self, ctx: commands.Context, channel: discord.TextChannel) -> None:
"""Set the channel to send console output to.""" """Set the channel to send console output to."""
await config.console_channel.set(channel.id) await config.console_channel.set(channel.id)
await ctx.send(f"Console channel set to {channel.mention}") await ctx.send(f"Console channel set to {channel.mention}")
@pterodactyl_config_console.command(name="commands") @pterodactyl_config_console.command(name = "commands")
async def pterodactyl_config_console_commands(self, ctx: commands.Context, enabled: bool) -> None: async def pterodactyl_config_console_commands(self, ctx: commands.Context, enabled: bool) -> None:
"""Enable or disable console commands.""" """Enable or disable console commands."""
await config.console_commands_enabled.set(enabled) await config.console_commands_enabled.set(enabled)
await ctx.send(f"Console commands set to {enabled}") await ctx.send(f"Console commands set to {enabled}")
@pterodactyl_config.command(name="invite") @pterodactyl_config.command(name = "invite")
async def pterodactyl_config_invite(self, ctx: commands.Context, invite: str) -> None: async def pterodactyl_config_invite(self, ctx: commands.Context, invite: str) -> None:
"""Set the invite link for your server.""" """Set the invite link for your server."""
await config.invite.set(invite) await config.invite.set(invite)
await ctx.send(f"Invite link set to {invite}") await ctx.send(f"Invite link set to {invite}")
@pterodactyl_config.group(name="topic") @pterodactyl_config.group(name = "topic")
async def pterodactyl_config_topic(self, ctx: commands.Context): async def pterodactyl_config_topic(self, ctx: commands.Context):
"""Set the topic for the console and chat channels.""" """Set the topic for the console and chat channels."""
@pterodactyl_config_topic.command(name="host", aliases=["hostname", "ip"]) @pterodactyl_config_topic.command(name = "host", aliases = ["hostname", "ip"])
async def pterodactyl_config_topic_host(self, ctx: commands.Context, host: str) -> None: async def pterodactyl_config_topic_host(self, ctx: commands.Context, host: str) -> None:
"""Set the hostname or IP address of your server.""" """Set the hostname or IP address of your server."""
await config.topic_hostname.set(host) await config.topic_hostname.set(host)
await ctx.send(f"Hostname/IP set to `{host}`") await ctx.send(f"Hostname/IP set to `{host}`")
@pterodactyl_config_topic.command(name="port") @pterodactyl_config_topic.command(name = "port")
async def pterodactyl_config_topic_port(self, ctx: commands.Context, port: int) -> None: async def pterodactyl_config_topic_port(self, ctx: commands.Context, port: int) -> None:
"""Set the port of your server.""" """Set the port of your server."""
await config.topic_port.set(port) await config.topic_port.set(port)
await ctx.send(f"Port set to `{port}`") await ctx.send(f"Port set to `{port}`")
@pterodactyl_config_topic.command(name="text") @pterodactyl_config_topic.command(name = "text")
async def pterodactyl_config_topic_text(self, ctx: commands.Context, *, text: str) -> None: async def pterodactyl_config_topic_text(self, ctx: commands.Context, *, text: str) -> None:
"""Set the text for the console and chat channels. """Set the text for the console and chat channels.
@ -416,19 +408,19 @@ 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):
"""Configure chat settings.""" """Configure chat settings."""
@pterodactyl_config_chat.command(name="channel") @pterodactyl_config_chat.command(name = "channel")
async def pterodactyl_config_chat_channel(self, ctx: commands.Context, channel: discord.TextChannel) -> None: async def pterodactyl_config_chat_channel(self, ctx: commands.Context, channel: discord.TextChannel) -> None:
"""Set the channel to send chat output to.""" """Set the channel to send chat output to."""
await config.chat_channel.set(channel.id) await config.chat_channel.set(channel.id)
await ctx.send(f"Chat channel set to {channel.mention}") await ctx.send(f"Chat channel set to {channel.mention}")
@pterodactyl_config_chat.command(name="command") @pterodactyl_config_chat.command(name = "command")
async def pterodactyl_config_chat_command(self, ctx: commands.Context, *, command: str) -> None: async def pterodactyl_config_chat_command(self, ctx: commands.Context, *, command: str) -> None:
"""Set the command that will be used to send messages from Discord. """Set the command that will be used to send messages from Discord.
@ -437,11 +429,11 @@ class Pterodactyl(commands.Cog):
await config.chat_command.set(command) await config.chat_command.set(command)
await ctx.send(f"Chat command set to:\n{box(command, 'json')}") await ctx.send(f"Chat command set to:\n{box(command, 'json')}")
@pterodactyl_config.group(name="regex") @pterodactyl_config.group(name = "regex")
async def pterodactyl_config_regex(self, ctx: commands.Context) -> None: async def pterodactyl_config_regex(self, ctx: commands.Context) -> None:
"""Set regex patterns.""" """Set regex patterns."""
@pterodactyl_config_regex.command(name="chat") @pterodactyl_config_regex.command(name = "chat")
async def pterodactyl_config_regex_chat(self, ctx: commands.Context, *, regex: str) -> None: async def pterodactyl_config_regex_chat(self, ctx: commands.Context, *, regex: str) -> None:
"""Set the regex pattern to match chat messages on the server. """Set the regex pattern to match chat messages on the server.
@ -449,7 +441,7 @@ class Pterodactyl(commands.Cog):
await config.chat_regex.set(regex) await config.chat_regex.set(regex)
await ctx.send(f"Chat regex set to:\n{box(regex, 'regex')}") await ctx.send(f"Chat regex set to:\n{box(regex, 'regex')}")
@pterodactyl_config_regex.command(name="server") @pterodactyl_config_regex.command(name = "server")
async def pterodactyl_config_regex_server(self, ctx: commands.Context, *, regex: str) -> None: async def pterodactyl_config_regex_server(self, ctx: commands.Context, *, regex: str) -> None:
"""Set the regex pattern to match server messages on the server. """Set the regex pattern to match server messages on the server.
@ -457,7 +449,7 @@ class Pterodactyl(commands.Cog):
await config.server_regex.set(regex) await config.server_regex.set(regex)
await ctx.send(f"Server regex set to:\n{box(regex, 'regex')}") await ctx.send(f"Server regex set to:\n{box(regex, 'regex')}")
@pterodactyl_config_regex.command(name="join") @pterodactyl_config_regex.command(name = "join")
async def pterodactyl_config_regex_join(self, ctx: commands.Context, *, regex: str) -> None: async def pterodactyl_config_regex_join(self, ctx: commands.Context, *, regex: str) -> None:
"""Set the regex pattern to match join messages on the server. """Set the regex pattern to match join messages on the server.
@ -465,7 +457,7 @@ class Pterodactyl(commands.Cog):
await config.join_regex.set(regex) await config.join_regex.set(regex)
await ctx.send(f"Join regex set to:\n{box(regex, 'regex')}") await ctx.send(f"Join regex set to:\n{box(regex, 'regex')}")
@pterodactyl_config_regex.command(name="leave") @pterodactyl_config_regex.command(name = "leave")
async def pterodactyl_config_regex_leave(self, ctx: commands.Context, *, regex: str) -> None: async def pterodactyl_config_regex_leave(self, ctx: commands.Context, *, regex: str) -> None:
"""Set the regex pattern to match leave messages on the server. """Set the regex pattern to match leave messages on the server.
@ -473,7 +465,7 @@ class Pterodactyl(commands.Cog):
await config.leave_regex.set(regex) await config.leave_regex.set(regex)
await ctx.send(f"Leave regex set to:\n{box(regex, 'regex')}") await ctx.send(f"Leave regex set to:\n{box(regex, 'regex')}")
@pterodactyl_config_regex.command(name="achievement") @pterodactyl_config_regex.command(name = "achievement")
async def pterodactyl_config_regex_achievement(self, ctx: commands.Context, *, regex: str) -> None: async def pterodactyl_config_regex_achievement(self, ctx: commands.Context, *, regex: str) -> None:
"""Set the regex pattern to match achievement messages on the server. """Set the regex pattern to match achievement messages on the server.
@ -481,41 +473,41 @@ class Pterodactyl(commands.Cog):
await config.achievement_regex.set(regex) await config.achievement_regex.set(regex)
await ctx.send(f"Achievement regex set to:\n{box(regex, 'regex')}") await ctx.send(f"Achievement regex set to:\n{box(regex, 'regex')}")
@pterodactyl_config.group(name="messages", aliases=["msg", "msgs", "message"]) @pterodactyl_config.group(name = "messages", aliases = ['msg', 'msgs', 'message'])
async def pterodactyl_config_messages(self, ctx: commands.Context): async def pterodactyl_config_messages(self, ctx: commands.Context):
"""Configure message settings.""" """Configure message settings."""
@pterodactyl_config_messages.command(name="startup") @pterodactyl_config_messages.command(name = "startup")
async def pterodactyl_config_messages_startup(self, ctx: commands.Context, *, message: str) -> None: async def pterodactyl_config_messages_startup(self, ctx: commands.Context, *, message: str) -> None:
"""Set the message that will be sent when the server starts.""" """Set the message that will be sent when the server starts."""
await config.startup_msg.set(message) await config.startup_msg.set(message)
await ctx.send(f"Startup message set to: {message}") await ctx.send(f"Startup message set to: {message}")
@pterodactyl_config_messages.command(name="shutdown") @pterodactyl_config_messages.command(name = "shutdown")
async def pterodactyl_config_messages_shutdown(self, ctx: commands.Context, *, message: str) -> None: async def pterodactyl_config_messages_shutdown(self, ctx: commands.Context, *, message: str) -> None:
"""Set the message that will be sent when the server stops.""" """Set the message that will be sent when the server stops."""
await config.shutdown_msg.set(message) await config.shutdown_msg.set(message)
await ctx.send(f"Shutdown message set to: {message}") await ctx.send(f"Shutdown message set to: {message}")
@pterodactyl_config_messages.command(name="join") @pterodactyl_config_messages.command(name = "join")
async def pterodactyl_config_messages_join(self, ctx: commands.Context, *, message: str) -> None: async def pterodactyl_config_messages_join(self, ctx: commands.Context, *, message: str) -> None:
"""Set the message that will be sent when a user joins the server. This is only shown in embeds.""" """Set the message that will be sent when a user joins the server. This is only shown in embeds."""
await config.join_msg.set(message) await config.join_msg.set(message)
await ctx.send(f"Join message set to: {message}") await ctx.send(f"Join message set to: {message}")
@pterodactyl_config_messages.command(name="leave") @pterodactyl_config_messages.command(name = "leave")
async def pterodactyl_config_messages_leave(self, ctx: commands.Context, *, message: str) -> None: async def pterodactyl_config_messages_leave(self, ctx: commands.Context, *, message: str) -> None:
"""Set the message that will be sent when a user leaves the server. This is only shown in embeds.""" """Set the message that will be sent when a user leaves the server. This is only shown in embeds."""
await config.leave_msg.set(message) await config.leave_msg.set(message)
await ctx.send(f"Leave message set to: {message}") await ctx.send(f"Leave message set to: {message}")
@pterodactyl_config.command(name="ip") @pterodactyl_config.command(name = "ip")
async def pterodactyl_config_mask_ip(self, ctx: commands.Context, mask: bool) -> None: async def pterodactyl_config_mask_ip(self, ctx: commands.Context, mask: bool) -> None:
"""Mask the IP addresses of users in console messages.""" """Mask the IP addresses of users in console messages."""
await config.mask_ip.set(mask) await config.mask_ip.set(mask)
await ctx.send(f"IP masking set to {mask}") await ctx.send(f"IP masking set to {mask}")
@pterodactyl_config.command(name="api") @pterodactyl_config.command(name = "api")
async def pterodactyl_config_api(self, ctx: commands.Context, endpoint: str) -> None: async def pterodactyl_config_api(self, ctx: commands.Context, endpoint: str) -> None:
"""Set the API endpoint for retrieving user avatars. """Set the API endpoint for retrieving user avatars.
@ -524,14 +516,11 @@ class Pterodactyl(commands.Cog):
await config.api_endpoint.set(endpoint) await config.api_endpoint.set(endpoint)
await ctx.send(f"API endpoint set to {endpoint}") await ctx.send(f"API endpoint set to {endpoint}")
@pterodactyl_config_regex.group( @pterodactyl_config_regex.group(name = "blacklist", aliases = ['block', 'blocklist'],)
name="blacklist",
aliases=["block", "blocklist"],
)
async def pterodactyl_config_regex_blacklist(self, ctx: commands.Context): async def pterodactyl_config_regex_blacklist(self, ctx: commands.Context):
"""Blacklist regex patterns.""" """Blacklist regex patterns."""
@pterodactyl_config_regex_blacklist.command(name="add") @pterodactyl_config_regex_blacklist.command(name = "add")
async def pterodactyl_config_regex_blacklist_add(self, ctx: commands.Context, name: str, *, regex: str) -> None: async def pterodactyl_config_regex_blacklist_add(self, ctx: commands.Context, name: str, *, regex: str) -> None:
"""Add a regex pattern to the blacklist.""" """Add a regex pattern to the blacklist."""
async with config.regex_blacklist() as blacklist: async with config.regex_blacklist() as blacklist:
@ -549,7 +538,7 @@ class Pterodactyl(commands.Cog):
else: else:
await msg.edit(content="Cancelled.") await msg.edit(content="Cancelled.")
@pterodactyl_config_regex_blacklist.command(name="remove") @pterodactyl_config_regex_blacklist.command(name = "remove")
async def pterodactyl_config_regex_blacklist_remove(self, ctx: commands.Context, name: str) -> None: async def pterodactyl_config_regex_blacklist_remove(self, ctx: commands.Context, name: str) -> None:
"""Remove a regex pattern from the blacklist.""" """Remove a regex pattern from the blacklist."""
async with config.regex_blacklist() as blacklist: async with config.regex_blacklist() as blacklist:
@ -566,7 +555,7 @@ class Pterodactyl(commands.Cog):
else: else:
await ctx.send(f"Name `{name}` does not exist in the blacklist.") await ctx.send(f"Name `{name}` does not exist in the blacklist.")
@pterodactyl_config.command(name="view", aliases=["show"]) @pterodactyl_config.command(name = 'view', aliases = ['show'])
async def pterodactyl_config_view(self, ctx: commands.Context) -> None: async def pterodactyl_config_view(self, ctx: commands.Context) -> None:
"""View the current configuration.""" """View the current configuration."""
base_url = await config.base_url() base_url = await config.base_url()
@ -591,7 +580,7 @@ class Pterodactyl(commands.Cog):
topic_text = await config.topic() topic_text = await config.topic()
topic_hostname = await config.topic_hostname() topic_hostname = await config.topic_hostname()
topic_port = await config.topic_port() topic_port = await config.topic_port()
embed = discord.Embed(color=await ctx.embed_color(), title="Pterodactyl Configuration") embed = discord.Embed(color = await ctx.embed_color(), title="Pterodactyl Configuration")
embed.description = f"""**Base URL:** {base_url} embed.description = f"""**Base URL:** {base_url}
**Server ID:** `{server_id}` **Server ID:** `{server_id}`
**Console Channel:** <#{console_channel}> **Console Channel:** <#{console_channel}>
@ -607,19 +596,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

@ -2,14 +2,14 @@
import json import json
import re import re
from pathlib import Path from pathlib import Path
from typing import Any, Optional, Tuple, Union from typing import Optional, Tuple, Union
import aiohttp import aiohttp
import discord import discord
import websockets
from pydactyl import PterodactylClient from pydactyl import PterodactylClient
from redbot.core.data_manager import bundled_data_path from redbot.core.data_manager import bundled_data_path
from redbot.core.utils.chat_formatting import bold, pagify from redbot.core.utils.chat_formatting import bold, pagify
from websockets.asyncio.client import connect
from pterodactyl.config import config from pterodactyl.config import config
from pterodactyl.logger import logger, websocket_logger from pterodactyl.logger import logger, websocket_logger
@ -19,48 +19,46 @@ from pterodactyl.pterodactyl import Pterodactyl
async def establish_websocket_connection(coginstance: Pterodactyl) -> None: async def establish_websocket_connection(coginstance: Pterodactyl) -> None:
await coginstance.bot.wait_until_red_ready() await coginstance.bot.wait_until_red_ready()
base_url = await config.base_url() base_url = await config.base_url()
base_url = base_url[:-1] if base_url.endswith("/") else base_url base_url = base_url[:-1] if base_url.endswith('/') else base_url
logger.info("Establishing WebSocket connection") logger.info("Establishing WebSocket connection")
websocket_credentials = await retrieve_websocket_credentials(coginstance) websocket_credentials = await retrieve_websocket_credentials(coginstance)
async with connect(websocket_credentials["data"]["socket"], origin=base_url, ping_timeout=60, logger=websocket_logger) as websocket: async with websockets.connect(websocket_credentials['data']['socket'], origin=base_url, ping_timeout=60, logger=websocket_logger) as websocket:
logger.info("WebSocket connection established") logger.info("WebSocket connection established")
auth_message = json.dumps({"event": "auth", "args": [websocket_credentials["data"]["token"]]}) auth_message = json.dumps({"event": "auth", "args": [websocket_credentials['data']['token']]})
await websocket.send(auth_message) await websocket.send(auth_message)
logger.info("Authentication message sent") logger.info("Authentication message sent")
coginstance.websocket = websocket coginstance.websocket = websocket
while True: # pylint: disable=too-many-nested-blocks while True: # pylint: disable=too-many-nested-blocks
message = json.loads(await websocket.recv()) message = json.loads(await websocket.recv())
if message["event"] in ("token expiring", "token expired"): if message['event'] in ('token expiring', 'token expired'):
logger.info("Received token expiring/expired event. Refreshing token.") logger.info("Received token expiring/expired event. Refreshing token.")
websocket_credentials = await retrieve_websocket_credentials(coginstance) websocket_credentials = await retrieve_websocket_credentials(coginstance)
auth_message = json.dumps({"event": "auth", "args": [websocket_credentials["data"]["token"]]}) auth_message = json.dumps({"event": "auth", "args": [websocket_credentials['data']['token']]})
await websocket.send(auth_message) await websocket.send(auth_message)
logger.info("Authentication message sent") logger.info("Authentication message sent")
if message["event"] == "auth success": if message['event'] == 'auth success':
logger.info("WebSocket authentication successful") logger.info("WebSocket authentication successful")
if message["event"] == "console output" and await config.console_channel() is not None: if message['event'] == 'console output' and await config.console_channel() is not None:
regex_blacklist: dict = await config.regex_blacklist() regex_blacklist: dict = await config.regex_blacklist()
matches = [re.search(regex, message["args"][0]) for regex in regex_blacklist.values()] matches = [re.search(regex, message['args'][0]) for regex in regex_blacklist.values()]
if await config.current_status() in ("running", "") and not any(matches): if await config.current_status() in ('running', '') and not any(matches):
content = remove_ansi_escape_codes(message["args"][0]) content = remove_ansi_escape_codes(message['args'][0])
if await config.mask_ip() is True: if await config.mask_ip() is True:
content = mask_ip(content) content = mask_ip(content)
console_channel = coginstance.bot.get_channel(await config.console_channel()) console_channel = coginstance.bot.get_channel(await config.console_channel())
assert isinstance(console_channel, discord.abc.Messageable)
chat_channel = coginstance.bot.get_channel(await config.chat_channel()) chat_channel = coginstance.bot.get_channel(await config.chat_channel())
assert isinstance(chat_channel, discord.abc.Messageable)
if console_channel is not None: if console_channel is not None:
if content.startswith("["): if content.startswith('['):
pagified_content = pagify(content, delims=[" ", "\n"]) pagified_content = pagify(content, delims=[" ", "\n"])
for page in pagified_content: for page in pagified_content:
await console_channel.send(content=page, allowed_mentions=discord.AllowedMentions.none()) await console_channel.send(content=page, allowed_mentions=discord.AllowedMentions.none())
@ -68,24 +66,24 @@ async def establish_websocket_connection(coginstance: Pterodactyl) -> None:
server_message = await check_if_server_message(content) server_message = await check_if_server_message(content)
if server_message: if server_message:
if chat_channel is not None: if chat_channel is not None:
await chat_channel.send(server_message if len(server_message) < 2000 else server_message[:1997] + "...", allowed_mentions=discord.AllowedMentions.none()) await chat_channel.send(server_message if len(server_message) < 2000 else server_message[:1997] + '...', allowed_mentions=discord.AllowedMentions.none())
chat_message = await check_if_chat_message(content) chat_message = await check_if_chat_message(content)
if chat_message: if chat_message:
info = await get_info(chat_message["username"]) info = await get_info(chat_message['username'])
if info is not None: if info is not None:
await send_chat_discord(coginstance, chat_message["username"], chat_message["message"], info["data"]["player"]["avatar"]) await send_chat_discord(coginstance, chat_message['username'], chat_message['message'], info['data']['player']['avatar'])
else: else:
await send_chat_discord(coginstance, chat_message["username"], chat_message["message"], "https://seafsh.cc/u/j3AzqQ.png") await send_chat_discord(coginstance, chat_message['username'], chat_message['message'], 'https://seafsh.cc/u/j3AzqQ.png')
join_message = await check_if_join_message(content) join_message = await check_if_join_message(content)
if join_message: if join_message:
if chat_channel is not None: if chat_channel is not None:
if coginstance.bot.embed_requested(chat_channel): if coginstance.bot.embed_requested(chat_channel):
embed, img = await generate_join_leave_embed(coginstance=coginstance, username=join_message, join=True) embed, img = await generate_join_leave_embed(coginstance=coginstance, username=join_message,join=True)
if img: if img:
with open(img, "rb") as file: with open(img, 'rb') as file:
await chat_channel.send(embed=embed, file=discord.File(fp=file)) await chat_channel.send(embed=embed, file=file)
else: else:
await chat_channel.send(embed=embed) await chat_channel.send(embed=embed)
else: else:
@ -95,10 +93,10 @@ async def establish_websocket_connection(coginstance: Pterodactyl) -> None:
if leave_message: if leave_message:
if chat_channel is not None: if chat_channel is not None:
if coginstance.bot.embed_requested(chat_channel): if coginstance.bot.embed_requested(chat_channel):
embed, img = await generate_join_leave_embed(coginstance=coginstance, username=leave_message, join=False) embed, img = await generate_join_leave_embed(coginstance=coginstance, username=leave_message,join=False)
if img: if img:
with open(img, "rb") as file: with open(img, 'rb') as file:
await chat_channel.send(embed=embed, file=discord.File(fp=file)) await chat_channel.send(embed=embed, file=file)
else: else:
await chat_channel.send(embed=embed) await chat_channel.send(embed=embed)
else: else:
@ -108,17 +106,13 @@ async def establish_websocket_connection(coginstance: Pterodactyl) -> None:
if achievement_message: if achievement_message:
if chat_channel is not None: if chat_channel is not None:
if coginstance.bot.embed_requested(chat_channel): if coginstance.bot.embed_requested(chat_channel):
embed, img = await generate_achievement_embed(coginstance, achievement_message["username"], achievement_message["achievement"], achievement_message["challenge"]) await chat_channel.send(embed=await generate_achievement_embed(coginstance, achievement_message['username'], achievement_message['achievement'], achievement_message['challenge']))
if img:
await chat_channel.send(embed=embed, file=discord.File(fp=img))
else:
await chat_channel.send(embed=embed)
else: else:
await chat_channel.send(f"{achievement_message['username']} has {'completed the challenge' if achievement_message['challenge'] else 'made the advancement'} {achievement_message['achievement']}") await chat_channel.send(f"{achievement_message['username']} has {'completed the challenge' if achievement_message['challenge'] else 'made the advancement'} {achievement_message['achievement']}")
if message["event"] == "status": if message['event'] == 'status':
old_status = await config.current_status() old_status = await config.current_status()
current_status = message["args"][0] current_status = message['args'][0]
if old_status != current_status: if old_status != current_status:
await config.current_status.set(current_status) await config.current_status.set(current_status)
if await config.console_channel() is not None: if await config.console_channel() is not None:
@ -126,92 +120,81 @@ async def establish_websocket_connection(coginstance: Pterodactyl) -> None:
if console is not None: if console is not None:
await console.send(f"Server status changed! `{current_status}`") await console.send(f"Server status changed! `{current_status}`")
if await config.chat_channel() is not None: if await config.chat_channel() is not None:
if current_status == "running" and await config.startup_msg() is not None: if current_status == 'running' and await config.startup_msg() is not None:
chat = coginstance.bot.get_channel(await config.chat_channel()) chat = coginstance.bot.get_channel(await config.chat_channel())
if chat is not None: if chat is not None:
await chat.send(await config.startup_msg()) await chat.send(await config.startup_msg())
if current_status == "stopping" and await config.shutdown_msg() is not None: if current_status == 'stopping' and await config.shutdown_msg() is not None:
chat = coginstance.bot.get_channel(await config.chat_channel()) chat = coginstance.bot.get_channel(await config.chat_channel())
if chat is not None: if chat is not None:
await chat.send(await config.shutdown_msg()) await chat.send(await config.shutdown_msg())
async def retrieve_websocket_credentials(coginstance: Pterodactyl) -> Optional[dict]:
async def retrieve_websocket_credentials(coginstance: Pterodactyl) -> dict:
pterodactyl_keys = await coginstance.bot.get_shared_api_tokens("pterodactyl") pterodactyl_keys = await coginstance.bot.get_shared_api_tokens("pterodactyl")
api_key = pterodactyl_keys.get("api_key") api_key = pterodactyl_keys.get("api_key")
if api_key is None: if api_key is None:
coginstance.maybe_cancel_task() coginstance.task.cancel()
raise ValueError("Pterodactyl API key not set. Please set it using `[p]set api`.") raise ValueError("Pterodactyl API key not set. Please set it using `[p]set api`.")
base_url = await config.base_url() base_url = await config.base_url()
if base_url is None: if base_url is None:
coginstance.maybe_cancel_task() coginstance.task.cancel()
raise ValueError("Pterodactyl base URL not set. Please set it using `[p]pterodactyl config url`.") raise ValueError("Pterodactyl base URL not set. Please set it using `[p]pterodactyl config url`.")
server_id = await config.server_id() server_id = await config.server_id()
if server_id is None: if server_id is None:
coginstance.maybe_cancel_task() coginstance.task.cancel()
raise ValueError("Pterodactyl server ID not set. Please set it using `[p]pterodactyl config serverid`.") raise ValueError("Pterodactyl server ID not set. Please set it using `[p]pterodactyl config serverid`.")
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 = client.servers.get_websocket(server_id)
if not websocket_credentials: logger.debug("""Websocket connection details retrieved:
coginstance.maybe_cancel_task()
raise ValueError("Failed to retrieve websocket credentials. Please ensure the API details are correctly configured.")
logger.debug(
"""Websocket connection details retrieved:
Socket: %s Socket: %s
Token: %s...""", Token: %s...""",
websocket_credentials["data"]["socket"], websocket_credentials['data']['socket'],
websocket_credentials["data"]["token"][:20], websocket_credentials['data']['token'][:20]
) )
return websocket_credentials return websocket_credentials
# NOTE - The token is truncated to prevent it from being logged in its entirety, for security reasons #NOTE - The token is truncated to prevent it from being logged in its entirety, for security reasons
def remove_ansi_escape_codes(text: str) -> str: def remove_ansi_escape_codes(text: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])") ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
# NOTE - https://chat.openai.com/share/d92f9acf-d776-4fd6-a53f-b14ac15dd540 #NOTE - https://chat.openai.com/share/d92f9acf-d776-4fd6-a53f-b14ac15dd540
return ansi_escape.sub("", text) return ansi_escape.sub('', text)
async def check_if_server_message(text: str) -> Union[bool, str]:
async def check_if_server_message(text: str) -> Optional[str]:
regex = await config.server_regex() regex = await config.server_regex()
match: Optional[re.Match[str]] = re.match(regex, text) match: Optional[re.Match[str]] = re.match(regex, text)
if match: if match:
logger.trace("Message is a server message") logger.trace("Message is a server message")
return match.group(1) return match.group(1)
return None return False
async def check_if_chat_message(text: str) -> Union[bool, dict]:
async def check_if_chat_message(text: str) -> Optional[dict]:
regex = await config.chat_regex() regex = await config.chat_regex()
match: Optional[re.Match[str]] = re.match(regex, text) match: Optional[re.Match[str]] = re.match(regex, text)
if match: if match:
groups = {"username": match.group(1), "message": match.group(2)} groups = {"username": match.group(1), "message": match.group(2)}
logger.trace("Message is a chat message\n%s", json.dumps(groups)) logger.trace("Message is a chat message\n%s", json.dumps(groups))
return groups return groups
return None return False
async def check_if_join_message(text: str) -> Union[bool, str]:
async def check_if_join_message(text: str) -> Optional[str]:
regex = await config.join_regex() regex = await config.join_regex()
match: Optional[re.Match[str]] = re.match(regex, text) match: Optional[re.Match[str]] = re.match(regex, text)
if match: if match:
logger.trace("Message is a join message") logger.trace("Message is a join message")
return match.group(1) return match.group(1)
return None return False
async def check_if_leave_message(text: str) -> Union[bool, str]:
async def check_if_leave_message(text: str) -> Optional[str]:
regex = await config.leave_regex() regex = await config.leave_regex()
match: Optional[re.Match[str]] = re.match(regex, text) match: Optional[re.Match[str]] = re.match(regex, text)
if match: if match:
logger.trace("Message is a leave message") logger.trace("Message is a leave message")
return match.group(1) return match.group(1)
return None return False
async def check_if_achievement_message(text: str) -> Union[bool, dict]:
async def check_if_achievement_message(text: str) -> Optional[dict]:
regex = await config.achievement_regex() regex = await config.achievement_regex()
match: Optional[re.Match[str]] = re.match(regex, text) match: Optional[re.Match[str]] = re.match(regex, text)
if match: if match:
@ -222,8 +205,7 @@ async def check_if_achievement_message(text: str) -> Optional[dict]:
groups["challenge"] = False groups["challenge"] = False
logger.trace("Message is an achievement message") logger.trace("Message is an achievement message")
return groups return groups
return None return False
async def get_info(username: str) -> Optional[dict]: async def get_info(username: str) -> Optional[dict]:
logger.verbose("Retrieving player info for %s", username) logger.verbose("Retrieving player info for %s", username)
@ -236,7 +218,6 @@ async def get_info(username: str) -> Optional[dict]:
logger.warning("Failed to retrieve player info for %s: %s", username, response.status) logger.warning("Failed to retrieve player info for %s: %s", username, response.status)
return None return None
async def send_chat_discord(coginstance: Pterodactyl, username: str, message: str, avatar_url: str) -> None: async def send_chat_discord(coginstance: Pterodactyl, username: str, message: str, avatar_url: str) -> None:
logger.trace("Sending chat message to Discord") logger.trace("Sending chat message to Discord")
channel = coginstance.bot.get_channel(await config.chat_channel()) channel = coginstance.bot.get_channel(await config.chat_channel())
@ -250,7 +231,6 @@ async def send_chat_discord(coginstance: Pterodactyl, username: str, message: st
else: else:
logger.warning("Chat channel not set. Skipping sending chat message to Discord") logger.warning("Chat channel not set. Skipping sending chat message to Discord")
async def generate_join_leave_embed(coginstance: Pterodactyl, username: str, join: bool) -> Tuple[discord.Embed, Optional[Union[str, Path]]]: async def generate_join_leave_embed(coginstance: Pterodactyl, username: str, join: bool) -> Tuple[discord.Embed, Optional[Union[str, Path]]]:
embed = discord.Embed() embed = discord.Embed()
embed.color = discord.Color.green() if join else discord.Color.red() embed.color = discord.Color.green() if join else discord.Color.red()
@ -258,32 +238,30 @@ async def generate_join_leave_embed(coginstance: Pterodactyl, username: str, joi
info = await get_info(username) info = await get_info(username)
if info: if info:
img = None img = None
embed.set_author(name=username, icon_url=info["data"]["player"]["avatar"]) embed.set_author(name=username, icon_url=info['data']['player']['avatar'])
else: else:
img = bundled_data_path(coginstance) / "unknown.png" img = bundled_data_path(coginstance) / "unknown.png"
embed.set_author(name=username, icon_url="attachment://unknown.png") embed.set_author(name=username, icon_url='attachment://unknown.png')
embed.timestamp = discord.utils.utcnow() embed.timestamp = discord.utils.utcnow()
return embed, img return embed, img
async def generate_achievement_embed(coginstance: Pterodactyl, username: str, achievement: str, challenge: bool) -> Tuple[discord.Embed, Optional[Union[str, Path]]]: async def generate_achievement_embed(coginstance: Pterodactyl, username: str, achievement: str, challenge: bool) -> Tuple[discord.Embed, Optional[Union[str, Path]]]:
embed = discord.Embed() embed = discord.Embed()
embed.color = discord.Color.from_str("#a800a7") if challenge else discord.Color.from_str("#54fb54") embed.color = discord.Color.from_str('#a800a7') if challenge else discord.Color.from_str('#54fb54')
embed.description = f"{bold(username)} has {'completed the challenge' if challenge else 'made the advancement'} {bold(achievement)}" embed.description = f"{bold(username)} has {'completed the challenge' if challenge else 'made the advancement'} {bold(achievement)}"
info = await get_info(username) info = await get_info(username)
if info: if info:
img = None img = None
embed.set_author(name=username, icon_url=info["data"]["player"]["avatar"]) embed.set_author(name=username, icon_url=info['data']['player']['avatar'])
else: else:
img = bundled_data_path(coginstance) / "unknown.png" img = bundled_data_path(coginstance) / "unknown.png"
embed.set_author(name=username, icon_url="attachment://unknown.png") embed.set_author(name=username, icon_url='attachment://unknown.png')
embed.timestamp = discord.utils.utcnow() embed.timestamp = discord.utils.utcnow()
return embed, img return embed, img
def mask_ip(string: str) -> str: def mask_ip(string: str) -> str:
def check(match: re.Match[str]): def check(match: re.Match[str]):
ip = match.group(0) ip = match.group(0)
return ".".join(r"\*" * len(octet) for octet in ip.split(".")) masked_ip = '.'.join(r'\*' * len(octet) for octet in ip.split('.'))
return masked_ip
return re.sub(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", check, string) return re.sub(r'\b(?:\d{1,3}\.){3}\d{1,3}\b', check, string)

View file

@ -1,76 +1,76 @@
[project] [tool.poetry]
name = "seacogs" name = "seacogs"
version = "0.1.0" version = "0.1.0"
description = "My assorted cogs for Red-DiscordBot." description = "My assorted cogs for Red-DiscordBot."
authors = [{ name = "cswimr", email = "seaswimmerthefsh@gmail.com" }] authors = ["cswimr"]
license = { file = "LICENSE" } license = "MPL 2"
readme = "README.md" readme = "README.md"
requires-python = ">=3.11" package-mode = false
dependencies = [
"aiosqlite==0.21.0",
"beautifulsoup4==4.13.3",
"colorthief==0.2.1",
"markdownify==1.1.0",
"numpy==2.2.4",
"phx-class-registry==5.1.1",
"pillow==10.4.0",
"pip==25.0.1",
"py-dactyl",
"pydantic==2.11.1",
"red-discordbot==3.5.18",
"watchdog==6.0.0",
"websockets==15.0.1",
]
[dependency-groups] [tool.poetry.dependencies]
documentation = [ python = ">=3.11,<3.12"
"mkdocs==1.6.1", Red-DiscordBot = "^3.5.5"
"mkdocs-git-authors-plugin==0.9.4", py-dactyl = "^2.0.4"
"mkdocs-git-revision-date-localized-plugin==1.4.5", websockets = "^12.0"
"mkdocs-material[imaging]==9.6.10", pillow = "^10.3.0"
"mkdocs-redirects==1.2.2", numpy = "^1.26.4"
"mkdocstrings[python]==0.29.0", colorthief = "^0.2.1"
] beautifulsoup4 = "^4.12.3"
markdownify = "^0.12.1"
py-lav = {extras = ["all"], version = ">=1.14.3,<1.15"}
[tool.uv] [tool.poetry.group.dev]
dev-dependencies = ["pylint==3.3.6", "ruff==0.11.2", "sqlite-web==0.6.4"] optional = true
[tool.uv.sources] [tool.poetry.group.dev.dependencies]
py-dactyl = { git = "https://github.com/iamkubi/pydactyl", tag = "v2.0.5" } ruff = "^0.3.1"
pylint = "^3.1.0"
sqlite-web = "^0.6.4"
[tool.basedpyright] [tool.poetry.group.docs]
typeCheckingMode = "basic" optional = true
reportAttributeAccessIssue = false # disabled because `commands.group.command` is listed as Any / Unknown for some reason
[tool.poetry.group.docs.dependencies]
mkdocs = "1.5.3"
mkdocstrings = {extras = ["python"], version = "0.24.0"}
mkdocs-git-authors-plugin = "0.7.2"
mkdocs-git-revision-date-localized-plugin = "1.2.2"
mkdocs-material = {extras = ["imaging"], version = "^9.5.2"}
mkdocs-redirects = "^1.2.1"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
[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.
@ -84,32 +84,8 @@ target-version = "py311"
# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default. # Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
# 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 = ["F", "W", "E", "C901"]
"I", ignore = ["C901"]
"N",
"F",
"W",
"E",
"G",
"A",
"COM",
"INP",
"T20",
"PLC",
"PLE",
"PLW",
"PLR",
"LOG",
"SLF",
"ERA",
"FIX",
"PERF",
"C4",
"EM",
"RET",
"RSE",
]
ignore = ["PLR0911", "PLR0912", "PLR0915", "PLR2004", "PLR0913", "EM101"]
# Allow fix for all enabled rules (when `--fix`) is provided. # Allow fix for all enabled rules (when `--fix`) is provided.
fixable = ["ALL"] fixable = ["ALL"]

View file

@ -1,5 +0,0 @@
{
"extends": [
"local>cc/renovate-config"
]
}

View file

@ -1,11 +1,10 @@
{ {
"$schema": "https://raw.githubusercontent.com/Cog-Creators/Red-DiscordBot/refs/heads/V3/develop/schema/red_cog_repo.schema.json", "author" : ["cswimr"],
"author": ["cswimr"], "install_msg" : "Thank you for installing SeaUtils!\nYou can find the source code of this cog [here](https://coastalcommits.com/cswimr/SeaCogs).",
"install_msg": "Thank you for installing SeaUtils!\nYou can find the source code of this cog [here](https://coastalcommits.com/cswimr/SeaCogs).", "name" : "SeaUtils",
"name": "SeaUtils", "short" : "A collection of useful utilities.",
"short": "A collection of useful utilities.", "description" : "A collection of useful utilities.",
"description": "A collection of useful utilities.", "end_user_data_statement" : "This cog does not store end user data.",
"end_user_data_statement": "This cog does not store end user data.",
"hidden": true, "hidden": true,
"disabled": false, "disabled": false,
"min_bot_version": "3.5.0", "min_bot_version": "3.5.0",

View file

@ -29,20 +29,18 @@ from redbot.core.utils.views import SimpleMenu
def md(soup: BeautifulSoup, **options) -> Any | str: def md(soup: BeautifulSoup, **options) -> Any | str:
return MarkdownConverter(**options).convert_soup(soup=soup) return MarkdownConverter(**options).convert_soup(soup=soup)
def format_rfc_text(text: str, number: int) -> str: def format_rfc_text(text: str, number: int) -> str:
one: str = re.sub(r"\(\.\/rfc(\d+)", r"(https://www.rfc-editor.org/rfc/rfc\1.html", text) one: str = re.sub(r"\(\.\/rfc(\d+)", r"(https://www.rfc-editor.org/rfc/rfc\1.html", text)
two: str = re.sub(r"\((#(?:section|page)-\d+(?:.\d+)?)\)", f"(https://www.rfc-editor.org/rfc/rfc{number}.html\1)", one) two: str = re.sub(r"\((#(?:section|page)-\d+(?:.\d+)?)\)", f"(https://www.rfc-editor.org/rfc/rfc{number}.html\1)", one)
three: str = re.sub(r"\n{3,}", "\n\n", two) three: str = re.sub(r"\n{3,}", "\n\n", two)
return three return three
class SeaUtils(commands.Cog): class SeaUtils(commands.Cog):
"""A collection of random utilities.""" """A collection of random utilities."""
__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.0.2" __version__ = "1.0.1"
__documentation__ = "https://seacogs.coastalcommits.com/seautils/" __documentation__ = "https://seacogs.coastalcommits.com/seautils/"
def __init__(self, bot: Red) -> None: def __init__(self, bot: Red) -> None:
@ -59,6 +57,7 @@ class SeaUtils(commands.Cog):
] ]
return "\n".join(text) return "\n".join(text)
def format_src(self, obj: Any) -> str: def format_src(self, obj: Any) -> str:
"""A large portion of this code is repurposed from Zephyrkul's RTFS cog. """A large portion of this code is repurposed from Zephyrkul's RTFS cog.
https://github.com/Zephyrkul/FluffyCogs/blob/master/rtfs/rtfs.py""" https://github.com/Zephyrkul/FluffyCogs/blob/master/rtfs/rtfs.py"""
@ -74,9 +73,9 @@ class SeaUtils(commands.Cog):
src = obj.function src = obj.function
return inspect.getsource(object=src) return inspect.getsource(object=src)
@commands.command(aliases=["source", "src", "code", "showsource"]) # type: ignore @commands.command(aliases=["source", "src", "code", "showsource"])
@commands.is_owner() @commands.is_owner()
async def showcode(self, ctx: commands.Context, *, object: str) -> None: # pylint: disable=redefined-builtin # noqa: A002 async def showcode(self, ctx: commands.Context, *, object: str) -> None: # pylint: disable=redefined-builtin
"""Show the code for a particular object.""" """Show the code for a particular object."""
try: try:
if object.startswith("/") and (obj := ctx.bot.tree.get_command(object[1:])): if object.startswith("/") and (obj := ctx.bot.tree.get_command(object[1:])):
@ -87,7 +86,11 @@ class SeaUtils(commands.Cog):
text = self.format_src(obj) text = self.format_src(obj)
else: else:
raise AttributeError raise AttributeError
temp_content = cf.pagify(text=cleanup_code(text), escape_mass_mentions=True, page_length=1977) temp_content = cf.pagify(
text=cleanup_code(text),
escape_mass_mentions=True,
page_length = 1977
)
content = [] content = []
max_i = operator.length_hint(temp_content) max_i = operator.length_hint(temp_content)
i = 1 i = 1
@ -102,7 +105,7 @@ class SeaUtils(commands.Cog):
else: else:
await ctx.send(content="Object not found!", reference=ctx.message.to_reference(fail_if_not_exists=False)) await ctx.send(content="Object not found!", reference=ctx.message.to_reference(fail_if_not_exists=False))
@commands.command(name="dig", aliases=["dnslookup", "nslookup"]) # type: ignore @commands.command(name='dig', aliases=['dnslookup', 'nslookup'])
@commands.is_owner() @commands.is_owner()
async def dig(self, ctx: commands.Context, name: str, record_type: str | None = None, server: str | None = None, port: int = 53) -> None: async def dig(self, ctx: commands.Context, name: str, record_type: str | None = None, server: str | None = None, port: int = 53) -> None:
"""Retrieve DNS information for a domain. """Retrieve DNS information for a domain.
@ -110,13 +113,13 @@ class SeaUtils(commands.Cog):
Uses `dig` to perform a DNS query. Will fall back to `nslookup` if `dig` is not installed on the system. Uses `dig` to perform a DNS query. Will fall back to `nslookup` if `dig` is not installed on the system.
`nslookup` does not provide as much information as `dig`, so only the `name` parameter will be used if `nslookup` is used. `nslookup` does not provide as much information as `dig`, so only the `name` parameter will be used if `nslookup` is used.
Will return the A, AAAA, and CNAME records for a domain by default. You can specify a different record type with the `type` parameter.""" Will return the A, AAAA, and CNAME records for a domain by default. You can specify a different record type with the `type` parameter."""
command_opts: list[str] = ["dig"] command_opts: list[str | int] = ['dig']
query_types: list[str] = [record_type] if record_type else ["A", "AAAA", "CNAME"] query_types: list[str] = [record_type] if record_type else ['A', 'AAAA', 'CNAME']
if server: if server:
command_opts.extend(["@", server]) command_opts.extend(['@', server])
for query_type in query_types: for query_type in query_types:
command_opts.extend([name, query_type]) command_opts.extend([name, query_type])
command_opts.extend(["-p", str(port), "+yaml"]) command_opts.extend(['-p', str(port), '+yaml'])
try: try:
process: Process = await asyncio.create_subprocess_exec(*command_opts, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) process: Process = await asyncio.create_subprocess_exec(*command_opts, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
@ -125,18 +128,22 @@ class SeaUtils(commands.Cog):
await ctx.maybe_send_embed(message="An error was encountered!\n" + cf.box(text=stderr.decode())) await ctx.maybe_send_embed(message="An error was encountered!\n" + cf.box(text=stderr.decode()))
else: else:
data = yaml.safe_load(stdout.decode()) data = yaml.safe_load(stdout.decode())
message_data: dict = data[0]["message"] message_data: dict = data[0]['message']
response_data: dict = message_data["response_message_data"] response_data: dict = message_data['response_message_data']
if ctx.embed_requested(): if ctx.embed_requested():
embed = Embed(title="DNS Query Result", color=await ctx.embed_color(), timestamp=message_data["response_time"]) embed = Embed(
embed.add_field(name="Response Address", value=message_data["response_address"], inline=True) title="DNS Query Result",
embed.add_field(name="Response Port", value=message_data["response_port"], inline=True) color=await ctx.embed_color(),
embed.add_field(name="Query Address", value=message_data["query_address"], inline=True) timestamp=message_data['response_time']
embed.add_field(name="Query Port", value=message_data["query_port"], inline=True) )
embed.add_field(name="Status", value=response_data["status"], inline=True) embed.add_field(name="Response Address", value=message_data['response_address'], inline=True)
embed.add_field(name="Flags", value=response_data["flags"], inline=True) embed.add_field(name="Response Port", value=message_data['response_port'], inline=True)
embed.add_field(name="Query Address", value=message_data['query_address'], inline=True)
embed.add_field(name="Query Port", value=message_data['query_port'], inline=True)
embed.add_field(name="Status", value=response_data['status'], inline=True)
embed.add_field(name="Flags", value=response_data['flags'], inline=True)
if response_data.get("status") != "NOERROR": if response_data.get('status') != 'NOERROR':
embed.colour = Color.red() embed.colour = Color.red()
embed.description = cf.error("Dig query did not return `NOERROR` status.") embed.description = cf.error("Dig query did not return `NOERROR` status.")
@ -144,19 +151,19 @@ class SeaUtils(commands.Cog):
answers = [] answers = []
authorities = [] authorities = []
for m in data: for m in data:
response = m["message"]["response_message_data"] response = m['message']['response_message_data']
if "QUESTION_SECTION" in response: if 'QUESTION_SECTION' in response:
for question in response["QUESTION_SECTION"]: for question in response['QUESTION_SECTION']:
if question not in questions: if question not in questions:
questions.append(question) questions.append(question)
if "ANSWER_SECTION" in response: if 'ANSWER_SECTION' in response:
for answer in response["ANSWER_SECTION"]: for answer in response['ANSWER_SECTION']:
if answer not in answers: if answer not in answers:
answers.append(answer) answers.append(answer)
if "AUTHORITY_SECTION" in response: if 'AUTHORITY_SECTION' in response:
for authority in response["AUTHORITY_SECTION"]: for authority in response['AUTHORITY_SECTION']:
if authority not in authorities: if authority not in authorities:
authorities.append(authority) authorities.append(authority)
@ -176,22 +183,26 @@ class SeaUtils(commands.Cog):
embed.add_field(name="Authority Section", value=f"{cf.box(text=authority_section, lang='prolog')}", inline=False) embed.add_field(name="Authority Section", value=f"{cf.box(text=authority_section, lang='prolog')}", inline=False)
await ctx.send(embed=embed) await ctx.send(embed=embed)
else: else:
await ctx.send(content=cf.box(text=str(stdout), lang="yaml")) await ctx.send(content=cf.box(text=stdout, lang='yaml'))
except FileNotFoundError: except (FileNotFoundError):
try: try:
ns_process = await asyncio.create_subprocess_exec("nslookup", name, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) ns_process = await asyncio.create_subprocess_exec('nslookup', name, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
ns_stdout, ns_stderr = await ns_process.communicate() ns_stdout, ns_stderr = await ns_process.communicate()
if ns_stderr: if ns_stderr:
await ctx.maybe_send_embed(message="An error was encountered!\n" + cf.box(text=ns_stderr.decode())) await ctx.maybe_send_embed(message="An error was encountered!\n" + cf.box(text=ns_stderr.decode()))
else: else:
warning = cf.warning("`dig` is not installed! Defaulting to `nslookup`.\nThis command provides more information when `dig` is installed on the system.\n") warning = cf.warning("`dig` is not installed! Defaulting to `nslookup`.\nThis command provides more information when `dig` is installed on the system.\n")
if await ctx.embed_requested(): if await ctx.embed_requested():
embed = Embed(title="DNS Query Result", color=await ctx.embed_color(), timestamp=ctx.message.created_at) embed = Embed(
title="DNS Query Result",
color=await ctx.embed_color(),
timestamp=ctx.message.created_at
)
embed.description = warning + cf.box(text=ns_stdout.decode()) embed.description = warning + cf.box(text=ns_stdout.decode())
await ctx.send(embed=embed) await ctx.send(embed=embed)
else: else:
await ctx.send(content=warning + cf.box(text=ns_stdout.decode())) await ctx.send(content = warning + cf.box(text=ns_stdout.decode()))
except FileNotFoundError: except (FileNotFoundError):
await ctx.maybe_send_embed(message=cf.error("Neither `dig` nor `nslookup` are installed on the system. Unable to resolve DNS query.")) await ctx.maybe_send_embed(message=cf.error("Neither `dig` nor `nslookup` are installed on the system. Unable to resolve DNS query."))
@commands.command() @commands.command()
@ -199,34 +210,45 @@ class SeaUtils(commands.Cog):
"""Retrieve the text of an RFC document. """Retrieve the text of an RFC document.
This command uses the [RFC Editor website](https://www.rfc-editor.org/) to fetch the text of an RFC document. This command uses the [RFC Editor website](https://www.rfc-editor.org/) to fetch the text of an RFC document.
A [Request for Comments (RFC)](https://en.wikipedia.org/wiki/Request_for_Comments) is a publication in a series from the principal technical development and standards-setting bodies for the [Internet](https://en.wikipedia.org/wiki/Internet), most prominently the [Internet Engineering Task Force](https://en.wikipedia.org/wiki/Internet_Engineering_Task_Force). An RFC is authored by individuals or groups of engineers and [computer scientists](https://en.wikipedia.org/wiki/Computer_scientist) in the form of a [memorandum](https://en.wikipedia.org/wiki/Memorandum) describing methods, behaviors, research, or innovations applicable to the working of the Internet and Internet-connected systems. It is submitted either for [peer review](https://en.wikipedia.org/wiki/Peer_review) or to convey new concepts, information, or, occasionally, engineering humor.""" # noqa: E501 A [Request for Comments (RFC)](https://en.wikipedia.org/wiki/Request_for_Comments) is a publication in a series from the principal technical development and standards-setting bodies for the [Internet](https://en.wikipedia.org/wiki/Internet), most prominently the [Internet Engineering Task Force](https://en.wikipedia.org/wiki/Internet_Engineering_Task_Force). An RFC is authored by individuals or groups of engineers and [computer scientists](https://en.wikipedia.org/wiki/Computer_scientist) in the form of a [memorandum](https://en.wikipedia.org/wiki/Memorandum) describing methods, behaviors, research, or innovations applicable to the working of the Internet and Internet-connected systems. It is submitted either for [peer review](https://en.wikipedia.org/wiki/Peer_review) or to convey new concepts, information, or, occasionally, engineering humor.""" # noqa: E501
url = f"https://www.rfc-editor.org/rfc/rfc{number}.html" url = f"https://www.rfc-editor.org/rfc/rfc{number}.html"
datatracker_url = f"https://datatracker.ietf.org/doc/rfc{number}" datatracker_url = f"https://datatracker.ietf.org/doc/rfc{number}"
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
async with session.get(url=url) as response: async with session.get(url=url) as response:
if response.status == 200: if response.status == 200:
html = await response.text() html = await response.text()
soup = BeautifulSoup(html, "html.parser") soup = BeautifulSoup(html, 'html.parser')
pre_tags = soup.find_all("pre") pre_tags = soup.find_all('pre')
content: list[str | Embed] = [] content: list[Embed | str] = []
for pre_tag in pre_tags: for pre_tag in pre_tags:
text = format_rfc_text(md(pre_tag), number) text = format_rfc_text(md(pre_tag), number)
if len(text) > 4096: if len(text) > 4096:
pagified_text = cf.pagify(text, delims=["\n\n"], page_length=4096) pagified_text = cf.pagify(text, delims=["\n\n"], page_length=4096)
for page in pagified_text: for page in pagified_text:
if await ctx.embed_requested(): if await ctx.embed_requested():
embed = Embed(title=f"RFC Document {number}", url=datatracker_url, description=page, color=await ctx.embed_color()) embed = Embed(
title=f"RFC Document {number}",
url=datatracker_url,
description=page,
color=await ctx.embed_color()
)
content.append(embed) content.append(embed)
else: else:
content.append(page) content.append(page)
elif await ctx.embed_requested():
embed = Embed(title=f"RFC Document {number}", url=datatracker_url, description=text, color=await ctx.embed_color())
content.append(embed)
else: else:
content.append(text) if await ctx.embed_requested():
embed = Embed(
title=f"RFC Document {number}",
url=datatracker_url,
description=text,
color=await ctx.embed_color()
)
content.append(embed)
else:
content.append(text)
if await ctx.embed_requested(): if await ctx.embed_requested():
for embed in content: for embed in content:
embed.set_footer(text=f"Page {content.index(embed) + 1}/{len(content)}") embed.set_footer(text=f"Page {content.index(embed) + 1}/{len(content)}")
await SimpleMenu(pages=content, disable_after_timeout=True, timeout=300).start(ctx) # type: ignore await SimpleMenu(pages=content, disable_after_timeout=True, timeout=300).start(ctx)
else: else:
await ctx.maybe_send_embed(message=cf.error(f"An error occurred while fetching RFC {number}. Status code: {response.status}.")) await ctx.maybe_send_embed(message=cf.error(f"An error occurred while fetching RFC {number}. Status code: {response.status}."))

12
tts/__init__.py Normal file
View file

@ -0,0 +1,12 @@
from __future__ import annotations
from pylav.extension.red.utils.required_methods import pylav_auto_setup
from pylav.type_hints.bot import DISCORD_BOT_TYPE
from redbot.core.utils import get_end_user_data_statement
from .tts import TTS
__red_end_user_data_statement__ = get_end_user_data_statement(__file__)
async def setup(bot: DISCORD_BOT_TYPE):
await pylav_auto_setup(bot, TTS)

14
tts/config.py Normal file
View file

@ -0,0 +1,14 @@
from redbot.core import Config
config: Config = Config.get_conf(None, identifier=69737245070283, cog_name="TTS")
def register_config(config_obj: Config):
config_obj.register_global(
use_google_tts = False,
)
config_obj.register_guild(
enabled_channels = [],
announce = False,
voice_channels = True
)

21
tts/info.json Normal file
View file

@ -0,0 +1,21 @@
{
"author" : ["SeaswimmerTheFsh (seasw.)"],
"install_msg" : "Thank you for installing TTS!\nPlease read the [documentation](https://seacogs.coastalcommits.com/tts) for more information.\nYou can find the source code of this cog [here](https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs).",
"name" : "TTS",
"short" : "Text to Speech through Pylav",
"description" : "Text to Speech through Pylav",
"end_user_data_statement" : "This cog does not store end user data.",
"hidden": false,
"disabled": false,
"min_bot_version": "3.5.0",
"min_python_version": [3, 11, 0],
"requirements": [
"Py-Lav[all]"
],
"tags": [
"pylav",
"audio",
"tts"
],
"required_cogs": {"audio" : "https://github.com/PyLav/Red-Cogs"}
}

68
tts/menu.py Normal file
View file

@ -0,0 +1,68 @@
from discord import ButtonStyle, Embed, Interaction, ui
from redbot.core import commands
from redbot.core.utils.chat_formatting import bold
from tts.config import config
class Menu(ui.View):
def __init__(self, ctx: commands.Context):
super().__init__()
self.ctx = ctx
@ui.button(label="Announce", style=ButtonStyle.green, row=0)
async def announce(self, interaction: Interaction, button: ui.Button):
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.guild(interaction.guild).announce
await config.guild(interaction.guild).announce.set(not current_setting)
await interaction.message.edit(embed=await embed(self.ctx))
@ui.button(label="Use Voice Channels", style=ButtonStyle.green, row=0)
async def voice_channels(self, interaction: Interaction, button: ui.Button):
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.guild(interaction.guild).voice_channels()
await config.guild(interaction.guild).voice_channels.set(not current_setting)
await interaction.message.edit(embed=await embed(self.ctx))
@ui.select(placeholder="Enabled Channels", cls=ui.ChannelSelect, row=1)
async def log_channel(self, interaction: Interaction, select: ui.ChannelSelect):
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()
channels: list = await config.guild(interaction.guild).enabled_channels()
if select.values[0] in channels:
channels.remove(select.values[0])
else:
channels.append(select.values[0])
await config.guild(interaction.guild).enabled_channels.set(channels)
await interaction.message.edit(embed=await embed(self.ctx))
async def embed(ctx: commands.Context):
embed = Embed(title="TTS Settings", color=ctx.embed_color)
override_settings = {
"announce": await config.guild(ctx.guild).announce(),
"voice_channels": await config.guild(ctx.guild).voice_channels(),
"enabled_channels": await config.guild(ctx.guild).enabled_channels(),
}
override_str = [
"- " + bold("Announce: ") + get_bool_emoji(override_settings["announce"]),
"- " + bold("Voice Channels: ") + get_bool_emoji(override_settings["voice_channels"]),
"- " + ", ".join([f"<#{channel}>" for channel in override_settings["voice_channels"]])
]
embed.description = "\n".join(override_str)
def get_bool_emoji(value: bool) -> str:
"""Returns a unicode emoji based on a boolean value."""
if value is True:
return "\N{WHITE HEAVY CHECK MARK}"
if value is False:
return "\N{NO ENTRY SIGN}"
return "\N{BLACK QUESTION MARK ORNAMENT}\N{VARIATION SELECTOR-16}"

57
tts/tts.py Normal file
View file

@ -0,0 +1,57 @@
# _____ _
# / ____| (_)
# | (___ ___ __ _ _____ ___ _ __ ___ _ __ ___ ___ _ __
# \___ \ / _ \/ _` / __\ \ /\ / / | '_ ` _ \| '_ ` _ \ / _ \ '__|
# ____) | __/ (_| \__ \\ V V /| | | | | | | | | | | | __/ |
# |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_|
import logging
from discord import Message
from redbot.core import commands
from redbot.core.bot import Red
from tts.config import config
from tts.menu import Menu, embed
class TTS(commands.Cog):
"""Text to Speech through Pylav"""
def __init__(self, bot: Red):
self.bot = bot
self.logger = logging.getLogger("red.sea.tts")
async def on_message(self, message: Message):
await self.bot.wait_until_red_ready()
if message.author.bot:
return
if message.guild is None:
return
valid_prefixes = await self.bot.get_valid_prefixes(message.guild)
valid_prefixes.append("\\")
if any(message.content.startswith(prefix) for prefix in valid_prefixes):
return
if message.channel.id in await self.config.guild(message.guild).enabled_channels():
pylav = self.bot.get_cog("PyLavPlayer")
if pylav is None:
self.logger.error("PyLav is not loaded, so TTS is not available.")
await message.reply("PyLav is not loaded, so TTS is not available.\nPlease report this to the bot owner.\nIf you are the bot owner, see [https://github.com/PyLav/Red-Cogs](PyLav/RedCogs) for more information.")
return
#TODO - add PyLav integration
return
@commands.group(name="tts")
@commands.admin_or_permissions(manage_guild=True)
async def tts(self, ctx: commands.Context):
"""Text to Speech settings"""
await ctx.send(embed=await embed(ctx), view=Menu(ctx))
@tts.command(name="google")
@commands.is_owner()
async def tts_google(self, ctx: commands.Context, enable: bool = None):
"""Enable or disable Google Cloud TTS"""
if enable is None:
enable = not await config.use_google_tts()
await config.use_google_tts.set(enable)
await ctx.send(f"Google TTS has been {'enabled' if enable else 'disabled'}.")

2075
uv.lock generated

File diff suppressed because it is too large Load diff