Merge branch 'main' into tts
|
@ -80,9 +80,23 @@ Manage the immunity whitelist.
|
||||||
- Usage: `[p]aurora timedelta <duration>`
|
- Usage: `[p]aurora timedelta <duration>`
|
||||||
- Aliases: `tdc, td, and timedeltaconvert`
|
- Aliases: `tdc, td, and timedeltaconvert`
|
||||||
|
|
||||||
This command converts a duration to a [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) Python object.
|
This command converts a duration to a [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) Python object.You cannot convert years or months as they are not fixed units. Use `[p]aurora relativedelta` for that.
|
||||||
|
|
||||||
**Example usage**
|
**Example usage**
|
||||||
`[p]timedelta 1 day 15hr 82 minutes 52s`
|
`[p]aurora timedelta 1 day 15hr 82 minutes 52s`
|
||||||
|
|
||||||
**Output**
|
**Output**
|
||||||
`1 day, 16:22:52`
|
`1 day, 16:22:52`
|
||||||
|
|
||||||
|
### aurora relativedelta
|
||||||
|
|
||||||
|
- Usage: `[p]aurora relativedelta <duration>`
|
||||||
|
- Aliases: `rdc, rd, and relativedeltaconvert`
|
||||||
|
|
||||||
|
This command converts a duration to a [`relativedelta`](https://dateutil.readthedocs.io/en/stable/relativedelta.html) Python object.
|
||||||
|
|
||||||
|
**Example usage**
|
||||||
|
`[p]aurora relativedelta 3 years 1 day 15hr 82 minutes 52s`
|
||||||
|
|
||||||
|
**Output**
|
||||||
|
`relativedelta(years=+3, days=+1, hours=+15, minutes=+82, seconds=+52)`
|
||||||
|
|
|
@ -10,7 +10,7 @@ Aurora is a fully-featured moderation system. It is heavily inspired by Galactic
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
[p]repo add seacogs https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs
|
[p]repo add seacogs https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs
|
||||||
[p]cog install seacogs aurora
|
[p]cog install seacogs aurora
|
||||||
[p]cog load aurora
|
[p]cog load aurora
|
||||||
```
|
```
|
||||||
|
|
|
@ -23,19 +23,27 @@ Add a note to a user.
|
||||||
|
|
||||||
Warn a user.
|
Warn a user.
|
||||||
|
|
||||||
## blacklist
|
## addrole
|
||||||
|
|
||||||
/// admonition | This command is unfinished, and doesn't currently work.
|
- Usage: `/addrole <target> <role> <reason> [duration] [silent]`
|
||||||
type: warning
|
- `target:` (Required) Who are you adding a role to?
|
||||||
///
|
- `role:` (Required) What role are you adding to the target?
|
||||||
|
- `reason:` (Required) Why are you adding a role to this user?
|
||||||
- Usage: `/blacklist <target> <role> <reason> [silent]`
|
- `duration:` (Optional) How long are you adding this role for?
|
||||||
- `target:` (Required) Who are you blacklisting?
|
|
||||||
- `role:` (Required) What blacklist type are you applying to the target?
|
|
||||||
- `reason:` (Required) Why are you blacklisting this user?
|
|
||||||
- `silent:` (Optional) Should the user be messaged?
|
- `silent:` (Optional) Should the user be messaged?
|
||||||
|
|
||||||
Add a blacklist role to a user.
|
Add a role to a user.
|
||||||
|
|
||||||
|
## removerole
|
||||||
|
|
||||||
|
- Usage: `/removerole <target> <role> <reason> [duration] [silent]`
|
||||||
|
- `target:` (Required) Who are you removing a role from?
|
||||||
|
- `role:` (Required) What role are you removing from the target?
|
||||||
|
- `reason:` (Required) Why are you removing a role from this user?
|
||||||
|
- `duration:` (Optional) How long are you removing this role for?
|
||||||
|
- `silent:` (Optional) Should the user be messaged?
|
||||||
|
|
||||||
|
Remove a role from a user.
|
||||||
|
|
||||||
## mute
|
## mute
|
||||||
|
|
||||||
|
|
|
@ -5,11 +5,19 @@ Backup allows you to export a JSON list of all of your installed repositories an
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
[p]repo add seacogs https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs
|
[p]repo add seacogs https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs
|
||||||
[p]cog install seacogs backup
|
[p]cog install seacogs backup
|
||||||
[p]cog load backup
|
[p]cog load backup
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Version Compatibility
|
||||||
|
|
||||||
|
As of commit [1edb08a](https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs/commit/1edb08a1271f12098ca0bed11a735f7162cedd14), the Backup cog no longer supports Red versions older than 3.5.6. If you want to use the cog on an earlier version (3.5.0 - 3.5.5), install the cog pinned to this commit: `43464db6a7c51bc69282b1ae3dc507a4aae851de`.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
[p]cog installversion sea-cogs 43464db6a7c51bc69282b1ae3dc507a4aae851de backup
|
||||||
|
```
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
### backup export
|
### backup export
|
||||||
|
|
|
@ -6,7 +6,7 @@ This cog does require an api key to work.
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
[p]repo add seacogs https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs
|
[p]repo add seacogs https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs
|
||||||
[p]cog install seacogs bible
|
[p]cog install seacogs bible
|
||||||
[p]cog load bible
|
[p]cog load bible
|
||||||
```
|
```
|
||||||
|
|
BIN
.docs/img/pterodactyl/installing-red/1.png
Normal file
After Width: | Height: | Size: 181 KiB |
BIN
.docs/img/pterodactyl/installing-red/2.png
Normal file
After Width: | Height: | Size: 168 KiB |
BIN
.docs/img/pterodactyl/installing-red/3.png
Normal file
After Width: | Height: | Size: 274 KiB |
BIN
.docs/img/pterodactyl/setup/1.png
Normal file
After Width: | Height: | Size: 167 KiB |
BIN
.docs/img/pterodactyl/setup/10.png
Normal file
After Width: | Height: | Size: 31 KiB |
BIN
.docs/img/pterodactyl/setup/2.png
Normal file
After Width: | Height: | Size: 52 KiB |
BIN
.docs/img/pterodactyl/setup/3.png
Normal file
After Width: | Height: | Size: 114 KiB |
BIN
.docs/img/pterodactyl/setup/4.png
Normal file
After Width: | Height: | Size: 129 KiB |
BIN
.docs/img/pterodactyl/setup/5.png
Normal file
After Width: | Height: | Size: 135 KiB |
BIN
.docs/img/pterodactyl/setup/6.png
Normal file
After Width: | Height: | Size: 35 KiB |
BIN
.docs/img/pterodactyl/setup/7.png
Normal file
After Width: | Height: | Size: 3.2 KiB |
BIN
.docs/img/pterodactyl/setup/8.png
Normal file
After Width: | Height: | Size: 38 KiB |
BIN
.docs/img/pterodactyl/setup/9.png
Normal file
After Width: | Height: | Size: 150 KiB |
|
@ -5,7 +5,7 @@ Nerdify allows you to nerdify other people's text.
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
[p]repo add seacogs https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs
|
[p]repo add seacogs https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs
|
||||||
[p]cog install seacogs nerdify
|
[p]cog install seacogs nerdify
|
||||||
[p]cog load nerdify
|
[p]cog load nerdify
|
||||||
```
|
```
|
||||||
|
|
199
.docs/pterodactyl/configuration.md
Normal file
|
@ -0,0 +1,199 @@
|
||||||
|
# Configuration
|
||||||
|
|
||||||
|
This page will go over all of the configuration options for the Pterodactyl cog.
|
||||||
|
All of the commands below can be accessed through `[p]pterodactyl config`.
|
||||||
|
|
||||||
|
## `api`
|
||||||
|
|
||||||
|
This option determines which [PlayerDB](https://playerdb.co/) endpoint the cog will use to retrieve player avatars.
|
||||||
|
This is only used for webhook avatars in the chat integration system. You should probably leave this as default.
|
||||||
|
|
||||||
|
Default value: `minecraft`
|
||||||
|
|
||||||
|
## `chat`
|
||||||
|
|
||||||
|
### `channel`
|
||||||
|
|
||||||
|
This option determines what channel chat messages will be sent to. If this is unset, the chat integration won't work.
|
||||||
|
**Make sure the bot has permissions to speak in this channel!**
|
||||||
|
|
||||||
|
Default value: `None`
|
||||||
|
|
||||||
|
### `command`
|
||||||
|
|
||||||
|
This option determines what command will be sent to the server whenever a message is sent in the configured chat channel. The JSON format Minecraft uses for this is very janky sometimes, if you need help with changing the command, you can join my [Discord server](https://discord.gg/eMUMe77Yb8).
|
||||||
|
|
||||||
|
Available placeholders:
|
||||||
|
|
||||||
|
- `.$C` - replaced with hex color of the author's top colored role
|
||||||
|
- `.$D` - replaced with the author's discriminator (will usually be 0, you shouldn't use this)
|
||||||
|
- `.$I` - replaced with the author's ID
|
||||||
|
- `.$M` - replaced with message content
|
||||||
|
- `.$N` - replaced with author's display name (or guild nickname, if set)
|
||||||
|
- `.$U` - replaced with the author's username (NOT display name, you should usually use `.$N`)
|
||||||
|
- `.$V` - replaced with the configured invite link
|
||||||
|
|
||||||
|
Default value:
|
||||||
|
|
||||||
|
```json
|
||||||
|
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"}]
|
||||||
|
```
|
||||||
|
|
||||||
|
## `console`
|
||||||
|
|
||||||
|
### `channel`
|
||||||
|
|
||||||
|
/// admonition | Only give access to the console channel to people you trust!
|
||||||
|
type: danger
|
||||||
|
If a user account has access to the console channel, they can execute ***any*** command on your server, including some power actions.
|
||||||
|
They will also be able to see potentially sensitive information, such as player IPs, if [IP Masking](configuration.md#ip) is disabled.
|
||||||
|
///
|
||||||
|
|
||||||
|
This option determines what channel console logs will be sent to. If this is unset, the console integration won't work.
|
||||||
|
**Make sure the bot has permissions to speak in this channel!**
|
||||||
|
Server status changes, Discord --> Minecraft chat messages, and command executions will all be logged here.
|
||||||
|
|
||||||
|
/// admonition
|
||||||
|
type: info
|
||||||
|
Please note that, in order to avoid Discord ratelimits, logs will not be posted when the server status is one of the following:
|
||||||
|
|
||||||
|
- `starting`
|
||||||
|
- `stopping`
|
||||||
|
|
||||||
|
This is to prevent the console channel from flooding and getting backed up by Discord's message ratelimits.
|
||||||
|
///
|
||||||
|
|
||||||
|
Default value: `None`
|
||||||
|
|
||||||
|
### `commands`
|
||||||
|
|
||||||
|
/// admonition | This has no effect on the `[p]pterodactyl command` text command, or the matching slash command.
|
||||||
|
type: danger
|
||||||
|
If you want to disable the ability to execute commands on the server through Discord, use the following commands:
|
||||||
|
`[p]pterodactyl config console commands False` - this command
|
||||||
|
`[p]command disable pterodactyl command` - disables the text command that lets you execute commands on the server
|
||||||
|
`[p]slash disable pterodactyl` - due to how slash commands are laid out, this is the only way to disable the ability to execute commands on the server
|
||||||
|
`[p]slash sync` - apply above slash command change
|
||||||
|
///
|
||||||
|
|
||||||
|
This option determines if commands sent to the console channel will be sent to the Pterodactyl console.
|
||||||
|
|
||||||
|
Default value: `False`
|
||||||
|
|
||||||
|
## `invite`
|
||||||
|
|
||||||
|
This option determines what url the chat command will substitute in for the Discord invite placeholder.
|
||||||
|
|
||||||
|
Default value: `None`
|
||||||
|
|
||||||
|
## `ip`
|
||||||
|
|
||||||
|
This option determines whether or not IP's will be redacted when posted in chat or to the console channel.
|
||||||
|
|
||||||
|
Default value: `True`
|
||||||
|
|
||||||
|
## `messages`
|
||||||
|
|
||||||
|
### `join`
|
||||||
|
|
||||||
|
This option determines what the description in embeds will be when a user joins the server. Has no effect if embeds aren't used.
|
||||||
|
|
||||||
|
Default value: `Welcome to the server! 👋`
|
||||||
|
|
||||||
|
### `leave`
|
||||||
|
|
||||||
|
This option determines what the description in embeds will be when a user leaves the server. Has no effect if embeds aren't used.
|
||||||
|
|
||||||
|
Default value: `Goodbye! 👋`
|
||||||
|
|
||||||
|
### `shutdown`
|
||||||
|
|
||||||
|
This option determines what the bot will send in the chat channel when the server stops.
|
||||||
|
|
||||||
|
Default value: `Server stopped!`
|
||||||
|
|
||||||
|
### `startup`
|
||||||
|
|
||||||
|
This option determines what the bot will send in the chat channel when the server is started.
|
||||||
|
|
||||||
|
Default value: `Server started!`
|
||||||
|
|
||||||
|
## `regex`
|
||||||
|
|
||||||
|
If you're not running on recent versions of Paper, which this cog was developed against, or you're otherwise changing for format of chat messages, you'll need to add custom regex through the `[p]pterodactyl config regex` command. Same thing applies if any other type of message isn't being detected. I recomend using ChatGPT or something similar for this, or if you need help, you can join my [Discord server](https://discord.gg/eMUMe77Yb8).
|
||||||
|
See [Regex Examples](regex.md) for default values.
|
||||||
|
|
||||||
|
### `blacklist`
|
||||||
|
|
||||||
|
This group of commands allows you to add regex patterns that will be ignored by the console logger. The intended use for this is if you're getting ratelimited by messages that flood the console after the server sets its status to `running` but before it actually finishes starting.
|
||||||
|
|
||||||
|
### `achievement`
|
||||||
|
|
||||||
|
This regex pattern is used to detect advacnements/challenges. The default should work for most Minecraft servers.
|
||||||
|
|
||||||
|
### `chat`
|
||||||
|
|
||||||
|
This regex pattern is used to detect chat messages. You will probably have to change this if you're using any plugins or mods that use custom chat formatting, like EssentialsX Chat or Styled Chat.
|
||||||
|
|
||||||
|
### `join`
|
||||||
|
|
||||||
|
This regex pattern is used to detect whenever a user joins the server. You shouldn't usually need to change this.
|
||||||
|
|
||||||
|
### `leave`
|
||||||
|
|
||||||
|
This regex pattern is used to detect whenever a user leaves the server. You shouldn't usually need to change this.
|
||||||
|
|
||||||
|
### `server`
|
||||||
|
|
||||||
|
This regex pattern is used to detect whenever a server message is sent. You will have to change this if you aren't running on Paper, most likely.
|
||||||
|
|
||||||
|
## `serverid`
|
||||||
|
|
||||||
|
This option determines which server's websocket to connect to. See [Getting Started](getting-started.md#getting-server-information) for more information on this.
|
||||||
|
|
||||||
|
Default value: `None`
|
||||||
|
|
||||||
|
## `topic`
|
||||||
|
|
||||||
|
### `host`
|
||||||
|
|
||||||
|
This option determines the hostname of your server that will be used to retrieve server information.
|
||||||
|
|
||||||
|
### `port`
|
||||||
|
|
||||||
|
This option determines the port of your server that will be used to retrieve server information.
|
||||||
|
|
||||||
|
Default value: `25565`
|
||||||
|
|
||||||
|
### `text`
|
||||||
|
|
||||||
|
This option determines what the channel topic will be set to.
|
||||||
|
|
||||||
|
Available placeholders:
|
||||||
|
|
||||||
|
- `.$H` - replaced with the server's hostname
|
||||||
|
- `.$O` - replaced with the server's port
|
||||||
|
|
||||||
|
Available with a Minecraft server:
|
||||||
|
|
||||||
|
- `.$I` - replaced with the server's ip address
|
||||||
|
- `.$M` - replaced with maximum player count
|
||||||
|
- `.$P` - replaced with current online player count
|
||||||
|
- `.$V` - replaced with the server's current version
|
||||||
|
- `.$D` - replaced with the server's description / message of the day
|
||||||
|
|
||||||
|
Default value:
|
||||||
|
|
||||||
|
```
|
||||||
|
Server IP: .$H\nServer Players: .$P/.$M
|
||||||
|
```
|
||||||
|
|
||||||
|
## `url`
|
||||||
|
|
||||||
|
This option determines what panel the cog will send requests to. See [Getting Started](getting-started.md#getting-server-information) for more information on this.
|
||||||
|
|
||||||
|
Default value: `None`
|
||||||
|
|
||||||
|
## `view`
|
||||||
|
|
||||||
|
Lists all of the configuration options offered by the cog.
|
104
.docs/pterodactyl/getting-started.md
Normal file
|
@ -0,0 +1,104 @@
|
||||||
|
# Getting Started
|
||||||
|
|
||||||
|
This page will go over the steps required to get started with the Pterodactyl cog.
|
||||||
|
|
||||||
|
/// admonition | Screenshots may be visually distinct
|
||||||
|
type: info
|
||||||
|
For the purpose of this guide, I'll be using [Bloom Host's](https://bloom.host/) [Pterodactyl fork](https://mc.bloom.host/).
|
||||||
|
The steps should be basically identical for other panels, but screenshots will look visually different.
|
||||||
|
If in doubt, contact your host's support.
|
||||||
|
///
|
||||||
|
|
||||||
|
## Installing the cog
|
||||||
|
|
||||||
|
This project is a [cog](https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html) made for use with *specifically* instances of [Red-DiscordBot](https://github.com/Cog-Creators/Red-DiscordBot).
|
||||||
|
See the [Red documentation](https://docs.discord.red/en/stable/install_guides/index.html) for information on how to run an instance of Red. Once you've got it running, come back here.
|
||||||
|
|
||||||
|
/// admonition | `[p]` is your bot's prefix
|
||||||
|
type: tip
|
||||||
|
///
|
||||||
|
|
||||||
|
Now, load the Downloader cog:
|
||||||
|
|
||||||
|
```
|
||||||
|
[p]load downloader
|
||||||
|
```
|
||||||
|
|
||||||
|
The Downloader cog allows you to add Git repositories to your bot in order to download cogs from them.
|
||||||
|
Now, use Downloader to add my repository to your bot:
|
||||||
|
|
||||||
|
```
|
||||||
|
[p]repo add sea-cogs https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs
|
||||||
|
```
|
||||||
|
|
||||||
|
Now, install the Pterodactyl cog:
|
||||||
|
|
||||||
|
```
|
||||||
|
[p]cog install sea-cogs pterodactyl
|
||||||
|
[p]load pterodactyl
|
||||||
|
```
|
||||||
|
|
||||||
|
## Creating a sub-user
|
||||||
|
|
||||||
|
This is **optional**, but highly recommended, for security reasons.
|
||||||
|
|
||||||
|
Navigate to your `Users` page, and click the `New User` button.
|
||||||
|
Type in an email address, and scroll down to the `Control` header.
|
||||||
|
Click the checkmark on that header to select all of the permissions contained under the header.
|
||||||
|
Now, scroll back up to the top of the prompt and press `Invite User`.
|
||||||
|
|
||||||
|
![image](../img/pterodactyl/setup/1.png)
|
||||||
|
![image](../img/pterodactyl/setup/2.png)
|
||||||
|
|
||||||
|
Now, you'll need to check the email you just entered into the subusers page, and create an account. I won't cover this, as it'll change depending on what host you're using.
|
||||||
|
|
||||||
|
## Getting an API Key
|
||||||
|
|
||||||
|
**Log out of your primary account, and switch to the sub-user you just created.**
|
||||||
|
|
||||||
|
Navigate to your sub-user account's `API Credentials` page.
|
||||||
|
|
||||||
|
![image](../img/pterodactyl/setup/3.png)
|
||||||
|
|
||||||
|
Create a new API key.
|
||||||
|
|
||||||
|
![image](../img/pterodactyl/setup/4.png)
|
||||||
|
|
||||||
|
You don't have to specify an allowed IP if you don't want to, but I recommend it. If you chose to, you'll need to retrieve your bot's IP address. You can do this through SSH or through a cog like [AAA3A's IP cog](https://github.com/AAA3A-AAA3A/AAA3A-cogs).
|
||||||
|
|
||||||
|
![image](../img/pterodactyl/setup/5.png)
|
||||||
|
|
||||||
|
Now, use the `[p]set api` command on your bot to add the API key.
|
||||||
|
The format is as follows:
|
||||||
|
|
||||||
|
```
|
||||||
|
# Service: pterodactyl
|
||||||
|
# Keys and Tokens: api_key ptlc_...
|
||||||
|
```
|
||||||
|
|
||||||
|
![image](../img/pterodactyl/setup/6.png)
|
||||||
|
|
||||||
|
## Getting server information
|
||||||
|
|
||||||
|
There's some other information that the Pterodactyl cog needs to function.
|
||||||
|
|
||||||
|
First, get the base url for your panel. This does not include any extra information, like server ids, or whatnot. In my case, I'm using `https://mc.bloom.host/`.
|
||||||
|
|
||||||
|
![image](../img/pterodactyl/setup/7.png)
|
||||||
|
|
||||||
|
Use the `[p]pterodactyl config url` command to set the URL the cog will use.
|
||||||
|
In my case, I'd use `-pterodactyl config url https://mc.bloom.host/`.
|
||||||
|
|
||||||
|
![image](../img/pterodactyl/setup/8.png)
|
||||||
|
|
||||||
|
Now, we need to get the id of your server. Navigate to the `Settings` page in your panel.
|
||||||
|
|
||||||
|
![image](../img/pterodactyl/setup/9.png)
|
||||||
|
|
||||||
|
Use the `[p]pterodactyl config serverid` command to add the server id to the bot.
|
||||||
|
In my case, I'd use `-pterodactyl config serverid ad712016-df3d-47a5-b1df-6b71baf50340`.
|
||||||
|
|
||||||
|
![image](../img/pterodactyl/setup/10.png)
|
||||||
|
|
||||||
|
Once you've done all of this, you should see a connection message in the bot's logs. Now, we need to configure some other things.
|
||||||
|
See the [Configuration](configuration.md) page for more information.
|
16
.docs/pterodactyl/index.md
Normal file
|
@ -0,0 +1,16 @@
|
||||||
|
# Pterodactyl
|
||||||
|
|
||||||
|
/// admonition | This project is in active development
|
||||||
|
type: warning
|
||||||
|
These docs are not complete yet, and there is a lot still to do.
|
||||||
|
///
|
||||||
|
|
||||||
|
Pterodactyl allows for connecting to a Pterodactyl server through websockets. It is intended primarily for use with Minecraft servers, as it allows for version & server platform-agnostic Discord integration, including console logging and two-way chat bridging.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
[p]repo add seacogs https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs
|
||||||
|
[p]cog install seacogs pterodactyl
|
||||||
|
[p]cog load aurora
|
||||||
|
```
|
74
.docs/pterodactyl/installing-red.md
Normal file
|
@ -0,0 +1,74 @@
|
||||||
|
# Installing Red
|
||||||
|
|
||||||
|
This guide will explain how to create an instance of [Red-DiscordBot]() (referred to as 'Red') on a Pterodactyl panel.
|
||||||
|
|
||||||
|
Running the bot on Pterodactyl is not required to use the Pterodactyl cog. If you already have a working instance of Red, you should look at [Getting Started](getting-started.md).
|
||||||
|
|
||||||
|
/// admonition | Caveats
|
||||||
|
type: warning
|
||||||
|
There are a few caveats to running an instance of Red on Pterodactyl.
|
||||||
|
|
||||||
|
- You will not receive any support from the Red developers.
|
||||||
|
- The built-in Audio cog will not work.
|
||||||
|
- 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).
|
||||||
|
///
|
||||||
|
|
||||||
|
/// admonition | Requirements
|
||||||
|
type: info
|
||||||
|
- A Discord bot token (see [Creating a bot account](https://docs.discord.red/en/stable/bot_application_guide.html))
|
||||||
|
- A panel host with the [Red-DiscordBot Pterodactyl egg](https://github.com/ign-gg/Pterodactyl-Eggs/tree/master/bots/discord/redbot)
|
||||||
|
- A panel with support for server splitting, like [Bloom.host](https://bloom.host/)'s DuckPanel.
|
||||||
|
///
|
||||||
|
|
||||||
|
## Creating a Server Split
|
||||||
|
|
||||||
|
1. Navigate to your host's server split option.
|
||||||
|
2. Select `Discord Bots` in the `Server Category` dropdown
|
||||||
|
3. Select `Red` in the `Server Type` dropdown
|
||||||
|
4. Allocate 1gb of RAM to Red. You can get away with less, but for the purposes of this guide we'll be using 1gb.
|
||||||
|
5. Allocate 5gb of storage space to Red.
|
||||||
|
6. Click the `Split Server` button. The installation process will take a few minutes, once it's done, continue to the next section.
|
||||||
|
|
||||||
|
![server-split-img](../img/pterodactyl/installing-red/1.png)
|
||||||
|
|
||||||
|
## Configuring Startup Variables
|
||||||
|
|
||||||
|
1. Navigate to the `Startup` page of your new server split.
|
||||||
|
2. Enter in your bot token.
|
||||||
|
3. If you want to change the default prefix that the bot will respond to, do so here.
|
||||||
|
4. If you want to change the owner of the bot, you can do so here. This defaults to the owner of the application the bot user is from.
|
||||||
|
|
||||||
|
![server-startup-img](../img/pterodactyl/installing-red/2.png)
|
||||||
|
|
||||||
|
## Inviting the Bot
|
||||||
|
|
||||||
|
1. Navigate to the `Console` page of your server split.
|
||||||
|
2. Click the `Start` button.
|
||||||
|
3. Click the Invite URL in your console, once the bot starts.
|
||||||
|
|
||||||
|
![console-img](../img/pterodactyl/installing-red/3.png)
|
||||||
|
|
||||||
|
## Initial Setup
|
||||||
|
|
||||||
|
Red is quite a large bot, so I'll focus on the specifics of getting the bot working with my Pterodactyl cog specifically.
|
||||||
|
|
||||||
|
/// admonition | `[p]` is your bot's prefix
|
||||||
|
type: tip
|
||||||
|
///
|
||||||
|
|
||||||
|
1. Load the `Downloader` cog.
|
||||||
|
```bash
|
||||||
|
[p]load downloader
|
||||||
|
```
|
||||||
|
2. Add my repository to the bot
|
||||||
|
```bash
|
||||||
|
[p]repo add sea-cogs https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs
|
||||||
|
```
|
||||||
|
3. Install and load the Pterodactyl cog
|
||||||
|
```bash
|
||||||
|
[p]cog install sea-cogs pterodactyl
|
||||||
|
[p]load pterodactyl
|
||||||
|
```
|
||||||
|
4. Follow the instructions given in [Getting Started](getting-started.md)
|
65
.docs/pterodactyl/regex.md
Normal file
|
@ -0,0 +1,65 @@
|
||||||
|
# Regex Examples
|
||||||
|
|
||||||
|
## 1.20.4 - Paper (Default)
|
||||||
|
|
||||||
|
### Achievements
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2} INFO\]: (.*) has (made the advancement|completed the challenge) \[(.*)\]$
|
||||||
|
```
|
||||||
|
|
||||||
|
### Chat
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2}\sINFO\]: (?!\[(?:Server|Rcon)\])(?:<|\[)(\w+)(?:>|\]) (.*)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Join
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2} INFO\]: ([^<\n]+) joined the game$
|
||||||
|
```
|
||||||
|
|
||||||
|
### Leave
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2} INFO\]: ([^<\n]+) left the game$
|
||||||
|
```
|
||||||
|
|
||||||
|
### Server
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2} INFO\]:(?: \[Not Secure\])? \[(?:Server|Rcon)\] (.*)
|
||||||
|
```
|
||||||
|
|
||||||
|
## 1.20.1 - Forge
|
||||||
|
|
||||||
|
### Achievements
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2}\] \[Server thread\/INFO\] \[minecraft\/MinecraftServer\]: (.*) has (made the advancement|completed the challenge) \[(.*)\]$
|
||||||
|
```
|
||||||
|
|
||||||
|
### Chat
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2}\] \[Server thread\/INFO\] \[minecraft\/MinecraftServer\]: (?!\[(?:Server|Rcon)\])(?:<|\[)(\w+)(?:>|\]) (.*)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Join
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2}\] \[Server thread\/INFO\] \[minecraft\/MinecraftServer\]: ([^<\n]+) joined the game$
|
||||||
|
```
|
||||||
|
|
||||||
|
### Leave
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2}\] \[Server thread\/INFO\] \[minecraft\/MinecraftServer\]: ([^<\n]+) left the game$
|
||||||
|
```
|
||||||
|
|
||||||
|
### Server
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2}\] \[Server thread\/INFO\] \[minecraft\/MinecraftServer\]: \[(?:Server|Rcon)\] (.*)
|
||||||
|
```
|
|
@ -1,23 +0,0 @@
|
||||||
---
|
|
||||||
name: Bug Report
|
|
||||||
about: Got an issue with a cog from SeaCogs? Use this.
|
|
||||||
title: "[BUG]"
|
|
||||||
labels: bug
|
|
||||||
assignees: ''
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
**Describe the bug**
|
|
||||||
A clear and concise description of what the bug is.
|
|
||||||
|
|
||||||
**To Reproduce**
|
|
||||||
What caused the error?
|
|
||||||
|
|
||||||
**Expected behavior**
|
|
||||||
A clear and concise description of what you expected to happen.
|
|
||||||
|
|
||||||
**Screenshots**
|
|
||||||
If applicable, add screenshots to help explain your problem.
|
|
||||||
|
|
||||||
**Additional context**
|
|
||||||
Add any other context about the problem here.
|
|
55
.forgejo/ISSUE_TEMPLATE/bug_report.yaml
Normal file
|
@ -0,0 +1,55 @@
|
||||||
|
name: Bug Report
|
||||||
|
about: File a bug report
|
||||||
|
title: "[Cog Name] "
|
||||||
|
labels: [bug]
|
||||||
|
ref: master
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
Thank you for taking the time to fill out this bug report!
|
||||||
|
- type: checkboxes
|
||||||
|
id: confirmation
|
||||||
|
attributes:
|
||||||
|
label: Please confirm that;
|
||||||
|
options:
|
||||||
|
- label: I have checked that this bug does not already have an opened/closed [issue](https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs/issues) or [pull request](https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs/pulls) associated with it.
|
||||||
|
required: true
|
||||||
|
- label: I have checked that I am on the latest version of [Red-DiscordBot](https://github.com/CogCreators/Red-DiscordBot), and SeaCogs.
|
||||||
|
required: true
|
||||||
|
- type: input
|
||||||
|
id: hosting
|
||||||
|
attributes:
|
||||||
|
label: Hosting
|
||||||
|
description: How is your bot hosted?
|
||||||
|
placeholder: Local, Docker, etc.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: what-happened
|
||||||
|
attributes:
|
||||||
|
label: What happened?
|
||||||
|
description: Also, what did you expect to happen?
|
||||||
|
placeholder: A bug happened!
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: reproduction
|
||||||
|
attributes:
|
||||||
|
label: Reproduction steps
|
||||||
|
description: Please provide detailed steps to reproduce the bug.
|
||||||
|
placeholder: |
|
||||||
|
1. Do this
|
||||||
|
2. Do that
|
||||||
|
3. Do this other thing
|
||||||
|
4. Bug happens!
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
|
- type: textarea
|
||||||
|
id: logs
|
||||||
|
attributes:
|
||||||
|
label: Relevant traceback or logs
|
||||||
|
description: Please copy and paste any relevant tracebacks or log output. This will be automatically formatted into code, so no need for backticks.
|
||||||
|
render: py
|
||||||
|
validations:
|
||||||
|
required: false
|
5
.forgejo/ISSUE_TEMPLATE/config.yaml
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
blank_issues_enabled: true
|
||||||
|
contact_links:
|
||||||
|
- name: Other Concerns?
|
||||||
|
url: https://discord.gg/eMUMe77Yb8
|
||||||
|
about: Ask in our Discord server!
|
|
@ -1,26 +0,0 @@
|
||||||
---
|
|
||||||
name: Suggestion
|
|
||||||
about: Trying to suggest something for SeaCogs? Use this.
|
|
||||||
title: "[SUGGESTION]"
|
|
||||||
labels: enhancement
|
|
||||||
assignees: ''
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
**What cog is your feature request for?**
|
|
||||||
A cog in this repository.
|
|
||||||
|
|
||||||
**Is your feature request related to a problem? Please describe.**
|
|
||||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
|
||||||
|
|
||||||
**Describe the solution you'd like**
|
|
||||||
A clear and concise description of what you want to happen.
|
|
||||||
|
|
||||||
**Describe alternatives you've considered**
|
|
||||||
A clear and concise description of any alternative solutions or features you've considered.
|
|
||||||
|
|
||||||
**Screenshots**
|
|
||||||
If applicable, add screenshots to help explain your problem.
|
|
||||||
|
|
||||||
**Additional context**
|
|
||||||
Add any other context about the problem here.
|
|
55
.forgejo/ISSUE_TEMPLATE/suggestion.yaml
Normal file
|
@ -0,0 +1,55 @@
|
||||||
|
name: Suggestion
|
||||||
|
about: Trying to suggest something for SeaCogs? Use this.
|
||||||
|
title: "[Cog Name] "
|
||||||
|
labels: enhancement
|
||||||
|
ref: master
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
Thank you for taking the time to suggest an enhancement!
|
||||||
|
- type: input
|
||||||
|
id: cog
|
||||||
|
attributes:
|
||||||
|
label: What cog is your feature request for?
|
||||||
|
description: Specify the cog within the repository.
|
||||||
|
placeholder: E.g., ModerationCog
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: problem-description
|
||||||
|
attributes:
|
||||||
|
label: Is your feature request related to a problem? Please describe.
|
||||||
|
placeholder: A clear and concise description of what the problem is.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: solution-description
|
||||||
|
attributes:
|
||||||
|
label: Describe the solution you'd like
|
||||||
|
placeholder: A clear and concise description of what you want to happen.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: alternatives
|
||||||
|
attributes:
|
||||||
|
label: Describe alternatives you've considered
|
||||||
|
placeholder: A clear and concise description of any alternative solutions or features you've considered.
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
|
- type: textarea
|
||||||
|
id: screenshots
|
||||||
|
attributes:
|
||||||
|
label: Screenshots
|
||||||
|
description: If applicable, add screenshots to help explain your problem.
|
||||||
|
placeholder: Paste image links here.
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
|
- type: textarea
|
||||||
|
id: additional-context
|
||||||
|
attributes:
|
||||||
|
label: Additional context
|
||||||
|
description: Add any other context about the problem here.
|
||||||
|
placeholder: Any extra information you think might be useful.
|
||||||
|
validations:
|
||||||
|
required: false
|
6
.forgejo/pull_request_template.md
Normal file
|
@ -0,0 +1,6 @@
|
||||||
|
# Describe what your pull request does and which issue you're targeting
|
||||||
|
|
||||||
|
<!-- Create a new issue, if it doesn't exist yet -->
|
||||||
|
|
||||||
|
- [ ] By submitting this pull request, I permit SeaswimmerTheFsh to license my work under
|
||||||
|
the [Mozilla Public License Version 2.0](https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs/src/branch/main/LICENSE).
|
|
@ -17,4 +17,5 @@
|
||||||
import-outside-toplevel,
|
import-outside-toplevel,
|
||||||
import-self,
|
import-self,
|
||||||
relative-beyond-top-level,
|
relative-beyond-top-level,
|
||||||
too-many-instance-attributes
|
too-many-instance-attributes,
|
||||||
|
duplicate-code
|
||||||
|
|
|
@ -17,11 +17,11 @@ jobs:
|
||||||
run: poetry install --with dev --no-root
|
run: poetry install --with dev --no-root
|
||||||
|
|
||||||
- name: Analysing code with Ruff
|
- name: Analysing code with Ruff
|
||||||
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: pylint --rcfile=.forgejo/workflows/config/.pylintrc $(git ls-files '*.py')
|
run: ./.venv/bin/pylint --rcfile=.forgejo/workflows/config/.pylintrc $(git ls-files '*.py')
|
||||||
|
|
||||||
Build Documentation (MkDocs):
|
Build Documentation (MkDocs):
|
||||||
runs-on: docker
|
runs-on: docker
|
||||||
|
@ -42,7 +42,7 @@ jobs:
|
||||||
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"
|
||||||
mkdocs build -v
|
./.venv/bin/mkdocs build -v
|
||||||
|
|
||||||
- name: Deploy documentation
|
- name: Deploy documentation
|
||||||
run: |
|
run: |
|
||||||
|
|
1
.gitignore
vendored
|
@ -1,3 +1,4 @@
|
||||||
.cache
|
.cache
|
||||||
.vscode
|
.vscode
|
||||||
site
|
site
|
||||||
|
.venv
|
||||||
|
|
5
antipolls/__init__.py
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
from .antipolls import AntiPolls
|
||||||
|
|
||||||
|
|
||||||
|
async def setup(bot):
|
||||||
|
await bot.add_cog(AntiPolls(bot))
|
180
antipolls/antipolls.py
Normal file
|
@ -0,0 +1,180 @@
|
||||||
|
# _____ _
|
||||||
|
# / ____| (_)
|
||||||
|
# | (___ ___ __ _ _____ ___ _ __ ___ _ __ ___ ___ _ __
|
||||||
|
# \___ \ / _ \/ _` / __\ \ /\ / / | '_ ` _ \| '_ ` _ \ / _ \ '__|
|
||||||
|
# ____) | __/ (_| \__ \\ V V /| | | | | | | | | | | | __/ |
|
||||||
|
# |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_|
|
||||||
|
|
||||||
|
import discord
|
||||||
|
from red_commons.logging import getLogger
|
||||||
|
from redbot.core import commands
|
||||||
|
from redbot.core.bot import Config, Red
|
||||||
|
from redbot.core.utils.chat_formatting import humanize_list
|
||||||
|
|
||||||
|
|
||||||
|
class AntiPolls(commands.Cog):
|
||||||
|
"""AntiPolls deletes messages that contain polls, with a configurable per-guild role and channel whitelist and support for default Discord permissions (Manage Messages)."""
|
||||||
|
|
||||||
|
__author__ = ["SeaswimmerTheFsh"]
|
||||||
|
__version__ = "1.0.0"
|
||||||
|
__documentation__ = "https://seacogs.coastalcommits.com/antipolls/"
|
||||||
|
|
||||||
|
def __init__(self, bot: Red):
|
||||||
|
super().__init__()
|
||||||
|
self.bot = bot
|
||||||
|
self.logger = getLogger("red.SeaCogs.AntiPolls")
|
||||||
|
self.config = Config.get_conf(self, identifier=23517395243, force_registration=True)
|
||||||
|
self.config.register_guild(
|
||||||
|
role_whitelist=[],
|
||||||
|
channel_whitelist=[],
|
||||||
|
manage_messages=True,
|
||||||
|
)
|
||||||
|
if not self.bot.intents.message_content:
|
||||||
|
self.logger.error("Message Content intent is not enabled, cog will not load.")
|
||||||
|
raise RuntimeError("This cog requires the Message Content intent to function. To prevent potentially destructive behavior, the cog will not load without the intent enabled.")
|
||||||
|
|
||||||
|
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"Cog Version: **{self.__version__}**",
|
||||||
|
f"Author: {humanize_list(self.__author__)}",
|
||||||
|
f"Documentation: {self.__documentation__}",
|
||||||
|
]
|
||||||
|
return "\n".join(text)
|
||||||
|
|
||||||
|
async def red_delete_data_for_user(self, **kwargs): # pylint: disable=unused-argument
|
||||||
|
"""Nothing to delete."""
|
||||||
|
return
|
||||||
|
|
||||||
|
@commands.Cog.listener('on_message')
|
||||||
|
async def polls_listener(self, message: discord.Message) -> None:
|
||||||
|
if message.guild is None:
|
||||||
|
return self.logger.verbose("Message in direct messages ignored")
|
||||||
|
|
||||||
|
if message.author.bot:
|
||||||
|
return self.logger.verbose("Message from bot ignored")
|
||||||
|
|
||||||
|
if await self.bot.cog_disabled_in_guild(self, message.guild):
|
||||||
|
return self.logger.verbose("Message ignored, cog is disabled in guild %s", message.guild.id)
|
||||||
|
|
||||||
|
guild_config = await self.config.guild(message.guild).all()
|
||||||
|
|
||||||
|
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")
|
||||||
|
|
||||||
|
if message.channel.id in guild_config['channel_whitelist']:
|
||||||
|
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):
|
||||||
|
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:
|
||||||
|
self.logger.trace("Message %s is a poll, attempting to delete", message.id)
|
||||||
|
|
||||||
|
try:
|
||||||
|
await message.delete()
|
||||||
|
except discord.HTTPException as e:
|
||||||
|
return self.logger.error("Failed to delete message: %s", e)
|
||||||
|
|
||||||
|
return self.logger.trace("Deleted poll message %s", message.id)
|
||||||
|
self.logger.verbose("Message %s is not a poll, ignoring", message.id)
|
||||||
|
|
||||||
|
@commands.group(name="antipolls", aliases=["ap"])
|
||||||
|
@commands.guild_only()
|
||||||
|
@commands.admin_or_permissions(manage_guild=True)
|
||||||
|
async def antipolls(self, ctx: commands.Context) -> None:
|
||||||
|
"""Manage AntiPolls settings."""
|
||||||
|
|
||||||
|
@antipolls.group(name="roles")
|
||||||
|
async def antipolls_roles(self, ctx: commands.Context) -> None:
|
||||||
|
"""Manage role whitelist."""
|
||||||
|
|
||||||
|
@antipolls_roles.command(name="add")
|
||||||
|
async def antipolls_roles_add(self, ctx: commands.Context, *roles: discord.Role) -> None:
|
||||||
|
"""Add roles to the whitelist."""
|
||||||
|
async with self.config.guild(ctx.guild).role_whitelist() as role_whitelist:
|
||||||
|
role_whitelist: list
|
||||||
|
failed: list[discord.Role] = []
|
||||||
|
for role in roles:
|
||||||
|
if role.id in role_whitelist:
|
||||||
|
failed.append(role)
|
||||||
|
continue
|
||||||
|
role_whitelist.append(role.id)
|
||||||
|
await ctx.tick()
|
||||||
|
if failed:
|
||||||
|
await ctx.send(f"The following roles were already in the whitelist: {humanize_list([role.mention for role in failed])}", delete_after=10)
|
||||||
|
|
||||||
|
@antipolls_roles.command(name="remove")
|
||||||
|
async def antipolls_roles_remove(self, ctx: commands.Context, *roles: discord.Role) -> None:
|
||||||
|
"""Remove roles from the whitelist."""
|
||||||
|
async with self.config.guild(ctx.guild).role_whitelist() as role_whitelist:
|
||||||
|
role_whitelist: list
|
||||||
|
failed: list[discord.Role] = []
|
||||||
|
for role in roles:
|
||||||
|
if role.id not in role_whitelist:
|
||||||
|
failed.append(role)
|
||||||
|
continue
|
||||||
|
role_whitelist.remove(role.id)
|
||||||
|
await ctx.tick()
|
||||||
|
if failed:
|
||||||
|
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")
|
||||||
|
async def antipolls_roles_list(self, ctx: commands.Context) -> None:
|
||||||
|
"""List roles in the whitelist."""
|
||||||
|
role_whitelist = await self.config.guild(ctx.guild).role_whitelist()
|
||||||
|
if not role_whitelist:
|
||||||
|
return await ctx.send("No roles in the whitelist.")
|
||||||
|
roles = [ctx.guild.get_role(role) for role in role_whitelist]
|
||||||
|
await ctx.send(humanize_list([role.mention for role in roles]))
|
||||||
|
|
||||||
|
@antipolls.group(name="channels")
|
||||||
|
async def antipolls_channels(self, ctx: commands.Context) -> None:
|
||||||
|
"""Manage channel whitelist."""
|
||||||
|
|
||||||
|
@antipolls_channels.command(name="add")
|
||||||
|
async def antipolls_channels_add(self, ctx: commands.Context, *channels: discord.TextChannel) -> None:
|
||||||
|
"""Add channels to the whitelist."""
|
||||||
|
async with self.config.guild(ctx.guild).channel_whitelist() as channel_whitelist:
|
||||||
|
channel_whitelist: list
|
||||||
|
failed: list[discord.TextChannel] = []
|
||||||
|
for channel in channels:
|
||||||
|
if channel.id in channel_whitelist:
|
||||||
|
failed.append(channel)
|
||||||
|
continue
|
||||||
|
channel_whitelist.append(channel.id)
|
||||||
|
await ctx.tick()
|
||||||
|
if failed:
|
||||||
|
await ctx.send(f"The following channels were already in the whitelist: {humanize_list([channel.mention for channel in failed])}", delete_after=10)
|
||||||
|
|
||||||
|
@antipolls_channels.command(name="remove")
|
||||||
|
async def antipolls_channels_remove(self, ctx: commands.Context, *channels: discord.TextChannel) -> None:
|
||||||
|
"""Remove channels from the whitelist."""
|
||||||
|
async with self.config.guild(ctx.guild).channel_whitelist() as channel_whitelist:
|
||||||
|
channel_whitelist: list
|
||||||
|
failed: list[discord.TextChannel] = []
|
||||||
|
for channel in channels:
|
||||||
|
if channel.id not in channel_whitelist:
|
||||||
|
failed.append(channel)
|
||||||
|
continue
|
||||||
|
channel_whitelist.remove(channel.id)
|
||||||
|
await ctx.tick()
|
||||||
|
if failed:
|
||||||
|
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")
|
||||||
|
async def antipolls_channels_list(self, ctx: commands.Context) -> None:
|
||||||
|
"""List channels in the whitelist."""
|
||||||
|
channel_whitelist = await self.config.guild(ctx.guild).channel_whitelist()
|
||||||
|
if not channel_whitelist:
|
||||||
|
return await ctx.send("No channels in the whitelist.")
|
||||||
|
channels = [ctx.guild.get_channel(channel) for channel in channel_whitelist]
|
||||||
|
await ctx.send(humanize_list([channel.mention for channel in channels]))
|
||||||
|
|
||||||
|
@antipolls.command(name="managemessages")
|
||||||
|
async def antipolls_managemessages(self, ctx: commands.Context, enabled: bool) -> None:
|
||||||
|
"""Toggle Manage Messages permission check."""
|
||||||
|
await self.config.guild(ctx.guild).manage_messages.set(enabled)
|
||||||
|
await ctx.tick()
|
17
antipolls/info.json
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
{
|
||||||
|
"author" : ["SeaswimmerTheFsh (seasw.)"],
|
||||||
|
"install_msg" : "Thank you for installing AntiPolls!\nYou can find the source code of this cog [here](https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs).",
|
||||||
|
"name" : "AntiPolls",
|
||||||
|
"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).",
|
||||||
|
"end_user_data_statement" : "This cog does not store any user data.",
|
||||||
|
"hidden": false,
|
||||||
|
"disabled": false,
|
||||||
|
"min_bot_version": "3.5.0",
|
||||||
|
"min_python_version": [3, 10, 0],
|
||||||
|
"tags": [
|
||||||
|
"automod",
|
||||||
|
"automoderation",
|
||||||
|
"polls"
|
||||||
|
]
|
||||||
|
}
|
360
aurora/aurora.py
|
@ -13,13 +13,14 @@ from datetime import datetime, timedelta, timezone
|
||||||
from math import ceil
|
from math import ceil
|
||||||
|
|
||||||
import discord
|
import discord
|
||||||
import humanize
|
from discord import Object
|
||||||
from discord.ext import tasks
|
from discord.ext import tasks
|
||||||
from pytimeparse2 import disable_dateutil, parse
|
|
||||||
from redbot.core import app_commands, commands, data_manager
|
from redbot.core import app_commands, commands, data_manager
|
||||||
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 box, error, warning
|
from redbot.core.commands.converter import parse_relativedelta, parse_timedelta
|
||||||
|
from redbot.core.utils.chat_formatting import (box, error, humanize_list,
|
||||||
|
humanize_timedelta, warning)
|
||||||
|
|
||||||
from aurora.importers.aurora import ImportAuroraView
|
from aurora.importers.aurora import ImportAuroraView
|
||||||
from aurora.importers.galacticbot import ImportGalacticBotView
|
from aurora.importers.galacticbot import ImportGalacticBotView
|
||||||
|
@ -38,7 +39,9 @@ from aurora.utilities.logger import logger
|
||||||
from aurora.utilities.utils import (check_moddable, check_permissions,
|
from aurora.utilities.utils import (check_moddable, check_permissions,
|
||||||
convert_timedelta_to_str,
|
convert_timedelta_to_str,
|
||||||
fetch_channel_dict, fetch_user_dict,
|
fetch_channel_dict, fetch_user_dict,
|
||||||
generate_dict, log, send_evidenceformat)
|
generate_dict, get_footer_image, log,
|
||||||
|
send_evidenceformat,
|
||||||
|
timedelta_from_relativedelta)
|
||||||
|
|
||||||
|
|
||||||
class Aurora(commands.Cog):
|
class Aurora(commands.Cog):
|
||||||
|
@ -46,8 +49,9 @@ class Aurora(commands.Cog):
|
||||||
It is heavily inspired by GalacticBot, and is designed to be a more user-friendly alternative to Red's core Mod cogs.
|
It is heavily inspired by GalacticBot, and is designed to be a more user-friendly alternative to Red's core Mod cogs.
|
||||||
This cog stores all of its data in an SQLite database."""
|
This cog stores all of its data in an SQLite database."""
|
||||||
|
|
||||||
__author__ = "SeaswimmerTheFsh"
|
__author__ = ["SeaswimmerTheFsh"]
|
||||||
__version__ = "2.0.5"
|
__version__ = "2.1.2"
|
||||||
|
__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):
|
||||||
if requester == "discord_deleted_user":
|
if requester == "discord_deleted_user":
|
||||||
|
@ -83,9 +87,19 @@ class Aurora(commands.Cog):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
register_config(config)
|
register_config(config)
|
||||||
disable_dateutil()
|
|
||||||
self.handle_expiry.start()
|
self.handle_expiry.start()
|
||||||
|
|
||||||
|
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"Cog Version: **{self.__version__}**",
|
||||||
|
f"Author: {humanize_list(self.__author__)}",
|
||||||
|
f"Documentation: {self.__documentation__}",
|
||||||
|
]
|
||||||
|
return "\n".join(text)
|
||||||
|
|
||||||
async def cog_load(self):
|
async def cog_load(self):
|
||||||
"""This method prepares the database schema for all of the guilds the bot is currently in."""
|
"""This method prepares the database schema for all of the guilds the bot is currently in."""
|
||||||
guilds: list[discord.Guild] = self.bot.guilds
|
guilds: list[discord.Guild] = self.bot.guilds
|
||||||
|
@ -110,6 +124,20 @@ class Aurora(commands.Cog):
|
||||||
except ConnectionRefusedError:
|
except ConnectionRefusedError:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
@commands.Cog.listener("on_member_join")
|
||||||
|
async def addrole_on_member_join(self, member: discord.Member):
|
||||||
|
"""This method automatically adds roles to users when they join the server."""
|
||||||
|
if not await self.bot.cog_disabled_in_guild(self, member.guild):
|
||||||
|
query = f"""SELECT moderation_id, role_id, reason FROM moderation_{member.guild.id} WHERE target_id = ? AND moderation_type = 'ADDROLE' AND expired = 0 AND resolved = 0;"""
|
||||||
|
database = connect()
|
||||||
|
cursor = database.cursor()
|
||||||
|
cursor.execute(query, (member.id,))
|
||||||
|
results = cursor.fetchall()
|
||||||
|
for result in results:
|
||||||
|
role = member.guild.get_role(result[1])
|
||||||
|
reason = result[2]
|
||||||
|
await member.add_roles(role, reason=f"Role automatically added on member rejoin for: {reason} (Case #{result[0]:,})")
|
||||||
|
|
||||||
@commands.Cog.listener("on_audit_log_entry_create")
|
@commands.Cog.listener("on_audit_log_entry_create")
|
||||||
async def autologger(self, entry: discord.AuditLogEntry):
|
async def autologger(self, entry: discord.AuditLogEntry):
|
||||||
"""This method automatically logs moderations done by users manually ("right clicks")."""
|
"""This method automatically logs moderations done by users manually ("right clicks")."""
|
||||||
|
@ -206,7 +234,7 @@ class Aurora(commands.Cog):
|
||||||
moderation_type="note",
|
moderation_type="note",
|
||||||
response=await interaction.original_response(),
|
response=await interaction.original_response(),
|
||||||
)
|
)
|
||||||
await target.send(embed=embed)
|
await target.send(embed=embed, file=get_footer_image(self))
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -265,7 +293,7 @@ class Aurora(commands.Cog):
|
||||||
moderation_type="warned",
|
moderation_type="warned",
|
||||||
response=await interaction.original_response(),
|
response=await interaction.original_response(),
|
||||||
)
|
)
|
||||||
await target.send(embed=embed)
|
await target.send(embed=embed, file=get_footer_image(self))
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -321,13 +349,10 @@ class Aurora(commands.Cog):
|
||||||
return
|
return
|
||||||
|
|
||||||
if duration is not None:
|
if duration is not None:
|
||||||
try:
|
parsed_time = parse_timedelta(duration)
|
||||||
parsed_time = parse(
|
if parsed_time is None:
|
||||||
sval=duration, as_timedelta=True, raise_exception=True
|
|
||||||
)
|
|
||||||
except ValueError:
|
|
||||||
await interaction.response.send_message(
|
await interaction.response.send_message(
|
||||||
error("Please provide a valid duration!"), ephemeral=True
|
content=error("Please provide a valid duration!"), ephemeral=True
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
else:
|
else:
|
||||||
|
@ -366,16 +391,16 @@ class Aurora(commands.Cog):
|
||||||
duration=parsed_time,
|
duration=parsed_time,
|
||||||
role=role,
|
role=role,
|
||||||
)
|
)
|
||||||
await target.send(embed=embed)
|
await target.send(embed=embed, file=get_footer_image(self))
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
await target.add_roles(
|
await target.add_roles(
|
||||||
role,
|
role,
|
||||||
reason=f"Role added by {interaction.user.id}{(' for ' + {humanize.precisedelta(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.precisedelta(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(
|
||||||
|
@ -389,7 +414,113 @@ class Aurora(commands.Cog):
|
||||||
reason,
|
reason,
|
||||||
)
|
)
|
||||||
await response.edit(
|
await response.edit(
|
||||||
content=f"{target.mention} has been given the {role.mention} role{(' for ' + {humanize.precisedelta(parsed_time)} if parsed_time != 'NULL' else '')}! (Case `#{moderation_id:,}`)\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 ''}! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`",
|
||||||
|
)
|
||||||
|
await log(interaction, moderation_id)
|
||||||
|
|
||||||
|
case = await fetch_case(moderation_id, interaction.guild.id)
|
||||||
|
await send_evidenceformat(interaction, case)
|
||||||
|
|
||||||
|
@app_commands.command(name="removerole")
|
||||||
|
async def removerole(
|
||||||
|
self,
|
||||||
|
interaction: discord.Interaction,
|
||||||
|
target: discord.Member,
|
||||||
|
role: discord.Role,
|
||||||
|
reason: str,
|
||||||
|
duration: str = None,
|
||||||
|
silent: bool = None,
|
||||||
|
):
|
||||||
|
"""Remove a role from a user.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
-----------
|
||||||
|
target: discord.Member
|
||||||
|
Who are you removing a role from?
|
||||||
|
role: discord.Role
|
||||||
|
What role are you removing from the target?
|
||||||
|
reason: str
|
||||||
|
Why are you removing a role from this user?
|
||||||
|
duration: str
|
||||||
|
How long are you removing this role for?
|
||||||
|
silent: bool
|
||||||
|
Should the user be messaged?"""
|
||||||
|
addrole_whitelist = await config.guild(interaction.guild).addrole_whitelist()
|
||||||
|
|
||||||
|
if not addrole_whitelist:
|
||||||
|
await interaction.response.send_message(
|
||||||
|
content=error("There are no whitelisted roles set for this server!"),
|
||||||
|
ephemeral=True,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
if duration is not None:
|
||||||
|
parsed_time = parse_timedelta(duration)
|
||||||
|
if parsed_time is None:
|
||||||
|
await interaction.response.send_message(
|
||||||
|
content=error("Please provide a valid duration!"), ephemeral=True
|
||||||
|
)
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
parsed_time = "NULL"
|
||||||
|
|
||||||
|
if role.id not in addrole_whitelist:
|
||||||
|
await interaction.response.send_message(
|
||||||
|
content=error("That role isn't whitelisted!"), ephemeral=True
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
if not await check_moddable(
|
||||||
|
target, interaction, ["moderate_members", "manage_roles"]
|
||||||
|
):
|
||||||
|
return
|
||||||
|
|
||||||
|
if role.id not in [user_role.id for user_role in target.roles]:
|
||||||
|
await interaction.response.send_message(
|
||||||
|
content=error(f"{target.mention} does not have this role!"),
|
||||||
|
ephemeral=True,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
await interaction.response.defer()
|
||||||
|
if silent is None:
|
||||||
|
silent = not await config.guild(interaction.guild).dm_users()
|
||||||
|
if silent is False:
|
||||||
|
try:
|
||||||
|
embed = await message_factory(
|
||||||
|
await self.bot.get_embed_color(interaction.channel),
|
||||||
|
guild=interaction.guild,
|
||||||
|
moderator=interaction.user,
|
||||||
|
reason=reason,
|
||||||
|
moderation_type="removerole",
|
||||||
|
response=await interaction.original_response(),
|
||||||
|
duration=parsed_time,
|
||||||
|
role=role,
|
||||||
|
)
|
||||||
|
await target.send(embed=embed, file=get_footer_image(self))
|
||||||
|
except discord.errors.HTTPException:
|
||||||
|
pass
|
||||||
|
|
||||||
|
await target.remove_roles(
|
||||||
|
role,
|
||||||
|
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(
|
||||||
|
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(
|
||||||
|
interaction.guild.id,
|
||||||
|
interaction.user.id,
|
||||||
|
"REMOVEROLE",
|
||||||
|
"USER",
|
||||||
|
target.id,
|
||||||
|
role.id,
|
||||||
|
parsed_time,
|
||||||
|
reason,
|
||||||
|
)
|
||||||
|
await response.edit(
|
||||||
|
content=f"{target.mention} has had the {role.mention} role removed{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''}! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`",
|
||||||
)
|
)
|
||||||
await log(interaction, moderation_id)
|
await log(interaction, moderation_id)
|
||||||
|
|
||||||
|
@ -429,16 +560,15 @@ class Aurora(commands.Cog):
|
||||||
return
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
parsed_time = parse(sval=duration, as_timedelta=True, raise_exception=True)
|
parsed_time = parse_timedelta(duration, maximum=timedelta(days=28))
|
||||||
except ValueError:
|
if parsed_time is None:
|
||||||
|
await interaction.response.send_message(
|
||||||
|
error("Please provide a valid duration!"), ephemeral=True
|
||||||
|
)
|
||||||
|
return
|
||||||
|
except commands.BadArgument:
|
||||||
await interaction.response.send_message(
|
await interaction.response.send_message(
|
||||||
error("Please provide a valid duration!"), ephemeral=True
|
error("Please provide a duration that is less than 28 days."), ephemeral=True
|
||||||
)
|
|
||||||
return
|
|
||||||
|
|
||||||
if parsed_time.total_seconds() / 1000 > 2419200000:
|
|
||||||
await interaction.response.send_message(
|
|
||||||
error("Please provide a duration that is less than 28 days.")
|
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
|
@ -447,7 +577,7 @@ class Aurora(commands.Cog):
|
||||||
)
|
)
|
||||||
|
|
||||||
await interaction.response.send_message(
|
await interaction.response.send_message(
|
||||||
content=f"{target.mention} has been muted for {humanize.precisedelta(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:
|
||||||
|
@ -463,7 +593,7 @@ class Aurora(commands.Cog):
|
||||||
response=await interaction.original_response(),
|
response=await interaction.original_response(),
|
||||||
duration=parsed_time,
|
duration=parsed_time,
|
||||||
)
|
)
|
||||||
await target.send(embed=embed)
|
await target.send(embed=embed, file=get_footer_image(self))
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -478,7 +608,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.precisedelta(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)
|
||||||
|
|
||||||
|
@ -538,7 +668,7 @@ class Aurora(commands.Cog):
|
||||||
moderation_type="unmuted",
|
moderation_type="unmuted",
|
||||||
response=await interaction.original_response(),
|
response=await interaction.original_response(),
|
||||||
)
|
)
|
||||||
await target.send(embed=embed)
|
await target.send(embed=embed, file=get_footer_image(self))
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -597,7 +727,7 @@ class Aurora(commands.Cog):
|
||||||
moderation_type="kicked",
|
moderation_type="kicked",
|
||||||
response=await interaction.original_response(),
|
response=await interaction.original_response(),
|
||||||
)
|
)
|
||||||
await target.send(embed=embed)
|
await target.send(embed=embed, file=get_footer_image(self))
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -673,18 +803,22 @@ class Aurora(commands.Cog):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
if duration:
|
if duration:
|
||||||
try:
|
parsed_time = parse_relativedelta(duration)
|
||||||
parsed_time = parse(
|
if parsed_time is None:
|
||||||
sval=duration, as_timedelta=True, raise_exception=True
|
await interaction.response.send_message(
|
||||||
|
content=error("Please provide a valid duration!"), ephemeral=True
|
||||||
)
|
)
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
parsed_time = timedelta_from_relativedelta(parsed_time)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
await interaction.response.send_message(
|
await interaction.response.send_message(
|
||||||
error("Please provide a valid duration!"), ephemeral=True
|
content=error("Please provide a valid duration!"), ephemeral=True
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
await interaction.response.send_message(
|
await interaction.response.send_message(
|
||||||
content=f"{target.mention} has been banned for {humanize.precisedelta(parsed_time)}!\n**Reason** - `{reason}`"
|
content=f"{target.mention} has been banned for {humanize_timedelta(timedelta=parsed_time)}!\n**Reason** - `{reason}`"
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
@ -697,7 +831,7 @@ class Aurora(commands.Cog):
|
||||||
response=await interaction.original_response(),
|
response=await interaction.original_response(),
|
||||||
duration=parsed_time,
|
duration=parsed_time,
|
||||||
)
|
)
|
||||||
await target.send(embed=embed)
|
await target.send(embed=embed, file=get_footer_image(self))
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -718,7 +852,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.precisedelta(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)
|
||||||
|
|
||||||
|
@ -741,7 +875,7 @@ class Aurora(commands.Cog):
|
||||||
moderation_type="banned",
|
moderation_type="banned",
|
||||||
response=await interaction.original_response(),
|
response=await interaction.original_response(),
|
||||||
)
|
)
|
||||||
await target.send(embed=embed)
|
await target.send(embed=embed, file=get_footer_image(self))
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -824,7 +958,7 @@ class Aurora(commands.Cog):
|
||||||
moderation_type="unbanned",
|
moderation_type="unbanned",
|
||||||
response=await interaction.original_response(),
|
response=await interaction.original_response(),
|
||||||
)
|
)
|
||||||
await target.send(embed=embed)
|
await target.send(embed=embed, file=get_footer_image(self))
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -1058,9 +1192,9 @@ class Aurora(commands.Cog):
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
duration_embed = (
|
duration_embed = (
|
||||||
f"{humanize.precisedelta(td)} | <t:{case['end_timestamp']}:R>"
|
f"{humanize_timedelta(timedelta=td)} | <t:{case['end_timestamp']}:R>"
|
||||||
if bool(case["expired"]) is False
|
if bool(case["expired"]) is False
|
||||||
else f"{humanize.precisedelta(td)} | Expired"
|
else f"{humanize_timedelta(timedelta=td)} | Expired"
|
||||||
)
|
)
|
||||||
field_value += f"\n**Duration:** {duration_embed}"
|
field_value += f"\n**Duration:** {duration_embed}"
|
||||||
|
|
||||||
|
@ -1303,7 +1437,7 @@ 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)}),
|
content=box(json.dumps(case_dict, indent=2), 'json'),
|
||||||
ephemeral=ephemeral,
|
ephemeral=ephemeral,
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
@ -1369,11 +1503,8 @@ class Aurora(commands.Cog):
|
||||||
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 duration:
|
if duration:
|
||||||
try:
|
parsed_time = parse_timedelta(duration)
|
||||||
parsed_time = parse(
|
if parsed_time is None:
|
||||||
sval=duration, as_timedelta=True, raise_exception=True
|
|
||||||
)
|
|
||||||
except ValueError:
|
|
||||||
await interaction.response.send_message(
|
await interaction.response.send_message(
|
||||||
error("Please provide a valid duration!"), ephemeral=True
|
error("Please provide a valid duration!"), ephemeral=True
|
||||||
)
|
)
|
||||||
|
@ -1486,10 +1617,13 @@ class Aurora(commands.Cog):
|
||||||
|
|
||||||
@tasks.loop(minutes=1)
|
@tasks.loop(minutes=1)
|
||||||
async def handle_expiry(self):
|
async def handle_expiry(self):
|
||||||
|
await self.bot.wait_until_red_ready()
|
||||||
current_time = time.time()
|
current_time = time.time()
|
||||||
database = connect()
|
database = connect()
|
||||||
cursor = database.cursor()
|
cursor = database.cursor()
|
||||||
global_num = 0
|
global_unban_num = 0
|
||||||
|
global_addrole_num = 0
|
||||||
|
global_removerole_num = 0
|
||||||
|
|
||||||
guilds: list[discord.Guild] = self.bot.guilds
|
guilds: list[discord.Guild] = self.bot.guilds
|
||||||
for guild in guilds:
|
for guild in guilds:
|
||||||
|
@ -1507,7 +1641,7 @@ class Aurora(commands.Cog):
|
||||||
target_ids = [row[0] for row in result]
|
target_ids = [row[0] for row in result]
|
||||||
moderation_ids = [row[1] for row in result]
|
moderation_ids = [row[1] for row in result]
|
||||||
|
|
||||||
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 = (
|
name = (
|
||||||
|
@ -1528,7 +1662,7 @@ class Aurora(commands.Cog):
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await user.send(embed=embed)
|
await user.send(embed=embed, file=get_footer_image(self))
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -1539,7 +1673,7 @@ class Aurora(commands.Cog):
|
||||||
guild.name,
|
guild.name,
|
||||||
guild.id,
|
guild.id,
|
||||||
)
|
)
|
||||||
num = num + 1
|
unban_num = unban_num + 1
|
||||||
except (
|
except (
|
||||||
discord.errors.NotFound,
|
discord.errors.NotFound,
|
||||||
discord.errors.Forbidden,
|
discord.errors.Forbidden,
|
||||||
|
@ -1554,12 +1688,10 @@ class Aurora(commands.Cog):
|
||||||
e,
|
e,
|
||||||
)
|
)
|
||||||
|
|
||||||
expiry_query = f"UPDATE `moderation_{guild.id}` SET expired = 1 WHERE (end_timestamp != 0 AND end_timestamp <= ? AND expired = 0 AND moderation_type != 'BLACKLIST') OR (expired = 0 AND resolved = 1 AND moderation_type != 'BLACKLIST')"
|
removerole_num = 0
|
||||||
cursor.execute(expiry_query, (time.time(),))
|
addrole_query = f"SELECT target_id, moderation_id, role_id FROM moderation_{guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'ADDROLE' AND expired = 0"
|
||||||
|
|
||||||
blacklist_query = f"SELECT target_id, moderation_id, role_id FROM moderation_{guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'BLACKLIST' AND expired = 0"
|
|
||||||
try:
|
try:
|
||||||
cursor.execute(blacklist_query, (time.time(),))
|
cursor.execute(addrole_query, (time.time(),))
|
||||||
result = cursor.fetchall()
|
result = cursor.fetchall()
|
||||||
except sqlite3.OperationalError:
|
except sqlite3.OperationalError:
|
||||||
continue
|
continue
|
||||||
|
@ -1571,27 +1703,72 @@ class Aurora(commands.Cog):
|
||||||
target_ids, moderation_ids, role_ids
|
target_ids, moderation_ids, role_ids
|
||||||
):
|
):
|
||||||
try:
|
try:
|
||||||
# member: discord.Member = await guild.fetch_member(target_id)
|
member = await guild.fetch_member(target_id)
|
||||||
|
|
||||||
role: discord.Role = guild.get_role(role_id)
|
await member.remove_roles(
|
||||||
if role is None:
|
Object(role_id), reason=f"Automatic role removal from case #{moderation_id}"
|
||||||
raise discord.errors.NotFound
|
)
|
||||||
|
|
||||||
|
removerole_num = removerole_num + 1
|
||||||
except (
|
except (
|
||||||
discord.errors.NotFound,
|
discord.errors.NotFound,
|
||||||
discord.errors.Forbidden,
|
discord.errors.Forbidden,
|
||||||
discord.errors.HTTPException,
|
discord.errors.HTTPException,
|
||||||
):
|
) as e:
|
||||||
|
logger.error(
|
||||||
|
"Removing the role %s from user %s failed due to: \n%s",
|
||||||
|
role_id,
|
||||||
|
target_id,
|
||||||
|
e,
|
||||||
|
)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
addrole_num = 0
|
||||||
|
removerole_query = f"SELECT target_id, moderation_id, role_id FROM moderation_{guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'REMOVEROLE' AND expired = 0"
|
||||||
|
try:
|
||||||
|
cursor.execute(removerole_query, (time.time(),))
|
||||||
|
result = cursor.fetchall()
|
||||||
|
except sqlite3.OperationalError:
|
||||||
|
continue
|
||||||
|
target_ids = [row[0] for row in result]
|
||||||
|
moderation_ids = [row[1] for row in result]
|
||||||
|
role_ids = [row[2] for row in result]
|
||||||
|
|
||||||
|
for target_id, moderation_id, role_id in zip(
|
||||||
|
target_ids, moderation_ids, role_ids
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
member = await guild.fetch_member(target_id)
|
||||||
|
|
||||||
|
await member.add_roles(
|
||||||
|
Object(role_id), reason=f"Automatic role addition from case #{moderation_id}"
|
||||||
|
)
|
||||||
|
|
||||||
|
addrole_num = addrole_num + 1
|
||||||
|
except (
|
||||||
|
discord.errors.NotFound,
|
||||||
|
discord.errors.Forbidden,
|
||||||
|
discord.errors.HTTPException,
|
||||||
|
) as e:
|
||||||
|
logger.error("Adding the role %s to user %s failed due to: \n%s", role_id, target_id, e)
|
||||||
|
continue
|
||||||
|
|
||||||
|
expiry_query = f"UPDATE `moderation_{guild.id}` SET expired = 1 WHERE (end_timestamp != 0 AND end_timestamp <= ? AND expired = 0) OR (expired = 0 AND resolved = 1);"
|
||||||
|
cursor.execute(expiry_query, (time.time(),))
|
||||||
|
|
||||||
per_guild_completion_time = (time.time() - time_per_guild) * 1000
|
per_guild_completion_time = (time.time() - time_per_guild) * 1000
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"Completed expiry loop for %s (%s) in %sms with %s users unbanned",
|
"Completed expiry loop for %s (%s) in %sms with %s users unbanned, %s roles added, and %s roles removed",
|
||||||
guild.name,
|
guild.name,
|
||||||
guild.id,
|
guild.id,
|
||||||
f"{per_guild_completion_time:.6f}",
|
f"{per_guild_completion_time:.6f}",
|
||||||
num,
|
unban_num,
|
||||||
|
addrole_num,
|
||||||
|
removerole_num,
|
||||||
)
|
)
|
||||||
global_num = global_num + num
|
global_unban_num = global_unban_num + unban_num
|
||||||
|
global_addrole_num = global_addrole_num + addrole_num
|
||||||
|
global_removerole_num = global_removerole_num + removerole_num
|
||||||
|
|
||||||
database.commit()
|
database.commit()
|
||||||
cursor.close()
|
cursor.close()
|
||||||
|
@ -1599,9 +1776,11 @@ class Aurora(commands.Cog):
|
||||||
|
|
||||||
completion_time = (time.time() - current_time) * 1000
|
completion_time = (time.time() - current_time) * 1000
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"Completed expiry loop in %sms with %s users unbanned",
|
"Completed expiry loop in %sms with %s users unbanned, %s roles added, and %s roles removed",
|
||||||
f"{completion_time:.6f}",
|
f"{completion_time:.6f}",
|
||||||
global_num,
|
global_unban_num,
|
||||||
|
global_addrole_num,
|
||||||
|
global_removerole_num,
|
||||||
)
|
)
|
||||||
|
|
||||||
########################################################################################################################
|
########################################################################################################################
|
||||||
|
@ -1619,14 +1798,16 @@ class Aurora(commands.Cog):
|
||||||
@aurora_settings.command(name="overrides", aliases=["override", "user"])
|
@aurora_settings.command(name="overrides", aliases=["override", "user"])
|
||||||
async def aurora_settings_overrides(self, ctx: commands.Context):
|
async def aurora_settings_overrides(self, ctx: commands.Context):
|
||||||
"""Manage Aurora's user overriddable settings."""
|
"""Manage Aurora's user overriddable settings."""
|
||||||
await ctx.send(embed=await overrides_embed(ctx), view=Overrides(ctx))
|
msg = await ctx.send(embed=await overrides_embed(ctx))
|
||||||
|
await msg.edit(view=Overrides(ctx, msg, 60))
|
||||||
|
|
||||||
@aurora_settings.command(name="guild", aliases=["server"])
|
@aurora_settings.command(name="guild", aliases=["server"])
|
||||||
@commands.admin_or_permissions(manage_guild=True)
|
@commands.admin_or_permissions(manage_guild=True)
|
||||||
@commands.guild_only()
|
@commands.guild_only()
|
||||||
async def aurora_settings_guild(self, ctx: commands.Context):
|
async def aurora_settings_guild(self, ctx: commands.Context):
|
||||||
"""Manage Aurora's guild settings."""
|
"""Manage Aurora's guild settings."""
|
||||||
await ctx.send(embed=await guild_embed(ctx), view=Guild(ctx))
|
msg = await ctx.send(embed=await guild_embed(ctx))
|
||||||
|
await msg.edit(view=Guild(ctx, msg, 60))
|
||||||
|
|
||||||
@aurora_settings.command(name="addrole", aliases=["removerole"])
|
@aurora_settings.command(name="addrole", aliases=["removerole"])
|
||||||
@commands.admin_or_permissions(manage_guild=True)
|
@commands.admin_or_permissions(manage_guild=True)
|
||||||
|
@ -1635,14 +1816,16 @@ class Aurora(commands.Cog):
|
||||||
"""Manage the addrole whitelist.
|
"""Manage the addrole whitelist.
|
||||||
|
|
||||||
Roles added to this list are also applied to `/removerole`."""
|
Roles added to this list are also applied to `/removerole`."""
|
||||||
await ctx.send(embed=await addrole_embed(ctx), view=Addrole(ctx))
|
msg = await ctx.send(embed=await addrole_embed(ctx))
|
||||||
|
await msg.edit(view=Addrole(ctx, msg, 60))
|
||||||
|
|
||||||
@aurora_settings.command(name="immunity")
|
@aurora_settings.command(name="immunity")
|
||||||
@commands.admin_or_permissions(manage_guild=True)
|
@commands.admin_or_permissions(manage_guild=True)
|
||||||
@commands.guild_only()
|
@commands.guild_only()
|
||||||
async def aurora_settings_immunity(self, ctx: commands.Context):
|
async def aurora_settings_immunity(self, ctx: commands.Context):
|
||||||
"""Manage the immunity whitelist."""
|
"""Manage the immunity whitelist."""
|
||||||
await ctx.send(embed=await immune_embed(ctx), view=Immune(ctx))
|
msg = await ctx.send(embed=await immune_embed(ctx))
|
||||||
|
await msg.edit(view=Immune(ctx, msg, 60))
|
||||||
|
|
||||||
@aurora.group(autohelp=True, name="import")
|
@aurora.group(autohelp=True, name="import")
|
||||||
@commands.admin()
|
@commands.admin()
|
||||||
|
@ -1689,15 +1872,34 @@ class Aurora(commands.Cog):
|
||||||
)
|
)
|
||||||
|
|
||||||
@aurora.command(aliases=["tdc", "td", "timedeltaconvert"])
|
@aurora.command(aliases=["tdc", "td", "timedeltaconvert"])
|
||||||
async def timedelta(self, ctx: commands.Context, *, duration: str):
|
async def timedelta(self, ctx: commands.Context, *, duration: str) -> None:
|
||||||
"""This command converts a duration to a [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) Python object.
|
"""Convert a string to a timedelta.
|
||||||
|
|
||||||
|
This command converts a duration to a [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) Python object.
|
||||||
|
You cannot convert years or months as they are not fixed units. Use `[p]aurora relativedelta` for that.
|
||||||
|
|
||||||
**Example usage**
|
**Example usage**
|
||||||
`[p]aurora timedelta 1 day 15hr 82 minutes 52s`
|
`[p]aurora timedelta 1 day 15hr 82 minutes 52s`
|
||||||
**Output**
|
**Output**
|
||||||
`1 day, 16:22:52`"""
|
`1 day, 16:22:52`"""
|
||||||
try:
|
parsed_time = parse_timedelta(duration)
|
||||||
parsed_time = parse(duration, as_timedelta=True, raise_exception=True)
|
if parsed_time is None:
|
||||||
await ctx.send(f"`{str(parsed_time)}`")
|
|
||||||
except ValueError:
|
|
||||||
await ctx.send(error("Please provide a convertible value!"))
|
await ctx.send(error("Please provide a convertible value!"))
|
||||||
|
return
|
||||||
|
await ctx.send(f"`{parsed_time}`")
|
||||||
|
|
||||||
|
@aurora.command(aliases=["rdc", "rd", "relativedeltaconvert"])
|
||||||
|
async def relativedelta(self, ctx: commands.Context, *, duration: str) -> None:
|
||||||
|
"""Convert a string to a relativedelta.
|
||||||
|
|
||||||
|
This command converts a duration to a [`relativedelta`](https://dateutil.readthedocs.io/en/stable/relativedelta.html) Python object.
|
||||||
|
|
||||||
|
**Example usage**
|
||||||
|
`[p]aurora relativedelta 3 years 1 day 15hr 82 minutes 52s`
|
||||||
|
**Output**
|
||||||
|
`relativedelta(years=+3, days=+1, hours=+15, minutes=+82, seconds=+52)`"""
|
||||||
|
parsed_time = parse_relativedelta(duration)
|
||||||
|
if parsed_time is None:
|
||||||
|
await ctx.send(error("Please provide a convertible value!"))
|
||||||
|
return
|
||||||
|
await ctx.send(f"`{parsed_time}`")
|
||||||
|
|
BIN
aurora/data/arrow.png
Normal file
After Width: | Height: | Size: 6.2 KiB |
|
@ -5,7 +5,6 @@
|
||||||
"short" : "A full replacement for Red's core Mod cogs.",
|
"short" : "A full replacement for Red's core Mod cogs.",
|
||||||
"description" : "Aurora is a fully-featured moderation system. It is heavily inspired by GalacticBot, and is designed to be a more user-friendly alternative to Red's core Mod cogs. This cog stores all of its data in an SQLite database.",
|
"description" : "Aurora is a fully-featured moderation system. It is heavily inspired by GalacticBot, and is designed to be a more user-friendly alternative to Red's core Mod cogs. This cog stores all of its data in an SQLite database.",
|
||||||
"end_user_data_statement" : "This cog stores the following information:\n- User IDs of accounts who moderate users or are moderated\n- Guild IDs of guilds with the cog enabled\n- Timestamps of moderations\n- Other information relating to moderations",
|
"end_user_data_statement" : "This cog stores the following information:\n- User IDs of accounts who moderate users or are moderated\n- Guild IDs of guilds with the cog enabled\n- Timestamps of moderations\n- Other information relating to moderations",
|
||||||
"requirements": ["humanize", "pytimeparse2"],
|
|
||||||
"hidden": false,
|
"hidden": false,
|
||||||
"disabled": false,
|
"disabled": false,
|
||||||
"min_bot_version": "3.5.0",
|
"min_bot_version": "3.5.0",
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from discord import ButtonStyle, Interaction, ui
|
from discord import ButtonStyle, Interaction, Message, ui
|
||||||
from redbot.core import commands
|
from redbot.core import commands
|
||||||
from redbot.core.utils.chat_formatting import error
|
from redbot.core.utils.chat_formatting import error
|
||||||
|
|
||||||
|
@ -7,9 +7,14 @@ from aurora.utilities.factory import addrole_embed
|
||||||
|
|
||||||
|
|
||||||
class Addrole(ui.View):
|
class Addrole(ui.View):
|
||||||
def __init__(self, ctx: commands.Context):
|
def __init__(self, ctx: commands.Context, message: Message, timeout: int = None):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.ctx = ctx
|
self.ctx = ctx
|
||||||
|
self.message = message
|
||||||
|
self.timeout = timeout
|
||||||
|
|
||||||
|
async def on_timeout(self):
|
||||||
|
await self.message.edit(view=None)
|
||||||
|
|
||||||
@ui.select(cls=ui.RoleSelect, placeholder="Select a role", min_values=0, max_values=25)
|
@ui.select(cls=ui.RoleSelect, placeholder="Select a role", min_values=0, max_values=25)
|
||||||
async def addrole_select(self, interaction: Interaction, select: ui.RoleSelect):
|
async def addrole_select(self, interaction: Interaction, select: ui.RoleSelect):
|
||||||
|
@ -17,12 +22,13 @@ class Addrole(ui.View):
|
||||||
await interaction.response.send_message(error("You must have the manage guild permission to add roles to the addrole whitelist."), ephemeral=True)
|
await interaction.response.send_message(error("You must have the manage guild permission to add roles to the addrole whitelist."), ephemeral=True)
|
||||||
return
|
return
|
||||||
await interaction.response.defer()
|
await interaction.response.defer()
|
||||||
addrole_whitelist: list = await config.guild(self.ctx.guild).addrole_whitelist()
|
async with config.guild(self.ctx.guild).addrole_whitelist() as addrole_whitelist:
|
||||||
if select.values[0].id in addrole_whitelist:
|
addrole_whitelist: list # type hint
|
||||||
addrole_whitelist.remove(select.values[0].id)
|
for value in select.values:
|
||||||
else:
|
if value.id in addrole_whitelist:
|
||||||
addrole_whitelist.append(select.values[0].id)
|
addrole_whitelist.remove(value.id)
|
||||||
await config.guild(self.ctx.guild).addrole_whitelist.set(addrole_whitelist)
|
else:
|
||||||
|
addrole_whitelist.append(value.id)
|
||||||
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)
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from discord import ButtonStyle, Interaction, ui
|
from discord import ButtonStyle, Interaction, Message, ui
|
||||||
from redbot.core import commands
|
from redbot.core import commands
|
||||||
|
|
||||||
from aurora.utilities.config import config
|
from aurora.utilities.config import config
|
||||||
|
@ -7,9 +7,14 @@ from aurora.utilities.utils import create_pagesize_options
|
||||||
|
|
||||||
|
|
||||||
class Guild(ui.View):
|
class Guild(ui.View):
|
||||||
def __init__(self, ctx: commands.Context):
|
def __init__(self, ctx: commands.Context, message: Message, timeout: int = None):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.ctx = ctx
|
self.ctx = ctx
|
||||||
|
self.message = message
|
||||||
|
self.timeout = timeout
|
||||||
|
|
||||||
|
async def on_timeout(self):
|
||||||
|
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
|
||||||
|
@ -17,7 +22,7 @@ class Guild(ui.View):
|
||||||
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
|
||||||
await interaction.response.defer()
|
await interaction.response.defer()
|
||||||
current_setting = await config.guild(interaction.guild).show_moderator
|
current_setting = await config.guild(interaction.guild).show_moderator()
|
||||||
await config.guild(interaction.guild).show_moderator.set(not current_setting)
|
await config.guild(interaction.guild).show_moderator.set(not current_setting)
|
||||||
await interaction.message.edit(embed=await guild_embed(self.ctx))
|
await interaction.message.edit(embed=await guild_embed(self.ctx))
|
||||||
|
|
||||||
|
@ -31,6 +36,16 @@ class Guild(ui.View):
|
||||||
await config.guild(interaction.guild).use_discord_permissions.set(not current_setting)
|
await config.guild(interaction.guild).use_discord_permissions.set(not current_setting)
|
||||||
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)
|
||||||
|
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:
|
||||||
|
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).respect_hierarchy()
|
||||||
|
await config.guild(interaction.guild).respect_hierarchy.set(not current_setting)
|
||||||
|
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:
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from discord import ButtonStyle, Interaction, ui
|
from discord import ButtonStyle, Interaction, Message, ui
|
||||||
from redbot.core import commands
|
from redbot.core import commands
|
||||||
from redbot.core.utils.chat_formatting import error
|
from redbot.core.utils.chat_formatting import error
|
||||||
|
|
||||||
|
@ -7,9 +7,14 @@ from aurora.utilities.factory import immune_embed
|
||||||
|
|
||||||
|
|
||||||
class Immune(ui.View):
|
class Immune(ui.View):
|
||||||
def __init__(self, ctx: commands.Context):
|
def __init__(self, ctx: commands.Context, message: Message, timeout: int = None):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.ctx = ctx
|
self.ctx = ctx
|
||||||
|
self.message = message
|
||||||
|
self.timeout = timeout
|
||||||
|
|
||||||
|
async def on_timeout(self):
|
||||||
|
await self.message.edit(view=None)
|
||||||
|
|
||||||
@ui.select(cls=ui.RoleSelect, placeholder="Select a role", min_values=0, max_values=25)
|
@ui.select(cls=ui.RoleSelect, placeholder="Select a role", min_values=0, max_values=25)
|
||||||
async def immune_select(self, interaction: Interaction, select: ui.RoleSelect):
|
async def immune_select(self, interaction: Interaction, select: ui.RoleSelect):
|
||||||
|
@ -17,13 +22,13 @@ class Immune(ui.View):
|
||||||
await interaction.response.send_message(error("You must have the manage guild permission to add immune roles."), ephemeral=True)
|
await interaction.response.send_message(error("You must have the manage guild permission to add immune roles."), ephemeral=True)
|
||||||
return
|
return
|
||||||
await interaction.response.defer()
|
await interaction.response.defer()
|
||||||
immune_roles: list = await config.guild(self.ctx.guild).immune_roles()
|
async with config.guild(self.ctx.guild).immune_roles() as immune_roles:
|
||||||
for role in select.values:
|
immune_roles: list # type hint
|
||||||
if role.id in immune_roles:
|
for value in select.values:
|
||||||
immune_roles.remove(role.id)
|
if value.id in immune_roles:
|
||||||
else:
|
immune_roles.remove(value.id)
|
||||||
immune_roles.append(role.id)
|
else:
|
||||||
await config.guild(self.ctx.guild).immune_roles.set(immune_roles)
|
immune_roles.append(value.id)
|
||||||
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)
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from discord import ButtonStyle, Interaction, ui
|
from discord import ButtonStyle, Interaction, Message, ui
|
||||||
from redbot.core import commands
|
from redbot.core import commands
|
||||||
|
|
||||||
from aurora.utilities.config import config
|
from aurora.utilities.config import config
|
||||||
|
@ -7,9 +7,14 @@ from aurora.utilities.utils import create_pagesize_options
|
||||||
|
|
||||||
|
|
||||||
class Overrides(ui.View):
|
class Overrides(ui.View):
|
||||||
def __init__(self, ctx: commands.Context):
|
def __init__(self, ctx: commands.Context, message: Message, timeout: int = None):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.ctx = ctx
|
self.ctx = ctx
|
||||||
|
self.message = message
|
||||||
|
self.timeout = timeout
|
||||||
|
|
||||||
|
async def on_timeout(self):
|
||||||
|
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
|
||||||
|
|
|
@ -7,6 +7,7 @@ def register_config(config_obj: Config):
|
||||||
config_obj.register_guild(
|
config_obj.register_guild(
|
||||||
show_moderator=True,
|
show_moderator=True,
|
||||||
use_discord_permissions=True,
|
use_discord_permissions=True,
|
||||||
|
respect_hierarchy=True,
|
||||||
ignore_modlog=True,
|
ignore_modlog=True,
|
||||||
ignore_other_bots=True,
|
ignore_other_bots=True,
|
||||||
dm_users=True,
|
dm_users=True,
|
||||||
|
|
|
@ -2,16 +2,12 @@
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from typing import Union
|
from typing import Union
|
||||||
|
|
||||||
import humanize
|
from discord import Color, Embed, Guild, Interaction, InteractionMessage, Member, Role, User
|
||||||
from discord import (Color, Embed, Guild, Interaction, InteractionMessage,
|
|
||||||
Member, Role, User)
|
|
||||||
from redbot.core import commands
|
from redbot.core import commands
|
||||||
from redbot.core.utils.chat_formatting import bold, box, error, warning
|
from redbot.core.utils.chat_formatting import bold, box, error, humanize_timedelta, warning
|
||||||
|
|
||||||
from aurora.utilities.config import config
|
from aurora.utilities.config import config
|
||||||
from aurora.utilities.utils import (fetch_channel_dict, fetch_user_dict,
|
from aurora.utilities.utils import fetch_channel_dict, fetch_user_dict, get_bool_emoji, get_next_case_number, get_pagesize_str
|
||||||
get_bool_emoji, get_next_case_number,
|
|
||||||
get_pagesize_str)
|
|
||||||
|
|
||||||
|
|
||||||
async def message_factory(
|
async def message_factory(
|
||||||
|
@ -50,8 +46,10 @@ async def message_factory(
|
||||||
else:
|
else:
|
||||||
guild_name = guild.name
|
guild_name = guild.name
|
||||||
|
|
||||||
|
title = moderation_type
|
||||||
|
|
||||||
if moderation_type in ["tempbanned", "muted"] and duration:
|
if moderation_type in ["tempbanned", "muted"] and duration:
|
||||||
embed_duration = f" for {humanize.precisedelta(duration)}"
|
embed_duration = f" for {humanize_timedelta(timedelta=duration)}"
|
||||||
else:
|
else:
|
||||||
embed_duration = ""
|
embed_duration = ""
|
||||||
|
|
||||||
|
@ -59,13 +57,17 @@ async def message_factory(
|
||||||
embed_desc = "received a"
|
embed_desc = "received a"
|
||||||
elif moderation_type == "addrole":
|
elif moderation_type == "addrole":
|
||||||
embed_desc = f"received the {role.name} role"
|
embed_desc = f"received the {role.name} role"
|
||||||
|
title = "Role Added"
|
||||||
|
moderation_type = ""
|
||||||
elif moderation_type == "removerole":
|
elif moderation_type == "removerole":
|
||||||
embed_desc = f"lost the {role.name} role"
|
embed_desc = f"lost the {role.name} role"
|
||||||
|
title = "Role Removed"
|
||||||
|
moderation_type = ""
|
||||||
else:
|
else:
|
||||||
embed_desc = "been"
|
embed_desc = "been"
|
||||||
|
|
||||||
embed = Embed(
|
embed = Embed(
|
||||||
title=str.title(moderation_type),
|
title=str.title(title),
|
||||||
description=f"You have {embed_desc} {moderation_type}{embed_duration} in {guild_name}.",
|
description=f"You have {embed_desc} {moderation_type}{embed_duration} in {guild_name}.",
|
||||||
color=color,
|
color=color,
|
||||||
timestamp=datetime.now(),
|
timestamp=datetime.now(),
|
||||||
|
@ -85,7 +87,7 @@ async def message_factory(
|
||||||
|
|
||||||
embed.set_footer(
|
embed.set_footer(
|
||||||
text=f"Case #{await get_next_case_number(guild.id):,}",
|
text=f"Case #{await get_next_case_number(guild.id):,}",
|
||||||
icon_url="https://cdn.discordapp.com/attachments/1070822161389994054/1159469476773904414/arrow-right-circle-icon-512x512-2p1e2aaw.png?ex=65312319&is=651eae19&hm=3cebdd28e805c13a79ec48ef87c32ca532ffa6b9ede2e48d0cf8e5e81f3a6818&",
|
icon_url="attachment://arrow.png",
|
||||||
)
|
)
|
||||||
|
|
||||||
return embed
|
return embed
|
||||||
|
@ -141,9 +143,9 @@ async def log_factory(
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
duration_embed = (
|
duration_embed = (
|
||||||
f"{humanize.precisedelta(td)} | <t:{case_dict['end_timestamp']}:R>"
|
f"{humanize_timedelta(timedelta=td)} | <t:{case_dict['end_timestamp']}:R>"
|
||||||
if case_dict["expired"] == "0"
|
if case_dict["expired"] == "0"
|
||||||
else str(humanize.precisedelta(td))
|
else str(humanize_timedelta(timedelta=td))
|
||||||
)
|
)
|
||||||
embed.description = (
|
embed.description = (
|
||||||
embed.description
|
embed.description
|
||||||
|
@ -204,7 +206,7 @@ async def log_factory(
|
||||||
)
|
)
|
||||||
embed.description = (
|
embed.description = (
|
||||||
embed.description
|
embed.description
|
||||||
+ f"\n**Duration:** {humanize.precisedelta(td)} | <t:{case_dict['end_timestamp']}:R>"
|
+ 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)
|
||||||
|
@ -255,9 +257,9 @@ async def case_factory(interaction: Interaction, case_dict: dict) -> Embed:
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
duration_embed = (
|
duration_embed = (
|
||||||
f"{humanize.precisedelta(td)} | <t:{case_dict['end_timestamp']}:R>"
|
f"{humanize_timedelta(timedelta=td)} | <t:{case_dict['end_timestamp']}:R>"
|
||||||
if bool(case_dict["expired"]) is False
|
if bool(case_dict["expired"]) is False
|
||||||
else str(humanize.precisedelta(td))
|
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'])}"
|
||||||
|
|
||||||
|
@ -267,6 +269,9 @@ async def case_factory(interaction: Interaction, case_dict: dict) -> Embed:
|
||||||
else "\n**Changes:** 0"
|
else "\n**Changes:** 0"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if 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 += (
|
embed.description += (
|
||||||
|
@ -379,7 +384,7 @@ async def evidenceformat_factory(interaction: Interaction, case_dict: dict) -> s
|
||||||
if case_dict["duration"] != "NULL":
|
if case_dict["duration"] != "NULL":
|
||||||
hours, minutes, seconds = map(int, case_dict["duration"].split(":"))
|
hours, minutes, seconds = map(int, case_dict["duration"].split(":"))
|
||||||
td = timedelta(hours=hours, minutes=minutes, seconds=seconds)
|
td = timedelta(hours=hours, minutes=minutes, seconds=seconds)
|
||||||
content += f"\nDuration: {humanize.precisedelta(td)}"
|
content += f"\nDuration: {humanize_timedelta(timedelta=td)}"
|
||||||
|
|
||||||
content += f"\nReason: {case_dict['reason']}"
|
content += f"\nReason: {case_dict['reason']}"
|
||||||
|
|
||||||
|
@ -455,6 +460,7 @@ async def guild_embed(ctx: commands.Context) -> Embed:
|
||||||
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(),
|
||||||
}
|
}
|
||||||
|
|
||||||
channel = ctx.guild.get_channel(guild_settings["log_channel"])
|
channel = ctx.guild.get_channel(guild_settings["log_channel"])
|
||||||
|
@ -471,6 +477,9 @@ async def guild_embed(ctx: commands.Context) -> Embed:
|
||||||
+ bold("Use Discord Permissions: ")
|
+ bold("Use Discord Permissions: ")
|
||||||
+ get_bool_emoji(guild_settings["use_discord_permissions"]),
|
+ get_bool_emoji(guild_settings["use_discord_permissions"]),
|
||||||
"- "
|
"- "
|
||||||
|
+ bold("Respect Hierarchy: ")
|
||||||
|
+ get_bool_emoji(guild_settings["respect_hierarchy"]),
|
||||||
|
"- "
|
||||||
+ bold("Ignore Modlog: ")
|
+ bold("Ignore Modlog: ")
|
||||||
+ get_bool_emoji(guild_settings["ignore_modlog"]),
|
+ get_bool_emoji(guild_settings["ignore_modlog"]),
|
||||||
"- "
|
"- "
|
||||||
|
@ -510,15 +519,29 @@ async def guild_embed(ctx: commands.Context) -> Embed:
|
||||||
async def addrole_embed(ctx: commands.Context) -> Embed:
|
async def addrole_embed(ctx: commands.Context) -> Embed:
|
||||||
"""Generates a configuration menu field value for a guild's addrole whitelist."""
|
"""Generates a configuration menu field value for a guild's addrole whitelist."""
|
||||||
|
|
||||||
whitelist = await config.guild(ctx.guild).addrole_whitelist()
|
roles = []
|
||||||
if whitelist:
|
async with config.guild(ctx.guild).addrole_whitelist() as whitelist:
|
||||||
whitelist = [
|
for role in whitelist:
|
||||||
ctx.guild.get_role(role).mention or error(f"`{role}` (Not Found)")
|
evalulated_role = ctx.guild.get_role(role) or error(f"`{role}` (Not Found)")
|
||||||
for role in whitelist
|
if isinstance(evalulated_role, Role):
|
||||||
]
|
roles.append({
|
||||||
whitelist = "\n".join(whitelist)
|
"id": evalulated_role.id,
|
||||||
|
"mention": evalulated_role.mention,
|
||||||
|
"position": evalulated_role.position
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
roles.append({
|
||||||
|
"id": role,
|
||||||
|
"mention": error(f"`{role}` (Not Found)"),
|
||||||
|
"position": 0
|
||||||
|
})
|
||||||
|
|
||||||
|
if roles:
|
||||||
|
roles = sorted(roles, key=lambda x: x["position"], reverse=True)
|
||||||
|
roles = [role["mention"] for role in roles]
|
||||||
|
whitelist_str = "\n".join(roles)
|
||||||
else:
|
else:
|
||||||
whitelist = warning("No roles are on the addrole whitelist!")
|
whitelist_str = warning("No roles are on the addrole whitelist!")
|
||||||
|
|
||||||
e = await _config(ctx)
|
e = await _config(ctx)
|
||||||
e.title += ": Addrole Whitelist"
|
e.title += ": Addrole Whitelist"
|
||||||
|
@ -526,8 +549,8 @@ async def addrole_embed(ctx: commands.Context) -> Embed:
|
||||||
"Use the select menu below to manage this guild's addrole whitelist."
|
"Use the select menu below to manage this guild's addrole whitelist."
|
||||||
)
|
)
|
||||||
|
|
||||||
if len(whitelist) > 4000 and len(whitelist) < 5000:
|
if len(whitelist_str) > 4000 and len(whitelist_str) < 5000:
|
||||||
lines = whitelist.split("\n")
|
lines = whitelist_str.split("\n")
|
||||||
chunks = []
|
chunks = []
|
||||||
chunk = ""
|
chunk = ""
|
||||||
for line in lines:
|
for line in lines:
|
||||||
|
@ -541,21 +564,35 @@ async def addrole_embed(ctx: commands.Context) -> Embed:
|
||||||
for chunk in chunks:
|
for chunk in chunks:
|
||||||
e.add_field(name="", value=chunk)
|
e.add_field(name="", value=chunk)
|
||||||
else:
|
else:
|
||||||
e.description += "\n\n" + whitelist
|
e.description += "\n\n" + whitelist_str
|
||||||
|
|
||||||
return e
|
return e
|
||||||
|
|
||||||
|
|
||||||
async def immune_embed(ctx: commands.Context) -> Embed:
|
async def immune_embed(ctx: commands.Context) -> Embed:
|
||||||
"""Generates a configuration menu field value for a guild's immune roles."""
|
"""Generates a configuration menu embed for a guild's immune roles."""
|
||||||
|
|
||||||
immune_roles = await config.guild(ctx.guild).immune_roles()
|
roles = []
|
||||||
if immune_roles:
|
async with config.guild(ctx.guild).immune_roles() as immune_roles:
|
||||||
immune_str = [
|
for role in immune_roles:
|
||||||
ctx.guild.get_role(role).mention or error(f"`{role}` (Not Found)")
|
evalulated_role = ctx.guild.get_role(role) or error(f"`{role}` (Not Found)")
|
||||||
for role in immune_roles
|
if isinstance(evalulated_role, Role):
|
||||||
]
|
roles.append({
|
||||||
immune_str = "\n".join(immune_str)
|
"id": evalulated_role.id,
|
||||||
|
"mention": evalulated_role.mention,
|
||||||
|
"position": evalulated_role.position
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
roles.append({
|
||||||
|
"id": role,
|
||||||
|
"mention": error(f"`{role}` (Not Found)"),
|
||||||
|
"position": 0
|
||||||
|
})
|
||||||
|
|
||||||
|
if roles:
|
||||||
|
roles = sorted(roles, key=lambda x: x["position"], reverse=True)
|
||||||
|
roles = [role["mention"] for role in roles]
|
||||||
|
immune_str = "\n".join(roles)
|
||||||
else:
|
else:
|
||||||
immune_str = warning("No roles are set as immune roles!")
|
immune_str = warning("No roles are set as immune roles!")
|
||||||
|
|
||||||
|
|
|
@ -1,3 +1,3 @@
|
||||||
import logging
|
from red_commons.logging import getLogger
|
||||||
|
|
||||||
logger = logging.getLogger("red.sea.aurora")
|
logger = getLogger("red.SeaCogs.Aurora")
|
||||||
|
|
|
@ -1,11 +1,13 @@
|
||||||
# pylint: disable=cyclic-import
|
# pylint: disable=cyclic-import
|
||||||
import json
|
import json
|
||||||
|
from datetime import datetime
|
||||||
from datetime import timedelta as td
|
from datetime import timedelta as td
|
||||||
from typing import Union
|
from typing import Optional, Union
|
||||||
|
|
||||||
from discord import Guild, Interaction, Member, SelectOption, User
|
from dateutil.relativedelta import relativedelta as rd
|
||||||
|
from discord import File, Guild, Interaction, Member, SelectOption, User
|
||||||
from discord.errors import Forbidden, NotFound
|
from discord.errors import Forbidden, NotFound
|
||||||
from redbot.core import commands
|
from redbot.core import commands, data_manager
|
||||||
from redbot.core.utils.chat_formatting import error
|
from redbot.core.utils.chat_formatting import error
|
||||||
|
|
||||||
from .config import config
|
from .config import config
|
||||||
|
@ -75,7 +77,7 @@ async def check_moddable(
|
||||||
return False
|
return False
|
||||||
|
|
||||||
if isinstance(target, Member):
|
if isinstance(target, Member):
|
||||||
if interaction.user.top_role <= target.top_role:
|
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(
|
content=error(
|
||||||
"You cannot moderate members with a higher role than you!"
|
"You cannot moderate members with a higher role than you!"
|
||||||
|
@ -248,7 +250,7 @@ def convert_timedelta_to_str(timedelta: td) -> str:
|
||||||
return f"{hours}:{minutes}:{seconds}"
|
return f"{hours}:{minutes}:{seconds}"
|
||||||
|
|
||||||
|
|
||||||
def get_bool_emoji(value: bool) -> str:
|
def get_bool_emoji(value: Optional[bool]) -> str:
|
||||||
"""Returns a unicode emoji based on a boolean value."""
|
"""Returns a unicode emoji based on a boolean value."""
|
||||||
if value is True:
|
if value is True:
|
||||||
return "\N{WHITE HEAVY CHECK MARK}"
|
return "\N{WHITE HEAVY CHECK MARK}"
|
||||||
|
@ -283,3 +285,14 @@ def create_pagesize_options() -> list[SelectOption]:
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
return options
|
return options
|
||||||
|
|
||||||
|
def timedelta_from_relativedelta(relativedelta: rd) -> td:
|
||||||
|
"""Converts a relativedelta object to a timedelta object."""
|
||||||
|
now = datetime.now()
|
||||||
|
then = now - relativedelta
|
||||||
|
return now - then
|
||||||
|
|
||||||
|
def get_footer_image(coginstance: commands.Cog) -> File:
|
||||||
|
"""Returns the footer image for the embeds."""
|
||||||
|
image_path = data_manager.bundled_data_path(coginstance) / "arrow.png"
|
||||||
|
return File(image_path, filename="arrow.png", description="arrow")
|
||||||
|
|
|
@ -7,28 +7,39 @@
|
||||||
|
|
||||||
import contextlib
|
import contextlib
|
||||||
import json
|
import json
|
||||||
import logging
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
|
from red_commons.logging import getLogger
|
||||||
from redbot.cogs.downloader import errors
|
from redbot.cogs.downloader import errors
|
||||||
from redbot.cogs.downloader.converters import InstalledCog
|
from redbot.cogs.downloader.converters import InstalledCog
|
||||||
from redbot.core import commands
|
from redbot.core import commands
|
||||||
from redbot.core.bot import Red
|
from redbot.core.bot import Red
|
||||||
from redbot.core.utils.chat_formatting import error, text_to_file
|
from redbot.core.utils.chat_formatting import error, humanize_list, text_to_file
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# 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__ = "SeaswimmerTheFsh"
|
__author__ = ["SeaswimmerTheFsh"]
|
||||||
__version__ = "1.0.0"
|
__version__ = "1.1.0"
|
||||||
|
__documentation__ = "https://seacogs.coastalcommits.com/backup/"
|
||||||
|
|
||||||
def __init__(self, bot: Red):
|
def __init__(self, bot: Red):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
self.logger = logging.getLogger("red.sea.backup")
|
self.logger = getLogger("red.SeaCogs.Backup")
|
||||||
|
|
||||||
|
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"Cog Version: **{self.__version__}**",
|
||||||
|
f"Author: {humanize_list(self.__author__)}",
|
||||||
|
f"Documentation: {self.__documentation__}",
|
||||||
|
]
|
||||||
|
return "\n".join(text)
|
||||||
|
|
||||||
@commands.group(autohelp=True)
|
@commands.group(autohelp=True)
|
||||||
@commands.is_owner()
|
@commands.is_owner()
|
||||||
|
@ -87,8 +98,11 @@ class Backup(commands.Cog):
|
||||||
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):
|
||||||
await ctx.send(error("Please provide a valid JSON export file."))
|
try:
|
||||||
return
|
export = json.loads(await ctx.message.reference.resolved.attachments[0].read())
|
||||||
|
except (json.JSONDecodeError, IndexError):
|
||||||
|
await ctx.send(error("Please provide a valid JSON export file."))
|
||||||
|
return
|
||||||
|
|
||||||
downloader = ctx.bot.get_cog("Downloader")
|
downloader = ctx.bot.get_cog("Downloader")
|
||||||
if downloader is None:
|
if downloader is None:
|
||||||
|
@ -146,17 +160,15 @@ class Backup(commands.Cog):
|
||||||
)
|
)
|
||||||
self.logger.debug("Repository %s already exists", name)
|
self.logger.debug("Repository %s already exists", name)
|
||||||
|
|
||||||
# This is commented out because errors.AuthenticationError is not yet implemented in Red 3.5.5's Downloader cog.
|
except errors.AuthenticationError as err:
|
||||||
# Rather, it is only in the development version and will be added in version 3.5.6 (or whatever the next version is).
|
repo_e.append(f"Authentication error while adding repository {name}. See logs for more information.")
|
||||||
# except errors.AuthenticationError as err:
|
self.logger.exception(
|
||||||
# repo_e.append(f"Authentication error while adding repository {name}. See logs for more information.")
|
"Something went wrong whilst cloning %s (to revision %s)",
|
||||||
# self.logger.exception(
|
url,
|
||||||
# "Something went wrong whilst cloning %s (to revision %s)",
|
branch,
|
||||||
# url,
|
exc_info=err,
|
||||||
# branch,
|
)
|
||||||
# exc_info=err,
|
continue
|
||||||
# )
|
|
||||||
# continue
|
|
||||||
|
|
||||||
except errors.CloningError as err:
|
except errors.CloningError as err:
|
||||||
repo_e.append(
|
repo_e.append(
|
||||||
|
|
|
@ -7,9 +7,9 @@
|
||||||
"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.5",
|
"min_bot_version": "3.5.6",
|
||||||
"max_bot_version": "3.5.5",
|
"max_bot_version": "3.5.9",
|
||||||
"min_python_version": [3, 10, 0],
|
"min_python_version": [3, 9, 0],
|
||||||
"tags": [
|
"tags": [
|
||||||
"utility",
|
"utility",
|
||||||
"backup",
|
"backup",
|
||||||
|
|
|
@ -5,14 +5,17 @@
|
||||||
# ____) | __/ (_| \__ \\ V V /| | | | | | | | | | | | __/ |
|
# ____) | __/ (_| \__ \\ V V /| | | | | | | | | | | | __/ |
|
||||||
# |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_|
|
# |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_|
|
||||||
|
|
||||||
import logging
|
|
||||||
import random
|
import random
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
import aiohttp
|
import aiohttp
|
||||||
from discord import Embed
|
import numpy as np
|
||||||
from redbot.core import Config, commands
|
from discord import Colour, Embed, File
|
||||||
|
from PIL import Image
|
||||||
|
from red_commons.logging import getLogger
|
||||||
|
from redbot.core import Config, commands, data_manager
|
||||||
from redbot.core.bot import Red
|
from redbot.core.bot import Red
|
||||||
from redbot.core.utils.chat_formatting import error
|
from redbot.core.utils.chat_formatting import error, humanize_list
|
||||||
|
|
||||||
import bible.errors
|
import bible.errors
|
||||||
from bible.models import Version
|
from bible.models import Version
|
||||||
|
@ -21,8 +24,9 @@ from bible.models import Version
|
||||||
class Bible(commands.Cog):
|
class Bible(commands.Cog):
|
||||||
"""Retrieve Bible verses from the API.bible API."""
|
"""Retrieve Bible verses from the API.bible API."""
|
||||||
|
|
||||||
__author__ = "SeaswimmerTheFsh"
|
__author__ = ["SeaswimmerTheFsh"]
|
||||||
__version__ = "1.0.0"
|
__version__ = "1.1.0"
|
||||||
|
__documentation__ = "https://seacogs.coastalcommits.com/bible/"
|
||||||
|
|
||||||
def __init__(self, bot: Red):
|
def __init__(self, bot: Red):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
@ -31,10 +35,37 @@ class Bible(commands.Cog):
|
||||||
self.config = Config.get_conf(
|
self.config = Config.get_conf(
|
||||||
self, identifier=481923957134912, force_registration=True
|
self, identifier=481923957134912, force_registration=True
|
||||||
)
|
)
|
||||||
self.logger = logging.getLogger("red.sea.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)
|
||||||
|
|
||||||
|
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"Cog Version: **{self.__version__}**",
|
||||||
|
f"Author: {humanize_list(self.__author__)}",
|
||||||
|
f"Documentation: {self.__documentation__}",
|
||||||
|
]
|
||||||
|
return "\n".join(text)
|
||||||
|
|
||||||
|
def get_icon(self, color: Colour) -> File:
|
||||||
|
"""Get the docs.api.bible favicon with a given color."""
|
||||||
|
image_path = data_manager.bundled_data_path(self) / "api.bible-logo.png"
|
||||||
|
image = Image.open(image_path)
|
||||||
|
image = image.convert("RGBA")
|
||||||
|
data = np.array(image)
|
||||||
|
red, green, blue, alpha = data.T # pylint: disable=unused-variable
|
||||||
|
white_areas = (red == 255) & (blue == 255) & (green == 255)
|
||||||
|
data[..., :-1][white_areas.T] = color.to_rgb()
|
||||||
|
image = Image.fromarray(data)
|
||||||
|
|
||||||
|
with BytesIO() as image_binary:
|
||||||
|
image.save(image_binary, "PNG")
|
||||||
|
image_binary.seek(0)
|
||||||
|
return File(image_binary, filename="icon.png", description="API.Bible Icon")
|
||||||
|
|
||||||
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 = [
|
book_name_list = [
|
||||||
|
@ -236,15 +267,17 @@ class Bible(commands.Cog):
|
||||||
return
|
return
|
||||||
|
|
||||||
if await ctx.embed_requested():
|
if await ctx.embed_requested():
|
||||||
|
icon = self.get_icon(await ctx.embed_color())
|
||||||
embed = Embed(
|
embed = Embed(
|
||||||
title=f"{passage['reference']}",
|
title=f"{passage['reference']}",
|
||||||
description=passage["content"].replace("¶ ", ""),
|
description=passage["content"].replace("¶ ", ""),
|
||||||
color=await self.bot.get_embed_color(ctx.channel),
|
color=await ctx.embed_color(),
|
||||||
)
|
)
|
||||||
embed.set_footer(
|
embed.set_footer(
|
||||||
text=f"{ctx.prefix}bible passage - Powered by API.Bible - {version.abbreviationLocal} ({version.languageLocal}, {version.descriptionLocal})"
|
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)
|
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']}")
|
||||||
|
|
||||||
|
@ -276,14 +309,16 @@ class Bible(commands.Cog):
|
||||||
return
|
return
|
||||||
|
|
||||||
if await ctx.embed_requested():
|
if await ctx.embed_requested():
|
||||||
|
icon = self.get_icon(await ctx.embed_color())
|
||||||
embed = Embed(
|
embed = Embed(
|
||||||
title=f"{passage['reference']}",
|
title=f"{passage['reference']}",
|
||||||
description=passage["content"].replace("¶ ", ""),
|
description=passage["content"].replace("¶ ", ""),
|
||||||
color=await self.bot.get_embed_color(ctx.channel),
|
color=await ctx.embed_color(),
|
||||||
)
|
)
|
||||||
embed.set_footer(
|
embed.set_footer(
|
||||||
text=f"{ctx.prefix}bible random - Powered by API.Bible - {version.abbreviationLocal} ({version.languageLocal}, {version.descriptionLocal})"
|
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)
|
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']}")
|
||||||
|
|
BIN
bible/data/api.bible-logo.png
Normal file
After Width: | Height: | Size: 20 KiB |
|
@ -9,6 +9,7 @@
|
||||||
"disabled": false,
|
"disabled": false,
|
||||||
"min_bot_version": "3.5.0",
|
"min_bot_version": "3.5.0",
|
||||||
"min_python_version": [3, 10, 0],
|
"min_python_version": [3, 10, 0],
|
||||||
|
"requirements": ["numpy", "pillow"],
|
||||||
"tags": [
|
"tags": [
|
||||||
"fun",
|
"fun",
|
||||||
"utility",
|
"utility",
|
||||||
|
|
|
@ -19,11 +19,17 @@ nav:
|
||||||
- Bible: bible.md
|
- Bible: bible.md
|
||||||
- Backup: backup.md
|
- Backup: backup.md
|
||||||
- Nerdify: nerdify.md
|
- Nerdify: nerdify.md
|
||||||
|
- Pterodactyl:
|
||||||
|
- pterodactyl/index.md
|
||||||
|
- Installing Red: pterodactyl/installing-red.md
|
||||||
|
- Getting Started: pterodactyl/getting-started.md
|
||||||
|
- Configuration: pterodactyl/configuration.md
|
||||||
|
- Regex Examples: pterodactyl/regex.md
|
||||||
|
|
||||||
plugins:
|
plugins:
|
||||||
- git-authors
|
- git-authors
|
||||||
- search
|
- search
|
||||||
- social
|
#- social
|
||||||
- git-revision-date-localized:
|
- git-revision-date-localized:
|
||||||
enable_creation_date: true
|
enable_creation_date: true
|
||||||
type: timeago
|
type: timeago
|
||||||
|
@ -105,3 +111,4 @@ watch:
|
||||||
- ./backup
|
- ./backup
|
||||||
- ./bible
|
- ./bible
|
||||||
- ./nerdify
|
- ./nerdify
|
||||||
|
- ./pterodactyl
|
||||||
|
|
|
@ -17,12 +17,24 @@ from redbot.core.utils import chat_formatting, common_filters
|
||||||
class Nerdify(commands.Cog):
|
class Nerdify(commands.Cog):
|
||||||
"""Nerdify your text."""
|
"""Nerdify your text."""
|
||||||
|
|
||||||
__author__ = "SeaswimmerTheFsh"
|
__author__ = ["SeaswimmerTheFsh"]
|
||||||
__version__ = "1.3.2"
|
__version__ = "1.3.4"
|
||||||
|
__documentation__ = "https://seacogs.coastalcommits.com/nerdify/"
|
||||||
|
|
||||||
def __init__(self, bot):
|
def __init__(self, bot):
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
|
|
||||||
|
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"Cog Version: **{self.__version__}**",
|
||||||
|
f"Author: {chat_formatting.humanize_list(self.__author__)}",
|
||||||
|
f"Documentation: {self.__documentation__}"
|
||||||
|
]
|
||||||
|
return "\n".join(text)
|
||||||
|
|
||||||
@commands.command(aliases=["nerd"])
|
@commands.command(aliases=["nerd"])
|
||||||
async def nerdify(
|
async def nerdify(
|
||||||
self, ctx: commands.Context, *, text: Optional[str] = None
|
self, ctx: commands.Context, *, text: Optional[str] = None
|
||||||
|
|
2236
poetry.lock
generated
5
pterodactyl/__init__.py
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
from .pterodactyl import Pterodactyl
|
||||||
|
|
||||||
|
|
||||||
|
async def setup(bot):
|
||||||
|
await bot.add_cog(Pterodactyl(bot))
|
30
pterodactyl/config.py
Normal file
|
@ -0,0 +1,30 @@
|
||||||
|
from redbot.core import Config
|
||||||
|
|
||||||
|
config: Config = Config.get_conf(None, identifier=457581387213637448123567, cog_name="Pterodactyl", force_registration=True)
|
||||||
|
|
||||||
|
def register_config(config_obj: Config) -> None:
|
||||||
|
config_obj.register_global(
|
||||||
|
base_url=None,
|
||||||
|
server_id=None,
|
||||||
|
console_channel=None,
|
||||||
|
console_commands_enabled=False,
|
||||||
|
current_status='',
|
||||||
|
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)\] (.*)",
|
||||||
|
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$",
|
||||||
|
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
|
||||||
|
topic='Server IP: .$H\nServer Players: .$P/.$M',
|
||||||
|
topic_hostname=None,
|
||||||
|
topic_port=25565,
|
||||||
|
api_endpoint="minecraft",
|
||||||
|
chat_channel=None,
|
||||||
|
startup_msg='Server started!',
|
||||||
|
shutdown_msg='Server stopped!',
|
||||||
|
join_msg='Welcome to the server! 👋',
|
||||||
|
leave_msg='Goodbye! 👋',
|
||||||
|
mask_ip=True,
|
||||||
|
invite=None,
|
||||||
|
regex_blacklist={},
|
||||||
|
)
|
19
pterodactyl/info.json
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
{
|
||||||
|
"author" : ["SeaswimmerTheFsh (seasw.)"],
|
||||||
|
"install_msg" : "Thank you for installing Pterodactyl!\nYou can find the source code of this cog [here](https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs).\nDocumentation can be found [here](https://seacogs.coastalcommits.com/pterodactyl ).",
|
||||||
|
"name" : "Pterodactyl",
|
||||||
|
"short" : "Interface with Pterodactyl through websockets.",
|
||||||
|
"description" : "Interface with Pterodactyl through websockets.",
|
||||||
|
"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": ["git+https://github.com/SeaswimmerTheFsh/pydactyl", "websockets"],
|
||||||
|
"tags": [
|
||||||
|
"pterodactyl",
|
||||||
|
"minecraft",
|
||||||
|
"server",
|
||||||
|
"management"
|
||||||
|
]
|
||||||
|
}
|
9
pterodactyl/logger.py
Normal file
|
@ -0,0 +1,9 @@
|
||||||
|
from red_commons import logging
|
||||||
|
from red_commons.logging import getLogger
|
||||||
|
|
||||||
|
logger = getLogger('red.SeaCogs.Pterodactyl')
|
||||||
|
websocket_logger = getLogger('red.SeaCogs.Pterodactyl.websocket')
|
||||||
|
if logger.level >= logging.VERBOSE:
|
||||||
|
websocket_logger.setLevel(logging.logging.INFO)
|
||||||
|
elif logger.level < logging.VERBOSE:
|
||||||
|
websocket_logger.setLevel(logging.logging.DEBUG)
|
10
pterodactyl/mcsrvstatus.py
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
import aiohttp
|
||||||
|
|
||||||
|
|
||||||
|
async def get_status(host: str, port: int = 25565) -> tuple[bool, dict]:
|
||||||
|
async with aiohttp.ClientSession() as session:
|
||||||
|
async with session.get(f'https://api.mcsrvstat.us/2/{host}:{port}') as response:
|
||||||
|
response = await response.json()
|
||||||
|
if response['online']:
|
||||||
|
return (True, response)
|
||||||
|
return (False, response)
|
627
pterodactyl/pterodactyl.py
Normal file
|
@ -0,0 +1,627 @@
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
from typing import Mapping, Optional, Tuple, Union
|
||||||
|
|
||||||
|
import discord
|
||||||
|
import websockets
|
||||||
|
from discord.ext import tasks
|
||||||
|
from pydactyl import PterodactylClient
|
||||||
|
from redbot.core import app_commands, commands
|
||||||
|
from redbot.core.app_commands import Choice
|
||||||
|
from redbot.core.bot import Red
|
||||||
|
from redbot.core.utils.chat_formatting import box, error, humanize_list
|
||||||
|
from redbot.core.utils.views import ConfirmView
|
||||||
|
|
||||||
|
from pterodactyl import mcsrvstatus
|
||||||
|
from pterodactyl.config import config, register_config
|
||||||
|
from pterodactyl.logger import logger
|
||||||
|
|
||||||
|
|
||||||
|
class Pterodactyl(commands.Cog):
|
||||||
|
"""Pterodactyl allows you to manage your Pterodactyl Panel from Discord."""
|
||||||
|
|
||||||
|
__author__ = ["SeaswimmerTheFsh"]
|
||||||
|
__version__ = "2.0.0"
|
||||||
|
__documentation__ = "https://seacogs.coastalcommits.com/pterodactyl/"
|
||||||
|
|
||||||
|
def __init__(self, bot: Red):
|
||||||
|
self.bot = bot
|
||||||
|
self.client: Optional[PterodactylClient] = None
|
||||||
|
self.task: Optional[asyncio.Task] = None
|
||||||
|
self.websocket: Optional[websockets.WebSocketClientProtocol] = None
|
||||||
|
self.retry_counter: int = 0
|
||||||
|
register_config(config)
|
||||||
|
self.task = self.get_task()
|
||||||
|
self.update_topic.start()
|
||||||
|
|
||||||
|
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"Cog Version: **{self.__version__}**",
|
||||||
|
f"Author: {humanize_list(self.__author__)}",
|
||||||
|
f"Documentation: {self.__documentation__}",
|
||||||
|
]
|
||||||
|
return "\n".join(text)
|
||||||
|
|
||||||
|
async def cog_unload(self) -> None:
|
||||||
|
self.update_topic.cancel()
|
||||||
|
self.task.cancel()
|
||||||
|
self.retry_counter = 0
|
||||||
|
await self.client._session.close() # pylint: disable=protected-access
|
||||||
|
|
||||||
|
def get_task(self) -> asyncio.Task:
|
||||||
|
from pterodactyl.websocket import establish_websocket_connection
|
||||||
|
task = self.bot.loop.create_task(establish_websocket_connection(self), name="Pterodactyl Websocket Connection")
|
||||||
|
task.add_done_callback(self.error_callback)
|
||||||
|
return task
|
||||||
|
|
||||||
|
def error_callback(self, fut) -> None: #NOTE - Thanks flame442 and zephyrkul for helping me figure this out
|
||||||
|
try:
|
||||||
|
fut.result()
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
logger.info("WebSocket task has been cancelled.")
|
||||||
|
except Exception as e: # pylint: disable=broad-exception-caught
|
||||||
|
logger.error("WebSocket task has failed: %s", e, exc_info=e)
|
||||||
|
self.task.cancel()
|
||||||
|
if self.retry_counter < 5:
|
||||||
|
self.retry_counter += 1
|
||||||
|
logger.info("Retrying in %s seconds...", 5 * self.retry_counter)
|
||||||
|
self.task = self.bot.loop.call_later(5 * self.retry_counter, self.get_task)
|
||||||
|
else:
|
||||||
|
logger.info("Retry limit reached. Stopping task.")
|
||||||
|
|
||||||
|
@tasks.loop(minutes=6)
|
||||||
|
async def update_topic(self):
|
||||||
|
await self.bot.wait_until_red_ready()
|
||||||
|
topic = await self.get_topic()
|
||||||
|
console = self.bot.get_channel(await config.console_channel())
|
||||||
|
chat = self.bot.get_channel(await config.chat_channel())
|
||||||
|
if console:
|
||||||
|
await console.edit(topic=topic)
|
||||||
|
if chat:
|
||||||
|
await chat.edit(topic=topic)
|
||||||
|
|
||||||
|
@commands.Cog.listener()
|
||||||
|
async def on_message_without_command(self, message: discord.Message) -> None:
|
||||||
|
if message.channel.id == await config.console_channel() and message.author.bot is False:
|
||||||
|
if await config.console_commands_enabled() is False:
|
||||||
|
await message.channel.send("Console commands are disabled.")
|
||||||
|
logger.debug("Received console command from %s, but console commands are disabled: %s", message.author.id, message.content)
|
||||||
|
return
|
||||||
|
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())
|
||||||
|
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:
|
||||||
|
logger.debug("Received chat message from %s: %s", message.author.id, message.content)
|
||||||
|
channel = self.bot.get_channel(await config.console_channel())
|
||||||
|
if channel:
|
||||||
|
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)]})
|
||||||
|
logger.debug("Sending chat message to server:\n%s", msg)
|
||||||
|
try:
|
||||||
|
await self.websocket.send(msg)
|
||||||
|
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()
|
||||||
|
|
||||||
|
async def get_topic(self) -> str:
|
||||||
|
topic: str = await config.topic()
|
||||||
|
placeholders = {
|
||||||
|
"H": await config.topic_hostname() or "unset",
|
||||||
|
"O": str(await config.topic_port()),
|
||||||
|
}
|
||||||
|
if await config.api_endpoint() == "minecraft":
|
||||||
|
status, response = await mcsrvstatus.get_status(await config.topic_hostname(), await config.topic_port())
|
||||||
|
if status:
|
||||||
|
placeholders.update({
|
||||||
|
"I": response['ip'],
|
||||||
|
"M": str(response['players']['max']),
|
||||||
|
"P": str(response['players']['online']),
|
||||||
|
"V": response['version'],
|
||||||
|
"D": response['motd']['clean'][0] if response['motd']['clean'] else "unset",
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
placeholders.update({
|
||||||
|
"I": response['ip'],
|
||||||
|
"M": "0",
|
||||||
|
"P": "0",
|
||||||
|
"V": "Server Offline",
|
||||||
|
"D": "Server Offline",
|
||||||
|
})
|
||||||
|
for key, value in placeholders.items():
|
||||||
|
topic = topic.replace('.$' + key, value)
|
||||||
|
return topic
|
||||||
|
|
||||||
|
async def get_chat_command(self, message: discord.Message) -> str:
|
||||||
|
command: str = await config.chat_command()
|
||||||
|
placeholders = {
|
||||||
|
"C": str(message.author.color),
|
||||||
|
"D": message.author.discriminator,
|
||||||
|
"I": str(message.author.id),
|
||||||
|
"M": message.content.replace('"','').replace("\n", " "),
|
||||||
|
"N": message.author.display_name,
|
||||||
|
"U": message.author.name,
|
||||||
|
"V": await config.invite() or "use [p]pterodactyl config invite to change me",
|
||||||
|
}
|
||||||
|
for key, value in placeholders.items():
|
||||||
|
command = command.replace('.$' + key, value)
|
||||||
|
return command
|
||||||
|
|
||||||
|
async def get_player_list(self) -> Optional[Tuple[str, list]]:
|
||||||
|
if await config.api_endpoint() == "minecraft":
|
||||||
|
status, response = await mcsrvstatus.get_status(await config.topic_hostname(), await config.topic_port())
|
||||||
|
if status and 'list' in response['players']:
|
||||||
|
output_str = '\n'.join(response['players']['list'])
|
||||||
|
return output_str, response['players']['list']
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def get_player_list_embed(self, ctx: Union[commands.Context, discord.Interaction]) -> Optional[discord.Embed]:
|
||||||
|
player_list = await self.get_player_list()
|
||||||
|
if player_list:
|
||||||
|
embed = discord.Embed(color=await self.bot.get_embed_color(ctx.channel), title="Players Online")
|
||||||
|
embed.description = player_list[0]
|
||||||
|
return embed
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def power(self, ctx: Union[discord.Interaction, commands.Context], action: str, action_ing: str, warning: str = '') -> None:
|
||||||
|
if isinstance(ctx, discord.Interaction):
|
||||||
|
author = ctx.user
|
||||||
|
else:
|
||||||
|
author = ctx.author
|
||||||
|
|
||||||
|
current_status = await config.current_status()
|
||||||
|
|
||||||
|
if current_status == action_ing:
|
||||||
|
if isinstance(ctx, discord.Interaction):
|
||||||
|
return await ctx.response.send_message(f"Server is already {action_ing}.", ephemeral=True)
|
||||||
|
return await ctx.send(f"Server is already {action_ing}.")
|
||||||
|
|
||||||
|
if current_status in ["starting", "stopping"] and action != "kill":
|
||||||
|
if isinstance(ctx, discord.Interaction):
|
||||||
|
return await ctx.response.send_message("Another power action is already in progress.", ephemeral=True)
|
||||||
|
return await ctx.send("Another power action is already in progress.")
|
||||||
|
|
||||||
|
view = ConfirmView(author, disable_buttons=True)
|
||||||
|
|
||||||
|
if isinstance(ctx, discord.Interaction):
|
||||||
|
await ctx.response.send_message(f"{warning}Are you sure you want to {action} the server?", view=view)
|
||||||
|
else:
|
||||||
|
message = await ctx.send(f"{warning}Are you sure you want to {action} the server?", view=view)
|
||||||
|
|
||||||
|
await view.wait()
|
||||||
|
|
||||||
|
if view.result is True:
|
||||||
|
if isinstance(ctx, discord.Interaction):
|
||||||
|
await ctx.edit_original_response(content=f"Sending websocket command to {action} server...", view=None)
|
||||||
|
else:
|
||||||
|
await message.edit(content=f"Sending websocket command to {action} server...", view=None)
|
||||||
|
|
||||||
|
await self.websocket.send(json.dumps({"event": "set state", "args": [action]}))
|
||||||
|
|
||||||
|
if isinstance(ctx, discord.Interaction):
|
||||||
|
await ctx.edit_original_response(content=f"Server {action_ing}", view=None)
|
||||||
|
else:
|
||||||
|
await message.edit(content=f"Server {action_ing}", view=None)
|
||||||
|
|
||||||
|
else:
|
||||||
|
if isinstance(ctx, discord.Interaction):
|
||||||
|
await ctx.edit_original_response(content="Cancelled.", view=None)
|
||||||
|
else:
|
||||||
|
await message.edit(content="Cancelled.", view=None)
|
||||||
|
|
||||||
|
async def send_command(self, ctx: Union[discord.Interaction, commands.Context], command: str):
|
||||||
|
channel = self.bot.get_channel(await config.console_channel())
|
||||||
|
if isinstance(ctx, discord.Interaction):
|
||||||
|
if channel:
|
||||||
|
await channel.send(f"Received console command from {ctx.user.id}: {command[:1900]}", allowed_mentions=discord.AllowedMentions.none())
|
||||||
|
try:
|
||||||
|
await self.websocket.send(json.dumps({"event": "send command", "args": [command]}))
|
||||||
|
await ctx.response.send_message(f"Command sent to server. {box(command, 'json')}", ephemeral=True)
|
||||||
|
except websockets.exceptions.ConnectionClosed as e:
|
||||||
|
logger.error("WebSocket connection closed: %s", e)
|
||||||
|
await ctx.response.send_message(error("WebSocket connection closed."))
|
||||||
|
self.task.cancel()
|
||||||
|
self.retry_counter = 0
|
||||||
|
self.task = self.get_task()
|
||||||
|
else:
|
||||||
|
if channel:
|
||||||
|
await channel.send(f"Received console command from {ctx.author.id}: {command[:1900]}", allowed_mentions=discord.AllowedMentions.none())
|
||||||
|
try:
|
||||||
|
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()
|
||||||
|
async def on_red_api_tokens_update(self, service_name: str, api_tokens: Mapping[str,str]): # pylint: disable=unused-argument
|
||||||
|
if service_name == "pterodactyl":
|
||||||
|
logger.info("Configuration value set: api_key\nRestarting task...")
|
||||||
|
self.task.cancel()
|
||||||
|
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.command(name = "command", description = "Send a command to the server console.")
|
||||||
|
async def slash_pterodactyl_command(self, interaction: discord.Interaction, command: str) -> None:
|
||||||
|
"""Send a command to the server console.
|
||||||
|
|
||||||
|
Parameters:
|
||||||
|
-----------
|
||||||
|
command: str
|
||||||
|
The command to send to the server."""
|
||||||
|
return await self.send_command(interaction, command)
|
||||||
|
|
||||||
|
@slash_pterodactyl.command(name = "players", description = "Retrieve a list of players on the server.")
|
||||||
|
async def slash_pterodactyl_players(self, interaction: discord.Interaction) -> None:
|
||||||
|
"""Retrieve a list of players on the server."""
|
||||||
|
e = await self.get_player_list_embed(interaction)
|
||||||
|
if e:
|
||||||
|
await interaction.response.send_message(embed=e, ephemeral=True)
|
||||||
|
else:
|
||||||
|
await interaction.response.send_message("No players online.", ephemeral=True)
|
||||||
|
|
||||||
|
@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")
|
||||||
|
])
|
||||||
|
async def slash_pterodactyl_power(self, interaction: discord.Interaction, action: app_commands.Choice[str]) -> None:
|
||||||
|
"""Send power actions to the server.
|
||||||
|
|
||||||
|
Parameters:
|
||||||
|
-----------
|
||||||
|
action: app_commands.Choice[str]
|
||||||
|
The action to perform on the server."""
|
||||||
|
if action.value == "kill":
|
||||||
|
return await self.power(interaction, action.value, "stopping... (forcefully killed)", warning="**⚠️ Forcefully killing the server process can corrupt data in some cases. ⚠️**\n")
|
||||||
|
if action.value == "stop":
|
||||||
|
return await self.power(interaction, action.value, "stopping...")
|
||||||
|
return await self.power(interaction, action.value, f"{action.value}ing...")
|
||||||
|
|
||||||
|
@commands.group(autohelp = True, name = "pterodactyl", aliases = ["ptero"])
|
||||||
|
async def pterodactyl(self, ctx: commands.Context) -> None:
|
||||||
|
"""Pterodactyl allows you to manage your Pterodactyl Panel from Discord."""
|
||||||
|
|
||||||
|
@pterodactyl.command(name = "players", aliases=["list", "online", "playerlist", "who"])
|
||||||
|
async def pterodactyl_players(self, ctx: commands.Context) -> None:
|
||||||
|
"""Retrieve a list of players on the server."""
|
||||||
|
e = await self.get_player_list_embed(ctx)
|
||||||
|
if e:
|
||||||
|
await ctx.send(embed=e)
|
||||||
|
else:
|
||||||
|
await ctx.send("No players online.")
|
||||||
|
|
||||||
|
@pterodactyl.command(name = "command", aliases = ["cmd", "execute", "exec"])
|
||||||
|
@commands.admin()
|
||||||
|
async def pterodactyl_command(self, ctx: commands.Context, *, command: str) -> None:
|
||||||
|
"""Send a command to the server console."""
|
||||||
|
return await self.send_command(ctx, command)
|
||||||
|
|
||||||
|
@pterodactyl.group(autohelp = True, name = "power")
|
||||||
|
@commands.admin()
|
||||||
|
async def pterodactyl_power(self, ctx: commands.Context) -> None:
|
||||||
|
"""Send power actions to the server."""
|
||||||
|
|
||||||
|
@pterodactyl_power.command(name = "start")
|
||||||
|
async def pterodactyl_power_start(self, ctx: commands.Context) -> Optional[discord.Message]:
|
||||||
|
"""Start the server."""
|
||||||
|
return await self.power(ctx, "start", "starting...")
|
||||||
|
|
||||||
|
@pterodactyl_power.command(name = "stop")
|
||||||
|
async def pterodactyl_power_stop(self, ctx: commands.Context) -> Optional[discord.Message]:
|
||||||
|
"""Stop the server."""
|
||||||
|
return await self.power(ctx, "stop", "stopping...")
|
||||||
|
|
||||||
|
@pterodactyl_power.command(name = "restart")
|
||||||
|
async def pterodactyl_power_restart(self, ctx: commands.Context) -> Optional[discord.Message]:
|
||||||
|
"""Restart the server."""
|
||||||
|
return await self.power(ctx, "restart", "restarting...")
|
||||||
|
|
||||||
|
@pterodactyl_power.command(name = "kill")
|
||||||
|
async def pterodactyl_power_kill(self, ctx: commands.Context) -> Optional[discord.Message]:
|
||||||
|
"""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")
|
||||||
|
|
||||||
|
@pterodactyl.group(autohelp = True, name = "config", aliases = ["settings", "set"])
|
||||||
|
@commands.is_owner()
|
||||||
|
async def pterodactyl_config(self, ctx: commands.Context) -> None:
|
||||||
|
"""Configure Pterodactyl settings."""
|
||||||
|
|
||||||
|
@pterodactyl_config.command(name = "url")
|
||||||
|
async def pterodactyl_config_base_url(self, ctx: commands.Context, *, base_url: str) -> None:
|
||||||
|
"""Set the base URL of your Pterodactyl Panel.
|
||||||
|
|
||||||
|
Please include the protocol (http/https).
|
||||||
|
Example: `https://panel.example.com`"""
|
||||||
|
await config.base_url.set(base_url)
|
||||||
|
await ctx.send(f"Base URL set to {base_url}")
|
||||||
|
logger.info("Configuration value set: base_url = %s\nRestarting task...", base_url)
|
||||||
|
self.task.cancel()
|
||||||
|
self.retry_counter = 0
|
||||||
|
self.task = self.get_task()
|
||||||
|
|
||||||
|
@pterodactyl_config.command(name = "serverid")
|
||||||
|
async def pterodactyl_config_server_id(self, ctx: commands.Context, *, server_id: str) -> None:
|
||||||
|
"""Set the ID of your server."""
|
||||||
|
await config.server_id.set(server_id)
|
||||||
|
await ctx.send(f"Server ID set to {server_id}")
|
||||||
|
logger.info("Configuration value set: server_id = %s\nRestarting task...", server_id)
|
||||||
|
self.task.cancel()
|
||||||
|
self.retry_counter = 0
|
||||||
|
self.task = self.get_task()
|
||||||
|
|
||||||
|
@pterodactyl_config.group(name = "console")
|
||||||
|
async def pterodactyl_config_console(self, ctx: commands.Context):
|
||||||
|
"""Configure console settings."""
|
||||||
|
|
||||||
|
@pterodactyl_config_console.command(name = "channel")
|
||||||
|
async def pterodactyl_config_console_channel(self, ctx: commands.Context, channel: discord.TextChannel) -> None:
|
||||||
|
"""Set the channel to send console output to."""
|
||||||
|
await config.console_channel.set(channel.id)
|
||||||
|
await ctx.send(f"Console channel set to {channel.mention}")
|
||||||
|
|
||||||
|
@pterodactyl_config_console.command(name = "commands")
|
||||||
|
async def pterodactyl_config_console_commands(self, ctx: commands.Context, enabled: bool) -> None:
|
||||||
|
"""Enable or disable console commands."""
|
||||||
|
await config.console_commands_enabled.set(enabled)
|
||||||
|
await ctx.send(f"Console commands set to {enabled}")
|
||||||
|
|
||||||
|
@pterodactyl_config.command(name = "invite")
|
||||||
|
async def pterodactyl_config_invite(self, ctx: commands.Context, invite: str) -> None:
|
||||||
|
"""Set the invite link for your server."""
|
||||||
|
await config.invite.set(invite)
|
||||||
|
await ctx.send(f"Invite link set to {invite}")
|
||||||
|
|
||||||
|
@pterodactyl_config.group(name = "topic")
|
||||||
|
async def pterodactyl_config_topic(self, ctx: commands.Context):
|
||||||
|
"""Set the topic for the console and chat channels."""
|
||||||
|
|
||||||
|
@pterodactyl_config_topic.command(name = "host", aliases = ["hostname", "ip"])
|
||||||
|
async def pterodactyl_config_topic_host(self, ctx: commands.Context, host: str) -> None:
|
||||||
|
"""Set the hostname or IP address of your server."""
|
||||||
|
await config.topic_hostname.set(host)
|
||||||
|
await ctx.send(f"Hostname/IP set to `{host}`")
|
||||||
|
|
||||||
|
@pterodactyl_config_topic.command(name = "port")
|
||||||
|
async def pterodactyl_config_topic_port(self, ctx: commands.Context, port: int) -> None:
|
||||||
|
"""Set the port of your server."""
|
||||||
|
await config.topic_port.set(port)
|
||||||
|
await ctx.send(f"Port set to `{port}`")
|
||||||
|
|
||||||
|
@pterodactyl_config_topic.command(name = "text")
|
||||||
|
async def pterodactyl_config_topic_text(self, ctx: commands.Context, *, text: str) -> None:
|
||||||
|
"""Set the text for the console and chat channels.
|
||||||
|
|
||||||
|
Available placeholders:
|
||||||
|
- `.$H` (hostname)
|
||||||
|
- `.$O` (port)
|
||||||
|
Available for Minecraft servers:
|
||||||
|
- `.$I` (ip)
|
||||||
|
- `.$M` (max players)
|
||||||
|
- `.$P` (players online)
|
||||||
|
- `.$V` (version)
|
||||||
|
- `.$D` (description / Message of the Day)"""
|
||||||
|
await config.topic.set(text)
|
||||||
|
await ctx.send(f"Topic set to:\n{box(text, 'yaml')}")
|
||||||
|
|
||||||
|
@pterodactyl_config.group(name = "chat")
|
||||||
|
async def pterodactyl_config_chat(self, ctx: commands.Context):
|
||||||
|
"""Configure chat settings."""
|
||||||
|
|
||||||
|
@pterodactyl_config_chat.command(name = "channel")
|
||||||
|
async def pterodactyl_config_chat_channel(self, ctx: commands.Context, channel: discord.TextChannel) -> None:
|
||||||
|
"""Set the channel to send chat output to."""
|
||||||
|
await config.chat_channel.set(channel.id)
|
||||||
|
await ctx.send(f"Chat channel set to {channel.mention}")
|
||||||
|
|
||||||
|
@pterodactyl_config_chat.command(name = "command")
|
||||||
|
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.
|
||||||
|
|
||||||
|
Required placeholders: `.$U` (username), `.$M` (message), `.$C` (color)
|
||||||
|
See [documentation](https://seacogs.coastalcommits.com/pterodactyl/setup/#changing-the-tellraw-command) for more information."""
|
||||||
|
await config.chat_command.set(command)
|
||||||
|
await ctx.send(f"Chat command set to:\n{box(command, 'json')}")
|
||||||
|
|
||||||
|
@pterodactyl_config.group(name = "regex")
|
||||||
|
async def pterodactyl_config_regex(self, ctx: commands.Context) -> None:
|
||||||
|
"""Set regex patterns."""
|
||||||
|
|
||||||
|
@pterodactyl_config_regex.command(name = "chat")
|
||||||
|
async def pterodactyl_config_regex_chat(self, ctx: commands.Context, *, regex: str) -> None:
|
||||||
|
"""Set the regex pattern to match chat messages on the server.
|
||||||
|
|
||||||
|
See [documentation](https://seacogs.coastalcommits.com/pterodactyl/setup/#my-chat-messages-arent-detected) for more information."""
|
||||||
|
await config.chat_regex.set(regex)
|
||||||
|
await ctx.send(f"Chat regex set to:\n{box(regex, 'regex')}")
|
||||||
|
|
||||||
|
@pterodactyl_config_regex.command(name = "server")
|
||||||
|
async def pterodactyl_config_regex_server(self, ctx: commands.Context, *, regex: str) -> None:
|
||||||
|
"""Set the regex pattern to match server messages on the server.
|
||||||
|
|
||||||
|
See [documentation](https://seacogs.coastalcommits.com/pterodactyl/setup/#my-chat-messages-arent-detected) for more information."""
|
||||||
|
await config.server_regex.set(regex)
|
||||||
|
await ctx.send(f"Server regex set to:\n{box(regex, 'regex')}")
|
||||||
|
|
||||||
|
@pterodactyl_config_regex.command(name = "join")
|
||||||
|
async def pterodactyl_config_regex_join(self, ctx: commands.Context, *, regex: str) -> None:
|
||||||
|
"""Set the regex pattern to match join messages on the server.
|
||||||
|
|
||||||
|
See [documentation](https://seacogs.coastalcommits.com/pterodactyl/setup/#my-chat-messages-arent-detected) for more information."""
|
||||||
|
await config.join_regex.set(regex)
|
||||||
|
await ctx.send(f"Join regex set to:\n{box(regex, 'regex')}")
|
||||||
|
|
||||||
|
@pterodactyl_config_regex.command(name = "leave")
|
||||||
|
async def pterodactyl_config_regex_leave(self, ctx: commands.Context, *, regex: str) -> None:
|
||||||
|
"""Set the regex pattern to match leave messages on the server.
|
||||||
|
|
||||||
|
See [documentation](https://seacogs.coastalcommits.com/pterodactyl/setup/#my-chat-messages-arent-detected) for more information."""
|
||||||
|
await config.leave_regex.set(regex)
|
||||||
|
await ctx.send(f"Leave regex set to:\n{box(regex, 'regex')}")
|
||||||
|
|
||||||
|
@pterodactyl_config_regex.command(name = "achievement")
|
||||||
|
async def pterodactyl_config_regex_achievement(self, ctx: commands.Context, *, regex: str) -> None:
|
||||||
|
"""Set the regex pattern to match achievement messages on the server.
|
||||||
|
|
||||||
|
See [documentation](https://seacogs.coastalcommits.com/pterodactyl/setup/#my-chat-messages-arent-detected) for more information."""
|
||||||
|
await config.achievement_regex.set(regex)
|
||||||
|
await ctx.send(f"Achievement regex set to:\n{box(regex, 'regex')}")
|
||||||
|
|
||||||
|
@pterodactyl_config.group(name = "messages", aliases = ['msg', 'msgs', 'message'])
|
||||||
|
async def pterodactyl_config_messages(self, ctx: commands.Context):
|
||||||
|
"""Configure message settings."""
|
||||||
|
|
||||||
|
@pterodactyl_config_messages.command(name = "startup")
|
||||||
|
async def pterodactyl_config_messages_startup(self, ctx: commands.Context, *, message: str) -> None:
|
||||||
|
"""Set the message that will be sent when the server starts."""
|
||||||
|
await config.startup_msg.set(message)
|
||||||
|
await ctx.send(f"Startup message set to: {message}")
|
||||||
|
|
||||||
|
@pterodactyl_config_messages.command(name = "shutdown")
|
||||||
|
async def pterodactyl_config_messages_shutdown(self, ctx: commands.Context, *, message: str) -> None:
|
||||||
|
"""Set the message that will be sent when the server stops."""
|
||||||
|
await config.shutdown_msg.set(message)
|
||||||
|
await ctx.send(f"Shutdown message set to: {message}")
|
||||||
|
|
||||||
|
@pterodactyl_config_messages.command(name = "join")
|
||||||
|
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."""
|
||||||
|
await config.join_msg.set(message)
|
||||||
|
await ctx.send(f"Join message set to: {message}")
|
||||||
|
|
||||||
|
@pterodactyl_config_messages.command(name = "leave")
|
||||||
|
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."""
|
||||||
|
await config.leave_msg.set(message)
|
||||||
|
await ctx.send(f"Leave message set to: {message}")
|
||||||
|
|
||||||
|
@pterodactyl_config.command(name = "ip")
|
||||||
|
async def pterodactyl_config_mask_ip(self, ctx: commands.Context, mask: bool) -> None:
|
||||||
|
"""Mask the IP addresses of users in console messages."""
|
||||||
|
await config.mask_ip.set(mask)
|
||||||
|
await ctx.send(f"IP masking set to {mask}")
|
||||||
|
|
||||||
|
@pterodactyl_config.command(name = "api")
|
||||||
|
async def pterodactyl_config_api(self, ctx: commands.Context, endpoint: str) -> None:
|
||||||
|
"""Set the API endpoint for retrieving user avatars.
|
||||||
|
|
||||||
|
This is only used for retrieving user avatars for webhook messages.
|
||||||
|
See [PlayerDB](https://playerdb.co/) for valid endpoints. Usually, you should leave this as default."""
|
||||||
|
await config.api_endpoint.set(endpoint)
|
||||||
|
await ctx.send(f"API endpoint set to {endpoint}")
|
||||||
|
|
||||||
|
@pterodactyl_config_regex.group(name = "blacklist", aliases = ['block', 'blocklist'],)
|
||||||
|
async def pterodactyl_config_regex_blacklist(self, ctx: commands.Context):
|
||||||
|
"""Blacklist regex patterns."""
|
||||||
|
|
||||||
|
@pterodactyl_config_regex_blacklist.command(name = "add")
|
||||||
|
async def pterodactyl_config_regex_blacklist_add(self, ctx: commands.Context, name: str, *, regex: str) -> None:
|
||||||
|
"""Add a regex pattern to the blacklist."""
|
||||||
|
async with config.regex_blacklist() as blacklist:
|
||||||
|
blacklist: dict
|
||||||
|
if name not in blacklist:
|
||||||
|
blacklist.update({name: regex})
|
||||||
|
await ctx.send(f"Added `{name}` to the regex blacklist.\n{box(regex, 're')}")
|
||||||
|
else:
|
||||||
|
view = ConfirmView(ctx.author, disable_buttons=True)
|
||||||
|
msg = await ctx.send(f"Name `{name}` already exists in the blacklist. Would you like to update it? Current value:\n{box(blacklist[name], 're')}", view=view)
|
||||||
|
await view.wait()
|
||||||
|
if view.result is True:
|
||||||
|
blacklist.update({name: regex})
|
||||||
|
await msg.edit(content=f"Updated `{name}` in the regex blacklist.\n{box(regex, 're')}")
|
||||||
|
else:
|
||||||
|
await msg.edit(content="Cancelled.")
|
||||||
|
|
||||||
|
@pterodactyl_config_regex_blacklist.command(name = "remove")
|
||||||
|
async def pterodactyl_config_regex_blacklist_remove(self, ctx: commands.Context, name: str) -> None:
|
||||||
|
"""Remove a regex pattern from the blacklist."""
|
||||||
|
async with config.regex_blacklist() as blacklist:
|
||||||
|
blacklist: dict
|
||||||
|
if name in blacklist:
|
||||||
|
view = ConfirmView(ctx.author, disable_buttons=True)
|
||||||
|
msg = await ctx.send(f"Are you sure you want to remove `{name}` from the regex blacklist?\n{box(blacklist[name], 're')}", view=view)
|
||||||
|
await view.wait()
|
||||||
|
if view.result is True:
|
||||||
|
del blacklist[name]
|
||||||
|
await msg.edit(content=f"Removed `{name}` from the regex blacklist.")
|
||||||
|
else:
|
||||||
|
await msg.edit(content="Cancelled.")
|
||||||
|
else:
|
||||||
|
await ctx.send(f"Name `{name}` does not exist in the blacklist.")
|
||||||
|
|
||||||
|
@pterodactyl_config.command(name = 'view', aliases = ['show'])
|
||||||
|
async def pterodactyl_config_view(self, ctx: commands.Context) -> None:
|
||||||
|
"""View the current configuration."""
|
||||||
|
base_url = await config.base_url()
|
||||||
|
server_id = await config.server_id()
|
||||||
|
console_channel = await config.console_channel()
|
||||||
|
console_commands_enabled = await config.console_commands_enabled()
|
||||||
|
chat_channel = await config.chat_channel()
|
||||||
|
chat_command = await config.chat_command()
|
||||||
|
chat_regex = await config.chat_regex()
|
||||||
|
server_regex = await config.server_regex()
|
||||||
|
join_regex = await config.join_regex()
|
||||||
|
leave_regex = await config.leave_regex()
|
||||||
|
achievement_regex = await config.achievement_regex()
|
||||||
|
startup_msg = await config.startup_msg()
|
||||||
|
shutdown_msg = await config.shutdown_msg()
|
||||||
|
join_msg = await config.join_msg()
|
||||||
|
leave_msg = await config.leave_msg()
|
||||||
|
mask_ip = await config.mask_ip()
|
||||||
|
api_endpoint = await config.api_endpoint()
|
||||||
|
invite = await config.invite()
|
||||||
|
regex_blacklist: dict = await config.regex_blacklist()
|
||||||
|
topic_text = await config.topic()
|
||||||
|
topic_hostname = await config.topic_hostname()
|
||||||
|
topic_port = await config.topic_port()
|
||||||
|
embed = discord.Embed(color = await ctx.embed_color(), title="Pterodactyl Configuration")
|
||||||
|
embed.description = f"""**Base URL:** {base_url}
|
||||||
|
**Server ID:** `{server_id}`
|
||||||
|
**Console Channel:** <#{console_channel}>
|
||||||
|
**Console Commands:** {self.get_bool_str(console_commands_enabled)}
|
||||||
|
**Chat Channel:** <#{chat_channel}>
|
||||||
|
**Startup Message:** {startup_msg}
|
||||||
|
**Shutdown Message:** {shutdown_msg}
|
||||||
|
**Join Message:** {join_msg}
|
||||||
|
**Leave Message:** {leave_msg}
|
||||||
|
**Mask IP:** {self.get_bool_str(mask_ip)}
|
||||||
|
**API Endpoint:** `{api_endpoint}`
|
||||||
|
**Invite:** {invite}
|
||||||
|
|
||||||
|
**Topic Hostname:** `{topic_hostname}`
|
||||||
|
**Topic Port:** `{topic_port}`
|
||||||
|
**Topic Text:** {box(topic_text, 'yaml')}
|
||||||
|
|
||||||
|
**Chat Command:** {box(chat_command, 'json')}
|
||||||
|
**Chat Regex:** {box(chat_regex, 're')}
|
||||||
|
**Server Regex:** {box(server_regex, 're')}
|
||||||
|
**Join Regex:** {box(join_regex, 're')}
|
||||||
|
**Leave Regex:** {box(leave_regex, 're')}
|
||||||
|
**Achievement Regex:** {box(achievement_regex, 're')}"""
|
||||||
|
await ctx.send(embed=embed)
|
||||||
|
if not len(regex_blacklist) == 0:
|
||||||
|
regex_blacklist_embed = discord.Embed(color = await ctx.embed_color(), title="Regex Blacklist")
|
||||||
|
for name, regex in regex_blacklist.items():
|
||||||
|
regex_blacklist_embed.add_field(name=name, value=box(regex, 're'), inline=False)
|
||||||
|
await ctx.send(embed=regex_blacklist_embed)
|
||||||
|
|
||||||
|
def get_bool_str(self, inp: bool) -> str:
|
||||||
|
"""Return a string representation of a boolean."""
|
||||||
|
return "Enabled" if inp else "Disabled"
|
251
pterodactyl/websocket.py
Normal file
|
@ -0,0 +1,251 @@
|
||||||
|
# pylint: disable=cyclic-import
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from typing import Optional, Union
|
||||||
|
|
||||||
|
import aiohttp
|
||||||
|
import discord
|
||||||
|
import websockets
|
||||||
|
from pydactyl import PterodactylClient
|
||||||
|
from redbot.core.utils.chat_formatting import bold, pagify
|
||||||
|
|
||||||
|
from pterodactyl.config import config
|
||||||
|
from pterodactyl.logger import logger, websocket_logger
|
||||||
|
from pterodactyl.pterodactyl import Pterodactyl
|
||||||
|
|
||||||
|
|
||||||
|
async def establish_websocket_connection(coginstance: Pterodactyl) -> None:
|
||||||
|
await coginstance.bot.wait_until_red_ready()
|
||||||
|
base_url = await config.base_url()
|
||||||
|
base_url = base_url[:-1] if base_url.endswith('/') else base_url
|
||||||
|
|
||||||
|
logger.info("Establishing WebSocket connection")
|
||||||
|
|
||||||
|
websocket_credentials = await retrieve_websocket_credentials(coginstance)
|
||||||
|
|
||||||
|
async with websockets.connect(websocket_credentials['data']['socket'], origin=base_url, ping_timeout=60, logger=websocket_logger) as websocket:
|
||||||
|
logger.info("WebSocket connection established")
|
||||||
|
|
||||||
|
auth_message = json.dumps({"event": "auth", "args": [websocket_credentials['data']['token']]})
|
||||||
|
await websocket.send(auth_message)
|
||||||
|
logger.info("Authentication message sent")
|
||||||
|
|
||||||
|
coginstance.websocket = websocket
|
||||||
|
|
||||||
|
while True: # pylint: disable=too-many-nested-blocks
|
||||||
|
message = json.loads(await websocket.recv())
|
||||||
|
if message['event'] in ('token expiring', 'token expired'):
|
||||||
|
logger.info("Received token expiring/expired event. Refreshing token.")
|
||||||
|
websocket_credentials = await retrieve_websocket_credentials(coginstance)
|
||||||
|
auth_message = json.dumps({"event": "auth", "args": [websocket_credentials['data']['token']]})
|
||||||
|
await websocket.send(auth_message)
|
||||||
|
logger.info("Authentication message sent")
|
||||||
|
|
||||||
|
if message['event'] == 'auth success':
|
||||||
|
logger.info("WebSocket authentication successful")
|
||||||
|
|
||||||
|
if message['event'] == 'console output' and await config.console_channel() is not None:
|
||||||
|
regex_blacklist: dict = await config.regex_blacklist()
|
||||||
|
matches = [re.search(regex, message['args'][0]) for regex in regex_blacklist.values()]
|
||||||
|
|
||||||
|
if await config.current_status() in ('running', '') and not any(matches):
|
||||||
|
content = remove_ansi_escape_codes(message['args'][0])
|
||||||
|
if await config.mask_ip() is True:
|
||||||
|
content = mask_ip(content)
|
||||||
|
|
||||||
|
console_channel = coginstance.bot.get_channel(await config.console_channel())
|
||||||
|
chat_channel = coginstance.bot.get_channel(await config.chat_channel())
|
||||||
|
if console_channel is not None:
|
||||||
|
if content.startswith('['):
|
||||||
|
pagified_content = pagify(content, delims=[" ", "\n"])
|
||||||
|
for page in pagified_content:
|
||||||
|
await console_channel.send(content=page, allowed_mentions=discord.AllowedMentions.none())
|
||||||
|
|
||||||
|
server_message = await check_if_server_message(content)
|
||||||
|
if server_message:
|
||||||
|
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())
|
||||||
|
|
||||||
|
chat_message = await check_if_chat_message(content)
|
||||||
|
if chat_message:
|
||||||
|
info = await get_info(chat_message['username'])
|
||||||
|
if info is not None:
|
||||||
|
await send_chat_discord(coginstance, chat_message['username'], chat_message['message'], info['data']['player']['avatar'])
|
||||||
|
else:
|
||||||
|
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)
|
||||||
|
if join_message:
|
||||||
|
if chat_channel is not None:
|
||||||
|
if coginstance.bot.embed_requested(chat_channel):
|
||||||
|
await chat_channel.send(embed=await generate_join_leave_embed(join_message, True))
|
||||||
|
else:
|
||||||
|
await chat_channel.send(f"{join_message} joined the game", allowed_mentions=discord.AllowedMentions.none())
|
||||||
|
|
||||||
|
leave_message = await check_if_leave_message(content)
|
||||||
|
if leave_message:
|
||||||
|
if chat_channel is not None:
|
||||||
|
if coginstance.bot.embed_requested(chat_channel):
|
||||||
|
await chat_channel.send(embed=await generate_join_leave_embed(leave_message, False))
|
||||||
|
else:
|
||||||
|
await chat_channel.send(f"{leave_message} left the game", allowed_mentions=discord.AllowedMentions.none())
|
||||||
|
|
||||||
|
achievement_message = await check_if_achievement_message(content)
|
||||||
|
if achievement_message:
|
||||||
|
if chat_channel is not None:
|
||||||
|
if coginstance.bot.embed_requested(chat_channel):
|
||||||
|
await chat_channel.send(embed=await generate_achievement_embed(achievement_message['username'], achievement_message['achievement'], achievement_message['challenge']))
|
||||||
|
else:
|
||||||
|
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':
|
||||||
|
old_status = await config.current_status()
|
||||||
|
current_status = message['args'][0]
|
||||||
|
if old_status != current_status:
|
||||||
|
await config.current_status.set(current_status)
|
||||||
|
if await config.console_channel() is not None:
|
||||||
|
console = coginstance.bot.get_channel(await config.console_channel())
|
||||||
|
if console is not None:
|
||||||
|
await console.send(f"Server status changed! `{current_status}`")
|
||||||
|
if await config.chat_channel() is not None:
|
||||||
|
if current_status == 'running' and await config.startup_msg() is not None:
|
||||||
|
chat = coginstance.bot.get_channel(await config.chat_channel())
|
||||||
|
if chat is not None:
|
||||||
|
await chat.send(await config.startup_msg())
|
||||||
|
if current_status == 'stopping' and await config.shutdown_msg() is not None:
|
||||||
|
chat = coginstance.bot.get_channel(await config.chat_channel())
|
||||||
|
if chat is not None:
|
||||||
|
await chat.send(await config.shutdown_msg())
|
||||||
|
|
||||||
|
async def retrieve_websocket_credentials(coginstance: Pterodactyl) -> Optional[dict]:
|
||||||
|
pterodactyl_keys = await coginstance.bot.get_shared_api_tokens("pterodactyl")
|
||||||
|
api_key = pterodactyl_keys.get("api_key")
|
||||||
|
if api_key is None:
|
||||||
|
coginstance.task.cancel()
|
||||||
|
raise ValueError("Pterodactyl API key not set. Please set it using `[p]set api`.")
|
||||||
|
base_url = await config.base_url()
|
||||||
|
if base_url is None:
|
||||||
|
coginstance.task.cancel()
|
||||||
|
raise ValueError("Pterodactyl base URL not set. Please set it using `[p]pterodactyl config url`.")
|
||||||
|
server_id = await config.server_id()
|
||||||
|
if server_id is None:
|
||||||
|
coginstance.task.cancel()
|
||||||
|
raise ValueError("Pterodactyl server ID not set. Please set it using `[p]pterodactyl config serverid`.")
|
||||||
|
|
||||||
|
client = PterodactylClient(base_url, api_key).client
|
||||||
|
coginstance.client = client
|
||||||
|
websocket_credentials = client.servers.get_websocket(server_id)
|
||||||
|
logger.debug("""Websocket connection details retrieved:
|
||||||
|
Socket: %s
|
||||||
|
Token: %s...""",
|
||||||
|
websocket_credentials['data']['socket'],
|
||||||
|
websocket_credentials['data']['token'][:20]
|
||||||
|
)
|
||||||
|
return websocket_credentials
|
||||||
|
#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:
|
||||||
|
ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
|
||||||
|
#NOTE - https://chat.openai.com/share/d92f9acf-d776-4fd6-a53f-b14ac15dd540
|
||||||
|
return ansi_escape.sub('', text)
|
||||||
|
|
||||||
|
async def check_if_server_message(text: str) -> Union[bool, str]:
|
||||||
|
regex = await config.server_regex()
|
||||||
|
match: Optional[re.Match[str]] = re.match(regex, text)
|
||||||
|
if match:
|
||||||
|
logger.debug("Message is a server message")
|
||||||
|
return match.group(1)
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def check_if_chat_message(text: str) -> Union[bool, dict]:
|
||||||
|
regex = await config.chat_regex()
|
||||||
|
match: Optional[re.Match[str]] = re.match(regex, text)
|
||||||
|
if match:
|
||||||
|
groups = {"username": match.group(1), "message": match.group(2)}
|
||||||
|
logger.debug("Message is a chat message\n%s", json.dumps(groups))
|
||||||
|
return groups
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def check_if_join_message(text: str) -> Union[bool, str]:
|
||||||
|
regex = await config.join_regex()
|
||||||
|
match: Optional[re.Match[str]] = re.match(regex, text)
|
||||||
|
if match:
|
||||||
|
logger.debug("Message is a join message")
|
||||||
|
return match.group(1)
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def check_if_leave_message(text: str) -> Union[bool, str]:
|
||||||
|
regex = await config.leave_regex()
|
||||||
|
match: Optional[re.Match[str]] = re.match(regex, text)
|
||||||
|
if match:
|
||||||
|
logger.debug("Message is a leave message")
|
||||||
|
return match.group(1)
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def check_if_achievement_message(text: str) -> Union[bool, dict]:
|
||||||
|
regex = await config.achievement_regex()
|
||||||
|
match: Optional[re.Match[str]] = re.match(regex, text)
|
||||||
|
if match:
|
||||||
|
groups = {"username": match.group(1), "achievement": match.group(3)}
|
||||||
|
if match.group(2) == "completed the challenge":
|
||||||
|
groups["challenge"] = True
|
||||||
|
else:
|
||||||
|
groups["challenge"] = False
|
||||||
|
logger.debug("Message is an achievement message")
|
||||||
|
return groups
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def get_info(username: str) -> Optional[dict]:
|
||||||
|
logger.debug("Retrieving player info for %s", username)
|
||||||
|
endpoint = await config.api_endpoint()
|
||||||
|
async with aiohttp.ClientSession() as session:
|
||||||
|
async with session.get(f"https://playerdb.co/api/player/{endpoint}/{username}") as response:
|
||||||
|
if response.status == 200:
|
||||||
|
logger.debug("Player info retrieved for %s", username)
|
||||||
|
return await response.json()
|
||||||
|
logger.error("Failed to retrieve player info for %s: %s", username, response.status)
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def send_chat_discord(coginstance: Pterodactyl, username: str, message: str, avatar_url: str) -> None:
|
||||||
|
logger.debug("Sending chat message to Discord")
|
||||||
|
channel = coginstance.bot.get_channel(await config.chat_channel())
|
||||||
|
if channel is not None:
|
||||||
|
webhooks = await channel.webhooks()
|
||||||
|
webhook = discord.utils.get(webhooks, name="Pterodactyl Chat")
|
||||||
|
if webhook is None:
|
||||||
|
webhook = await channel.create_webhook(name="Pterodactyl Chat")
|
||||||
|
await webhook.send(content=message, username=username, avatar_url=avatar_url, allowed_mentions=discord.AllowedMentions(everyone=False, roles=False, users=True))
|
||||||
|
logger.debug("Chat message sent to Discord")
|
||||||
|
else:
|
||||||
|
logger.warning("Chat channel not set. Skipping sending chat message to Discord")
|
||||||
|
|
||||||
|
async def generate_join_leave_embed(username: str, join: bool) -> discord.Embed:
|
||||||
|
embed = discord.Embed()
|
||||||
|
embed.color = discord.Color.green() if join else discord.Color.red()
|
||||||
|
embed.description = await config.join_msg() if join else await config.leave_msg()
|
||||||
|
info = await get_info(username)
|
||||||
|
if info:
|
||||||
|
embed.set_author(name=username, icon_url=info['data']['player']['avatar'])
|
||||||
|
else:
|
||||||
|
embed.set_author(name=username, icon_url='https://seafsh.cc/u/j3AzqQ.png')
|
||||||
|
embed.timestamp = discord.utils.utcnow()
|
||||||
|
return embed
|
||||||
|
|
||||||
|
async def generate_achievement_embed(username: str, achievement: str, challenge: bool) -> discord.Embed:
|
||||||
|
embed = discord.Embed()
|
||||||
|
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)}"
|
||||||
|
info = await get_info(username)
|
||||||
|
if info:
|
||||||
|
embed.set_author(name=username, icon_url=info['data']['player']['avatar'])
|
||||||
|
else:
|
||||||
|
embed.set_author(name=username, icon_url='https://seafsh.cc/u/j3AzqQ.png')
|
||||||
|
embed.timestamp = discord.utils.utcnow()
|
||||||
|
return embed
|
||||||
|
|
||||||
|
def mask_ip(string: str) -> str:
|
||||||
|
def check(match: re.Match[str]):
|
||||||
|
ip = match.group(0)
|
||||||
|
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)
|
|
@ -5,19 +5,21 @@ description = "My assorted cogs for Red-DiscordBot."
|
||||||
authors = ["SeaswimmerTheFsh"]
|
authors = ["SeaswimmerTheFsh"]
|
||||||
license = "MPL 2"
|
license = "MPL 2"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
|
package-mode = false
|
||||||
|
|
||||||
[tool.poetry.dependencies]
|
[tool.poetry.dependencies]
|
||||||
python = ">=3.11,<3.12"
|
python = ">=3.11,<3.12"
|
||||||
Red-DiscordBot = "^3.5.5"
|
Red-DiscordBot = "^3.5.5"
|
||||||
pytimeparse2 = "^1.7.1"
|
py-dactyl = "^2.0.4"
|
||||||
humanize = "^4.8.0"
|
websockets = "^12.0"
|
||||||
py-lav = {extras = ["all"], version = ">=1.14.3,<1.15"}
|
pillow = "^10.3.0"
|
||||||
|
numpy = "^1.26.4"
|
||||||
|
|
||||||
[tool.poetry.group.dev]
|
[tool.poetry.group.dev]
|
||||||
optional = true
|
optional = true
|
||||||
|
|
||||||
[tool.poetry.group.dev.dependencies]
|
[tool.poetry.group.dev.dependencies]
|
||||||
ruff = "^0.2.1"
|
ruff = "^0.3.1"
|
||||||
pylint = "^3.1.0"
|
pylint = "^3.1.0"
|
||||||
|
|
||||||
[tool.poetry.group.docs]
|
[tool.poetry.group.docs]
|
||||||
|
|