Compare commits

...
Sign in to create a new pull request.

105 commits

Author SHA1 Message Date
d89c156744
chore(deps): update ghcr.io/astral-sh/uv docker tag to v0.5.30 (#53)
Some checks failed
Actions / Build Documentation (MkDocs) (push) Failing after 0s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 47s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [ghcr.io/astral-sh/uv](https://github.com/astral-sh/uv) | stage | patch | `0.5.24` -> `0.5.30` |

---

> ⚠️ **Warning**
>
> Some dependencies could not be looked up. Check the Dependency Dashboard for more information.

---

### Release Notes

<details>
<summary>astral-sh/uv (ghcr.io/astral-sh/uv)</summary>

### [`v0.5.30`](https://github.com/astral-sh/uv/blob/HEAD/CHANGELOG.md#0530)

[Compare Source](https://github.com/astral-sh/uv/compare/0.5.29...0.5.30)

##### Python

The managed PyPy distributions have been updated for PyPy v7.3.18, which includes:

-   PyPy3.10, which updates the standard library from Python 3.10.14 to 3.10.19
-   PyPy3.11, which adds beta support for Python 3.11.11

See the [PyPy release](https://pypy.org/posts/2025/02/pypy-v7318-release.html) for more details.

##### Enhancements

-   Add `uv sync --dry-run` ([#&#8203;11299](https://github.com/astral-sh/uv/pull/11299))
-   Ignore `#egg` fragment in HTML Simple API response ([#&#8203;11340](https://github.com/astral-sh/uv/pull/11340))

##### Configuration

-   Add `NO_BINARY` and `NO_BINARY_PACKAGE` environment variables ([#&#8203;11399](https://github.com/astral-sh/uv/pull/11399))

##### Performance

-   Avoid re-cloning name when populating ambiguous set ([#&#8203;11401](https://github.com/astral-sh/uv/pull/11401))
-   Optimize flattening in large workspaces ([#&#8203;11313](https://github.com/astral-sh/uv/pull/11313))

##### Bug fixes

-   Allow dynamic packages to be overloaded ([#&#8203;11400](https://github.com/astral-sh/uv/pull/11400))
-   Fix credential caching for index roots when URL ends in `simple/` ([#&#8203;11336](https://github.com/astral-sh/uv/pull/11336))
-   Fix marker merging for requirements.txt for psycopg ([#&#8203;11298](https://github.com/astral-sh/uv/pull/11298))
-   Set 777 permissions on locked files ([#&#8203;11328](https://github.com/astral-sh/uv/pull/11328))
-   Support extras in `@` requests for tools ([#&#8203;11335](https://github.com/astral-sh/uv/pull/11335))
-   Upgrade `astral-tokio-tar` to v0.5.1 ([#&#8203;11359](https://github.com/astral-sh/uv/pull/11359))
-   Avoid missing logging for no-op upgrade events ([#&#8203;11301](https://github.com/astral-sh/uv/pull/11301))
-   Use refined specifiers when logging narrowed Python range ([#&#8203;11334](https://github.com/astral-sh/uv/pull/11334))
-   Don't use popup-generating `eprintln` in trampoline warnings ([#&#8203;11295](https://github.com/astral-sh/uv/pull/11295))
-   Patch pkg-config files to be relocatable ([#&#8203;11291](https://github.com/astral-sh/uv/pull/11291))
-   Fix a case of duplicate `torch` packages when using conflicting extras ([#&#8203;11323](https://github.com/astral-sh/uv/pull/11323))

##### Documentation

-   Add docs for `uv tool install --editable` ([#&#8203;11280](https://github.com/astral-sh/uv/pull/11280))
-   Fix broken anchors in README and docs index ([#&#8203;11338](https://github.com/astral-sh/uv/pull/11338))

### [`v0.5.29`](https://github.com/astral-sh/uv/blob/HEAD/CHANGELOG.md#0529)

[Compare Source](https://github.com/astral-sh/uv/compare/0.5.28...0.5.29)

##### Enhancements

-   Add `--bare` option to `uv init` ([#&#8203;11192](https://github.com/astral-sh/uv/pull/11192))
-   Add support for respecting `VIRTUAL_ENV` in project commands via `--active` ([#&#8203;11189](https://github.com/astral-sh/uv/pull/11189))
-   Allow the project `VIRTUAL_ENV` warning to be silenced with `--no-active` ([#&#8203;11251](https://github.com/astral-sh/uv/pull/11251))

##### Python

The managed Python distributions have been updated, including:

-   CPython 3.12.9
-   CPython 3.13.2
-   pkg-config files are now relocatable

See the [`python-build-standalone` release notes](https://github.com/astral-sh/python-build-standalone/releases/tag/20250205) for more details.

##### Bug fixes

-   Always use base Python discovery logic for cached environments ([#&#8203;11254](https://github.com/astral-sh/uv/pull/11254))
-   Use a flock to avoid concurrent initialization of project environments ([#&#8203;11259](https://github.com/astral-sh/uv/pull/11259))
-   Fix handling of `--all-groups` and `--no-default-groups` flags ([#&#8203;11224](https://github.com/astral-sh/uv/pull/11224))

##### Documentation

-   Minor touchups to the Docker provenance docs ([#&#8203;11252](https://github.com/astral-sh/uv/pull/11252))
-   Move content from the `mkdocs.public.yml` into the template ([#&#8203;11246](https://github.com/astral-sh/uv/pull/11246))

### [`v0.5.28`](https://github.com/astral-sh/uv/blob/HEAD/CHANGELOG.md#0528)

[Compare Source](https://github.com/astral-sh/uv/compare/0.5.27...0.5.28)

##### Bug fixes

-   Allow discovering virtual environments from the first interpreter found on the `PATH` ([#&#8203;11218](https://github.com/astral-sh/uv/pull/11218))
-   Clear ephemeral overlays when running tools ([#&#8203;11141](https://github.com/astral-sh/uv/pull/11141))
-   Disable SSL in Git commands for `--allow-insecure-host` ([#&#8203;11210](https://github.com/astral-sh/uv/pull/11210))
-   Fix hardlinks in tar unpacking ([#&#8203;11221](https://github.com/astral-sh/uv/pull/11221))
-   Set base executable when returning virtual environment ([#&#8203;11209](https://github.com/astral-sh/uv/pull/11209))
-   Use base Python for cached environments ([#&#8203;11208](https://github.com/astral-sh/uv/pull/11208))

##### Documentation

-   Add documentation on verifying Docker image attestations ([#&#8203;11140](https://github.com/astral-sh/uv/pull/11140))
-   Add `last updated` to documentation ([#&#8203;11164](https://github.com/astral-sh/uv/pull/11164))

### [`v0.5.27`](https://github.com/astral-sh/uv/blob/HEAD/CHANGELOG.md#0527)

[Compare Source](https://github.com/astral-sh/uv/compare/0.5.26...0.5.27)

##### Enhancements

-   Avoid setting permissions during tar extraction ([#&#8203;11191](https://github.com/astral-sh/uv/pull/11191))
-   Remove warnings for missing lower bounds ([#&#8203;11195](https://github.com/astral-sh/uv/pull/11195))
-   Update PubGrub to set-based outdated priority tracking ([#&#8203;11169](https://github.com/astral-sh/uv/pull/11169))
-   Improve error messages for `uv pip install` with `--extra` or `--all-extras` and invalid sources ([#&#8203;11193](https://github.com/astral-sh/uv/pull/11193))
-   Sign Docker images using GitHub attestations ([#&#8203;8685](https://github.com/astral-sh/uv/pull/8685))

##### Preview features

-   Don't expand self-referential extras in the build backend ([#&#8203;11142](https://github.com/astral-sh/uv/pull/11142))

##### Performance

-   Filter discovered Python executables by source before querying ([#&#8203;11143](https://github.com/astral-sh/uv/pull/11143))
-   Optimize exclusion computation for markers ([#&#8203;11158](https://github.com/astral-sh/uv/pull/11158))
-   Use Astral-maintained `tokio-tar` fork ([#&#8203;11174](https://github.com/astral-sh/uv/pull/11174))
-   Remove unneeded `.clone()` ([#&#8203;11127](https://github.com/astral-sh/uv/pull/11127))

##### Bug fixes

-   Fix relative paths in bytecode compilation ([#&#8203;11177](https://github.com/astral-sh/uv/pull/11177))
-   Percent-decode URLs in canonical comparisons ([#&#8203;11088](https://github.com/astral-sh/uv/pull/11088))
-   Respect concurrency limits in parallel index fetch ([#&#8203;11182](https://github.com/astral-sh/uv/pull/11182))
-   Use wire JSON schema for conflict items ([#&#8203;11196](https://github.com/astral-sh/uv/pull/11196))
-   Use explicit `_GLibCVersion` tuple in uv-python crate ([#&#8203;11122](https://github.com/astral-sh/uv/pull/11122))

##### Documentation

-   Add Git SHA locking behavior to docs ([#&#8203;11125](https://github.com/astral-sh/uv/pull/11125))
-   Add best-practice flags to `pip install` example in troubleshooting guide ([#&#8203;11194](https://github.com/astral-sh/uv/pull/11194))
-   Set `VIRTUAL_ENV` in Jupyter kernels ([#&#8203;11155](https://github.com/astral-sh/uv/pull/11155))
-   Add instructions for deactivating an environment ([#&#8203;11200](https://github.com/astral-sh/uv/pull/11200))

### [`v0.5.26`](https://github.com/astral-sh/uv/blob/HEAD/CHANGELOG.md#0526)

[Compare Source](https://github.com/astral-sh/uv/compare/0.5.25...0.5.26)

##### Enhancements

-   Add support for `uvx python` ([#&#8203;11076](https://github.com/astral-sh/uv/pull/11076))
-   Allow `--no-dev --invert` in `uv tree` ([#&#8203;11068](https://github.com/astral-sh/uv/pull/11068))
-   Update `uv python install --reinstall` to reinstall all previous versions ([#&#8203;11072](https://github.com/astral-sh/uv/pull/11072))
-   Consistently write log messages with capitalized first word ([#&#8203;11111](https://github.com/astral-sh/uv/pull/11111))
-   Suggest `--build-backend` when `--backend` is passed to `uv init` ([#&#8203;10958](https://github.com/astral-sh/uv/pull/10958))
-   Improve retry trace message ([#&#8203;11108](https://github.com/astral-sh/uv/pull/11108))

##### Performance

-   Remove unnecessary UTF-8 conversion in hash parsing ([#&#8203;11110](https://github.com/astral-sh/uv/pull/11110))

##### Bug fixes

-   Ignore non-hash fragments in HTML API responses ([#&#8203;11107](https://github.com/astral-sh/uv/pull/11107))
-   Avoid resolving symbolic links when querying Python interpreters ([#&#8203;11083](https://github.com/astral-sh/uv/pull/11083))
-   Avoid sharing state between universal and non-universal resolves ([#&#8203;11051](https://github.com/astral-sh/uv/pull/11051))
-   Error when `--script` is passing a non-PEP 723 script ([#&#8203;11118](https://github.com/astral-sh/uv/pull/11118))
-   Make metadata deserialization failures non-fatal in the cache ([#&#8203;11105](https://github.com/astral-sh/uv/pull/11105))
-   Mark metadata as dynamic when reading from built wheel cache ([#&#8203;11046](https://github.com/astral-sh/uv/pull/11046))
-   Propagate credentials for `<index>/simple` to `<index>/...` endpoints ([#&#8203;11074](https://github.com/astral-sh/uv/pull/11074))
-   Fix conflicting extra bug during `uv sync` ([#&#8203;11075](https://github.com/astral-sh/uv/pull/11075))

##### Documentation

-   Add PyTorch XPU instructions to the PyTorch guide ([#&#8203;11109](https://github.com/astral-sh/uv/pull/11109))
-   Add docs for signal handling ([#&#8203;11041](https://github.com/astral-sh/uv/pull/11041))
-   Explain build frontend vs. build backend ([#&#8203;11094](https://github.com/astral-sh/uv/pull/11094))
-   Fix formatting of `RUST_LOG` documentation ([#&#8203;10053](https://github.com/astral-sh/uv/pull/10053))
-   Fix typo in `--no-deps` description ([#&#8203;11073](https://github.com/astral-sh/uv/pull/11073))
-   Reflow CLI documentation comments ([#&#8203;11040](https://github.com/astral-sh/uv/pull/11040))
-   Shorten "Using existing Python versions" nav item so it fits on one line ([#&#8203;11077](https://github.com/astral-sh/uv/pull/11077))
-   Some minor touch-ups to the Python install guide ([#&#8203;11116](https://github.com/astral-sh/uv/pull/11116))
-   Update Dependabot tracking issue link ([#&#8203;11054](https://github.com/astral-sh/uv/pull/11054))
-   Update documentation for running in a container ([#&#8203;11052](https://github.com/astral-sh/uv/pull/11052))
-   Upgrade PyTorch version in documentation ([#&#8203;11114](https://github.com/astral-sh/uv/pull/11114))
-   Use `sys_platform` in lieu of `platform_system` in PyTorch docs ([#&#8203;11113](https://github.com/astral-sh/uv/pull/11113))
-   Use positive (rather than negative) markers in PyTorch examples ([#&#8203;11112](https://github.com/astral-sh/uv/pull/11112))
-   Fix unnecessary backslashes in brackets ([#&#8203;11059](https://github.com/astral-sh/uv/pull/11059))
-   Suggest setting copy link mode in GitLab integration guide ([#&#8203;11067](https://github.com/astral-sh/uv/pull/11067))

### [`v0.5.25`](https://github.com/astral-sh/uv/blob/HEAD/CHANGELOG.md#0525)

[Compare Source](https://github.com/astral-sh/uv/compare/0.5.24...0.5.25)

##### Enhancements

-   Allow installation of manylinux wheels on loongarch64 ([#&#8203;10927](https://github.com/astral-sh/uv/pull/10927))
-   Allow optional `=` for editables in `requirements.txt` ([#&#8203;10954](https://github.com/astral-sh/uv/pull/10954))
-   Add Windows aarch64 to the release binaries ([#&#8203;10885](https://github.com/astral-sh/uv/pull/10885))

##### Bug fixes

-   Use spec-compliant (`128+n`) exit codes for `uv run` and `uv tool run` on Unix ([#&#8203;10781](https://github.com/astral-sh/uv/pull/10781))
-   Fix best-interpreter lookups when there is an invalid interpreter in the `PATH` ([#&#8203;11030](https://github.com/astral-sh/uv/pull/11030))
-   Guard against concurrent cache writes on Windows ([#&#8203;11007](https://github.com/astral-sh/uv/pull/11007))
-   Prioritize package preferences with greater package versions ([#&#8203;10963](https://github.com/astral-sh/uv/pull/10963))
-   Reject `--editable` flag on non-directory requirements ([#&#8203;10994](https://github.com/astral-sh/uv/pull/10994))
-   Respect `--no-sources` for `uv pip install` workspace discovery ([#&#8203;11003](https://github.com/astral-sh/uv/pull/11003))
-   Set `JEMALLOC_SYS_WITH_LG_PAGE=16` in ARM Docker builds ([#&#8203;10943](https://github.com/astral-sh/uv/pull/10943))
-   Update `riscv64` Python downloads to allow install on `riscv64gc` ([#&#8203;10937](https://github.com/astral-sh/uv/pull/10937))
-   Fix file persist retries on Windows ([#&#8203;11008](https://github.com/astral-sh/uv/pull/11008))
-   Fix incorrect error message when specifying `tool.uv.sources.(package).workspace` with other options ([#&#8203;11013](https://github.com/astral-sh/uv/pull/11013))
-   Improve SIGINT handling in `uv run` ([#&#8203;11009](https://github.com/astral-sh/uv/pull/11009))

##### Documentation

-   Add `SECURITY` policy ([#&#8203;11035](https://github.com/astral-sh/uv/pull/11035))
-   Add `Requires-Python` upper bound behavior to the docs ([#&#8203;10964](https://github.com/astral-sh/uv/pull/10964))
-   Add a troubleshooting section and reproducible example guide ([#&#8203;10947](https://github.com/astral-sh/uv/pull/10947))
-   Add documentation for `uv add -r` ([#&#8203;10926](https://github.com/astral-sh/uv/pull/10926))
-   Amend `requires-python` rules in resolver documentation ([#&#8203;10993](https://github.com/astral-sh/uv/pull/10993))
-   Reference workspaces in `--no-sources` documentation ([#&#8203;10995](https://github.com/astral-sh/uv/pull/10995))
-   Update documentation for activating virtual environments in different shell ([#&#8203;11000](https://github.com/astral-sh/uv/pull/11000))
-   Add Docker SHA pinning tip ([#&#8203;10955](https://github.com/astral-sh/uv/pull/10955))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzOS4xNDAuMCIsInVwZGF0ZWRJblZlciI6IjM5LjE2My4wIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119-->

Reviewed-on: #53
Co-authored-by: Renovate <renovate@csw.im>
Co-committed-by: Renovate <renovate@csw.im>
2025-02-10 23:01:15 -05:00
e854abfb0e
feat(backup): update to most recent red version
Some checks failed
Actions / Build Documentation (MkDocs) (push) Failing after 0s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 51s
2025-02-08 19:00:45 -06:00
7ada16e999
chore(tooling): add .editorconfig 2025-02-08 19:00:36 -06:00
d649ca0f02
chore(repo): formatting
Some checks failed
Actions / Lint Code (Ruff & Pylint) (push) Failing after 0s
Actions / Build Documentation (MkDocs) (push) Failing after 0s
2025-02-07 16:07:50 -06:00
72dcc96fea
chore(tooling): remove comments 2025-02-07 16:07:44 -06:00
527c372fb0
chore(tooling): fix the nix flake
Some checks failed
Actions / Build Documentation (MkDocs) (push) Failing after 26s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 47s
2025-02-06 17:20:39 -06:00
e7714cd2df
fix(hotreload): fix typehint 2025-02-06 17:20:21 -06:00
9b96a15621
chore(repo): add schemas to repo.json files
Some checks failed
Actions / Lint Code (Ruff & Pylint) (push) Failing after 46s
Actions / Build Documentation (MkDocs) (push) Failing after 24s
2025-02-06 15:10:19 -06:00
7593aace00
chore(tooling): add dig to the nix flake
Some checks failed
Actions / Build Documentation (MkDocs) (push) Failing after 29s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 49s
2025-02-06 06:41:39 -06:00
e4f419ec7b
chore(repo): formatting
Some checks failed
Actions / Build Documentation (MkDocs) (push) Failing after 27s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 52s
2025-02-06 06:41:00 -06:00
1224d2b60f
chore(deps): update dependencies 2025-02-06 06:40:49 -06:00
999fd8e96f
chore(tooling): re-add nix flake and update deps
Some checks failed
Actions / Build Documentation (MkDocs) (push) Failing after 27s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 48s
2025-02-04 20:18:31 -06:00
2a5b924409
feat(repo): make all cogs pylance-typechecking compliant
Some checks failed
Actions / Lint Code (Ruff & Pylint) (push) Failing after 43s
Actions / Build Documentation (MkDocs) (push) Failing after 24s
at `basic` level, does not include Aurora as it's being rewritten in the `aurora/v3` branch
2025-02-01 16:57:45 +00:00
ea0b7937f8
chore(tooling): switch to zsh in the dev shell 2025-02-01 16:56:49 +00:00
034748b08e
chore(deps): update dependencies 2025-02-01 16:56:34 +00:00
89d5108ef2
chore(repo): update pull request template
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 39s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 45s
2025-01-29 23:34:52 +00:00
3eeb2f90a6
feat(hotreload): add pre-compilation
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 40s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 44s
this feature will detect syntax errors before reloading a cog and cancel the cog reload if it detects one. DOES NOT detect runtime/logic errors, only syntax errors.
2025-01-29 23:24:19 +00:00
7c2ff7681c
chore(deps): update code.forgejo.org/forgejo/runner docker tag to v6.2.1 (#56)
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 40s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 45s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [code.forgejo.org/forgejo/runner](https://forgejo.org) ([source](https://code.forgejo.org/forgejo/runner)) | stage | patch | `6.2.0` -> `6.2.1` |

---

> ⚠️ **Warning**
>
> Some dependencies could not be looked up. Check the Dependency Dashboard for more information.

---

### Release Notes

<details>
<summary>forgejo/runner (code.forgejo.org/forgejo/runner)</summary>

### [`v6.2.1`](https://code.forgejo.org/forgejo/runner/blob/HEAD/RELEASE-NOTES.md#621)

[Compare Source](https://code.forgejo.org/forgejo/runner/compare/v6.2.0...v6.2.1)

-   LXC [templates are updated if needed](https://code.forgejo.org/forgejo/act/pulls/102).

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzOS4xNDAuMCIsInVwZGF0ZWRJblZlciI6IjM5LjE0MC4wIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119-->

Reviewed-on: https://www.coastalcommits.com/cswimr/SeaCogs/pulls/56
Co-authored-by: Renovate <renovate@coastalcommits.com>
Co-committed-by: Renovate <renovate@coastalcommits.com>
2025-01-29 13:39:57 -05:00
1ca452669c
chore(deps): pin code.forgejo.org/forgejo/runner docker tag to 936c4fe (#52)
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 42s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 52s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [code.forgejo.org/forgejo/runner](https://forgejo.org) ([source](https://code.forgejo.org/forgejo/runner)) | stage | pinDigest |  -> `936c4fe` |

---

> ⚠️ **Warning**
>
> Some dependencies could not be looked up. Check the Dependency Dashboard for more information.

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzOS4xMzMuNCIsInVwZGF0ZWRJblZlciI6IjM5LjEzMy40IiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119-->

Reviewed-on: https://www.coastalcommits.com/cswimr/SeaCogs/pulls/52
Co-authored-by: Renovate <renovate@coastalcommits.com>
Co-committed-by: Renovate <renovate@coastalcommits.com>
2025-01-26 17:36:59 -05:00
666efaf893
chore(devcontainer): add DiD, forgejo runner, aliases
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 43s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 50s
2025-01-26 22:27:22 +00:00
289da84b76
fix(hotreload): use 3.8-compatible typehints
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 44s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 50s
2025-01-26 21:31:48 +00:00
5c6783452d
fix(hotreload): verify that a file path exists before creating an observer schedule for it
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 47s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 52s
2025-01-26 21:29:02 +00:00
70d75c688c
fix(hotreload): only import ObserverType for TYPE_CHECKING 2025-01-26 21:23:08 +00:00
76f0a4cdd4
chore(hotreload): support python 3.8+ instead of 3.10+
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 51s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 58s
2025-01-26 21:09:38 +00:00
19eca0b1b5
docs: fixed incorrect command instructions
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 42s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 48s
2025-01-26 15:33:34 +00:00
9e489a4c91
docs(hotreload): add docs
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 40s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 46s
2025-01-26 15:29:07 +00:00
1993da084d
docs(hotreload): add docs
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 43s
Actions / Lint Code (Ruff & Pylint) (push) Has been cancelled
2025-01-26 15:28:21 +00:00
b22d81f514
feat(hotreload): handle multiple observers
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 42s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 47s
2025-01-26 15:18:05 +00:00
ccf9389e13
feat(hotreload): Channel Notifications (#51)
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 41s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 47s
# Channel Notifications

This PR adds the ability for HotReload to send messages to a configurable discord channel when reloading a cog. Messages are only sent after the cog is reloaded to prevent slowdowns.
<!-- Create a new issue, if it doesn't exist yet -->

- [x] By submitting this pull request, I permit [cswimr](https://www.coastalcommits.com/cswimr) to license my work under
  the [Mozilla Public License Version 2.0](https://www.coastalcommits.com/cswimr/SeaCogs/src/branch/main/LICENSE).

Reviewed-on: https://www.coastalcommits.com/cswimr/SeaCogs/pulls/51
2025-01-26 10:06:14 -05:00
ff9e20be91
fix(pterodactyl): update pterodactyl for the new version of websockets & fix a few minor bugs
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 42s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 47s
2025-01-26 15:04:05 +00:00
d51e3f17e9
fix(antipolls): ruff fixes
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 42s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 48s
2025-01-26 14:22:12 +00:00
59d33ea87d
style(seautils): ruff fix
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 44s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 49s
2025-01-26 14:16:46 +00:00
65cfafc7b3
style(emojiinfo): ruff fix 2025-01-26 14:16:39 +00:00
ea5f51892a
style(repo): ruff fixes
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 42s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 47s
2025-01-26 14:13:37 +00:00
9df7f15bbe
chore(repo): enable even more ruff rules 2025-01-26 14:11:37 +00:00
4ad73ec6ee
fix(pterodactyl): ruff fix
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 43s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 47s
2025-01-26 14:10:48 +00:00
2543563af1
fix(hotreload): ruff fix 2025-01-26 14:10:48 +00:00
0b60a2df66
chore(repo): enable more ruff rules
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 44s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 49s
2025-01-26 14:03:28 +00:00
6f0fee8275
fix(backup): disable SLF001
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 45s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 52s
2025-01-26 13:42:57 +00:00
dbff8d0d2a
chore(repo): enable some more ruff rules 2025-01-26 13:42:48 +00:00
0c43e3d2c9
fix(backup): update for red 3.5.14 & reformat
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 44s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 51s
2025-01-26 13:21:28 +00:00
0f47a15291
fix(emojiinfo): ruff fixes & rename logger
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 43s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 49s
2025-01-26 13:18:04 +00:00
7f2a81e350
fix(bible): ruff fixes 2025-01-26 13:16:54 +00:00
5c5a2f28b2
chore(repo): reformat pyproject.toml and disable a stupid linting rule 2025-01-26 13:16:26 +00:00
d5a248733a
fix(pterodactyl): fix a ruff violation
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 44s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 51s
2025-01-26 13:09:15 +00:00
5decc51a36
chore(deps): update 2025-01-26 13:08:33 +00:00
41678ef3ed
chore(repo): enable more ruff linting rules 2025-01-26 13:08:28 +00:00
0492b30662
chore(repo): add two paths to gitignore 2025-01-26 13:08:02 +00:00
3063721b8d
chore(vscode): add some settings overrides 2025-01-26 13:07:46 +00:00
3d882625d2
style(seautils): reformat
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 36s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 40s
2025-01-26 01:54:02 +00:00
6c25d61dfd
fix(hotreload): use %s formatting in logging strings 2025-01-26 01:53:40 +00:00
6ffa81fdee
fix(bible): fix ruff errors 2025-01-26 01:53:09 +00:00
06e678f26f
style(repo): enable some more linting rules 2025-01-26 01:52:46 +00:00
e5210420cb
chore(vscode): force load hotreload in launch & debug configuration
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 35s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 40s
2025-01-26 01:08:06 +00:00
1677412b56
chore(hotreload): add disclaimer in install message that this cog doesn't add any commands
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 36s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 40s
2025-01-26 00:56:50 +00:00
451ecfe5d9
chore(tooling): disable too-many-positional-arguments
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 37s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 41s
2025-01-26 00:48:25 +00:00
8511b7b964
fix(bible): mark cog_unload as async 2025-01-26 00:46:21 +00:00
f233a7dec5
fix(hotreload): mark cog_load and cog_unload as async 2025-01-26 00:46:00 +00:00
18ba837467
fix(workflow): run on main branch and prs only, run docs build on prs
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 36s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 41s
2025-01-26 00:43:02 +00:00
2859f93501
fix(bible): close asyncio session after unloading the cog
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 35s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 40s
2025-01-26 00:39:09 +00:00
7d1a9cc01a
fix(hotreload): only add dest_package_name to the cogs_to_reload list if dest_package_name != src_package_name
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 34s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 40s
fix(hotreload): only add `dest_package_name` to the `cogs_to_reload` list if `dest_package_name != src_package_name`
2025-01-26 00:32:29 +00:00
5adc7a2c7b
feat(hotreload): Add more events (#50)
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 35s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 38s
# More HotReload Events
<!-- Create a new issue, if it doesn't exist yet -->
Currently, HotReload only supports file modification events. It should also support file moves, and some other event types.

- [x] By submitting this pull request, I permit cswimr to license my work under
  the [Mozilla Public License Version 2.0](https://www.coastalcommits.com/cswimr/SeaCogs/src/branch/main/LICENSE).

Reviewed-on: https://www.coastalcommits.com/cswimr/SeaCogs/pulls/50
2025-01-25 19:25:29 -05:00
5384809780
feat(hotreload): init (#49)
Some checks failed
Actions / Build Documentation (MkDocs) (push) Has been skipped
Actions / Lint Code (Ruff & Pylint) (push) Failing after 42s
Actions / Build Documentation (MkDocs) (pull_request) Has been skipped
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 41s
This pull request adds a cog that allows for automatic reloading of local cogs.

- [x] By submitting this pull request, I permit [cswimr](https://www.coastalcommits.com) to license my work under
  the [Mozilla Public License Version 2.0](https://www.coastalcommits.com/cswimr/SeaCogs/src/branch/main/LICENSE).

Reviewed-on: https://www.coastalcommits.com/cswimr/SeaCogs/pulls/49
2025-01-25 23:55:37 +00:00
78f036da48
feat(devcontainer): initialize redbot instance in postCreateCommand
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 37s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 41s
2025-01-25 22:50:35 +00:00
f831bfcdd5
feat(vscode): add --dev argument to redbot args
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 40s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 43s
2025-01-25 16:50:51 -05:00
9b60a8f01e
chore(vscode): add -vvv argument to launch & debug
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 37s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 41s
2025-01-25 15:47:05 -05:00
7369f5810a
fix(devcontainer): chown workspace directory
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 40s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 41s
for some reason, the default `.data` mount is not owned by the `vscode` user (on my system at least), so we `chown` it to ensure that `uv run redbot-setup` can write to the directory.
2025-01-25 14:43:02 -05:00
a8bb62dcf3
fix(devcontainer): ensure pip is installed in the devcontainer
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 37s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 41s
this is being done because Red-DiscordBot requires pip to be installed to function, but does not declare it as a dependency. this is only a problem when uv is being used to install dependencies in an environment where pip is not present. so, we ensure pip is present!
2025-01-25 14:39:24 -05:00
d910b0f4e1
chore(repo): add vscode run and debug configuration
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 38s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 42s
2025-01-24 23:12:58 +00:00
a04f1ddc6e
Merge pull request 'chore(deps): update www.coastalcommits.com/cswimr/actions:docs docker digest to e405cd6' (#43) from renovate/www.coastalcommits.com-cswimr-actions-docs into main
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 40s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 43s
Reviewed-on: https://www.coastalcommits.com/cswimr/SeaCogs/pulls/43
2025-01-24 18:07:33 -05:00
536a8c3c82
Merge pull request 'chore(deps): pin dependencies' (#46) from renovate/pin-dependencies into main
Some checks failed
Actions / Build Documentation (MkDocs) (push) Failing after 0s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 44s
Reviewed-on: https://www.coastalcommits.com/cswimr/SeaCogs/pulls/46
2025-01-24 18:06:29 -05:00
9f1c1cfc01
Merge branch 'main' into renovate/pin-dependencies
Some checks failed
Actions / Build Documentation (MkDocs) (push) Has been skipped
Actions / Build Documentation (MkDocs) (pull_request) Has been skipped
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 44s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 46s
2025-01-24 18:06:12 -05:00
ffd45c77c5
chore(devcontainer): change volume name
Some checks failed
Actions / Build Documentation (MkDocs) (push) Failing after 0s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 44s
2025-01-24 23:05:24 +00:00
d62ff5b3c9
chore(repo): update red-discordbot and add pip 2025-01-24 23:05:15 +00:00
e3ecd995e9
chore(deps): update www.coastalcommits.com/cswimr/actions:docs docker digest to e405cd6
Some checks failed
Actions / Build Documentation (MkDocs) (push) Has been skipped
Actions / Lint Code (Ruff & Pylint) (push) Failing after 45s
Actions / Build Documentation (MkDocs) (pull_request) Has been skipped
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 43s
2025-01-24 22:53:50 +00:00
62d6ea6d66
chore(deps): pin dependencies
Some checks failed
Actions / Build Documentation (MkDocs) (push) Has been skipped
Actions / Build Documentation (MkDocs) (pull_request) Has been skipped
Actions / Lint Code (Ruff & Pylint) (push) Failing after 45s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 46s
2025-01-24 22:53:48 +00:00
616d81d398
switch to devcontainers
Some checks failed
Actions / Build Documentation (MkDocs) (push) Failing after 0s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 42s
2025-01-24 22:17:25 +00:00
071dcf7e27
chore(deps): update www.coastalcommits.com/cswimr/actions:uv docker digest to 211aaf7
Some checks failed
Actions / Build Documentation (MkDocs) (pull_request) Has been skipped
Actions / Build Documentation (MkDocs) (push) Failing after 0s
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 46s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 45s
2025-01-24 00:11:43 +00:00
493f4fde34
style(repo): format nix flake
Some checks failed
Actions / Build Documentation (MkDocs) (push) Failing after 0s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 41s
2025-01-22 08:57:20 -06:00
43d4a1c911
chore(deps): update www.coastalcommits.com/cswimr/actions:uv docker digest to 95493fb
Some checks failed
Actions / Build Documentation (MkDocs) (pull_request) Has been skipped
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 43s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 42s
Actions / Build Documentation (MkDocs) (push) Has been skipped
2025-01-22 00:03:50 +00:00
f0ced3bbb6
chore(repo): update renovate config
Some checks failed
Actions / Lint Code (Ruff & Pylint) (push) Failing after 44s
Actions / Build Documentation (MkDocs) (push) Successful in 44s
2024-12-27 22:53:54 -05:00
431a9d9e71
Merge pull request 'chore(deps): pin dependencies' (#36) from renovate/pin-dependencies into main
Some checks failed
Actions / Lint Code (Ruff & Pylint) (push) Failing after 40s
Actions / Build Documentation (MkDocs) (push) Successful in 41s
Reviewed-on: https://www.coastalcommits.com/cswimr/SeaCogs/pulls/36
2024-12-27 15:26:24 -05:00
203b6aec64
chore(deps): pin dependencies
Some checks failed
Actions / Build Documentation (MkDocs) (push) Has been skipped
Actions / Lint Code (Ruff & Pylint) (push) Failing after 39s
Actions / Build Documentation (MkDocs) (pull_request) Has been skipped
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 38s
2024-12-27 20:25:46 +00:00
e2b85dedd7
Update renovate.json
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 40s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 41s
2024-12-27 15:08:48 -05:00
cea73b7955
Merge pull request 'chore(deps): update actions/checkout action to v4' (#37) from renovate/actions-checkout-4.x into main
Some checks failed
Actions / Lint Code (Ruff & Pylint) (push) Failing after 40s
Actions / Build Documentation (MkDocs) (push) Successful in 40s
Reviewed-on: https://www.coastalcommits.com/cswimr/SeaCogs/pulls/37
2024-12-27 14:52:01 -05:00
e2c4e20cfc
chore(deps): update actions/checkout action to v4
Some checks failed
Actions / Build Documentation (MkDocs) (push) Has been skipped
Actions / Lint Code (Ruff & Pylint) (push) Failing after 48s
Actions / Build Documentation (MkDocs) (pull_request) Has been skipped
Actions / Lint Code (Ruff & Pylint) (pull_request) Failing after 41s
2024-12-27 19:48:58 +00:00
35b4c08461
Add renovate.json
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 43s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 44s
2024-12-27 10:51:43 -05:00
7af8e02462
chore(repo): flake formatting
Some checks failed
Actions / Lint Code (Ruff & Pylint) (push) Failing after 48s
Actions / Build Documentation (MkDocs) (push) Successful in 1m5s
2024-11-20 12:33:59 -05:00
a40f78e88f
chore(repo): use nixpkgs-python to get python version instead of setting languages.python.package
Some checks failed
Actions / Lint Code (Ruff & Pylint) (push) Failing after 47s
Actions / Build Documentation (MkDocs) (push) Successful in 1m3s
2024-11-20 12:27:59 -05:00
216fa74a53
chore(repo): add nix flake dev-shell for development environment
Some checks failed
Actions / Lint Code (Ruff & Pylint) (push) Failing after 43s
Actions / Build Documentation (MkDocs) (push) Successful in 56s
2024-11-20 12:22:57 -05:00
901c10a458
chore(repo): update issue templates
Some checks failed
Actions / Lint Code (Ruff & Pylint) (push) Failing after 29s
Actions / Build Documentation (MkDocs) (push) Successful in 30s
2024-11-01 11:21:38 -04:00
1150115171
remove poetry file and update workflow file to use correct meli secret
Some checks failed
Actions / Build Documentation (MkDocs) (push) Has been skipped
Actions / Lint Code (Ruff & Pylint) (push) Failing after 29s
2024-10-21 16:53:28 -04:00
8d4d61c017
chore(repo): add uv.lock file
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 28s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 33s
2024-10-10 16:08:39 -04:00
23f2aaa2ee
feat(workflow): move to uv
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 32s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 35s
2024-10-10 16:03:50 -04:00
8b6d269e1a
(repo): switch to uv
Some checks failed
Actions / Lint Code (Ruff & Pylint) (push) Failing after 4s
Actions / Build Documentation (MkDocs) (push) Failing after 7s
Signed-off-by: cswimr <seaswimmerthefsh@gmail.com>
2024-10-10 16:01:54 -04:00
8c323e36a9
docs(pterodactyl): link to the pelican-eggs repository instead of some random fork
Some checks failed
Actions / Lint Code (Ruff & Pylint) (push) Failing after 39s
Actions / Build Documentation (MkDocs) (push) Successful in 32s
Signed-off-by: cswimr <seaswimmerthefsh@gmail.com>
2024-09-25 12:07:53 -04:00
1392a9324a
chore(poetry): update deps
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 34s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 44s
2024-08-28 17:01:58 -04:00
9cba1767e6
fix(repo): update all instances of SeaswimmerTheFsh to cswimr
Some checks failed
Actions / Build Documentation (MkDocs) (push) Failing after 22s
Actions / Lint Code (Ruff & Pylint) (push) Successful in 39s
2024-08-27 14:25:14 -04:00
cbfff6d211
fix(backup): update for red 3.5.13
All checks were successful
Actions / Lint Code (Ruff & Pylint) (push) Successful in 40s
Actions / Build Documentation (MkDocs) (push) Successful in 28s
2024-08-27 14:22:38 -04:00
56d1e14454
feat(repo): updated all cogs (except aurora) to use the help formatting present in the indev version of aurora 2024-08-27 14:22:19 -04:00
571be4e245
fix(pterodactyl): fixed a missing argument in one of the websocket events
All checks were successful
Actions / Build Documentation (MkDocs) (push) Successful in 26s
Actions / Lint Code (Ruff & Pylint) (push) Successful in 37s
2024-08-27 14:05:10 -04:00
6b2793e692
fix(actions): updated container tags
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 28s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 38s
2024-08-27 14:03:15 -04:00
ad0bb7cf00
fix(pterodactyl): fixed join and leave listeners throwing errors
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 31s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 56s
2024-08-26 19:43:57 -04:00
1244d5a941
fix(pterodactyl): don't depend on a website to host images when i can bundle image files in the cog itself
Some checks failed
Actions / Build Documentation (MkDocs) (push) Successful in 30s
Actions / Lint Code (Ruff & Pylint) (push) Failing after 54s
2024-08-26 17:46:42 -04:00
1c0f12660b
chore(pterodactyl): clean up some dirty code
All checks were successful
Actions / Build Documentation (MkDocs) (push) Successful in 30s
Actions / Lint Code (Ruff & Pylint) (push) Successful in 54s
2024-08-26 15:03:37 -04:00
57 changed files with 3250 additions and 3345 deletions

38
.devcontainer/Dockerfile Normal file
View file

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

View file

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

View file

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

View file

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

View file

@ -5,14 +5,14 @@ Backup allows you to export a JSON list of all of your installed repositories an
## Installation
```bash
[p]repo add seacogs https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs
[p]repo add seacogs https://www.coastalcommits.com/cswimr/SeaCogs
[p]cog install seacogs backup
[p]cog load backup
[p]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`.
As of commit [1edb08a](https://www.coastalcommits.com/cswimr/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

View file

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

View file

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

26
.docs/hotreload.md Normal file
View file

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

View file

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

View file

@ -28,7 +28,7 @@ The Downloader cog allows you to add Git repositories to your bot in order to do
Now, use Downloader to add my repository to your bot:
```
[p]repo add sea-cogs https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs
[p]repo add sea-cogs https://www.coastalcommits.com/cswimr/SeaCogs
```
Now, install the Pterodactyl cog:

View file

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

View file

@ -10,7 +10,7 @@ There are a few caveats to running an instance of Red on Pterodactyl.
- You will not receive any support from the Red developers.
- 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).
- Depending on your host, you might have to request a [`tmpfs` size increase](https://github.com/pelican-eggs/eggs/tree/master/bots/discord/redbot#additional-requirements).
If these are unacceptable to you, you should [install Red normally](https://docs.discord.red/en/stable/install_guides/index.html).
///
@ -64,7 +64,7 @@ Red is quite a large bot, so I'll focus on the specifics of getting the bot work
```
2. Add my repository to the bot
```bash
[p]repo add sea-cogs https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs
[p]repo add sea-cogs https://www.coastalcommits.com/cswimr/SeaCogs
```
3. Install and load the Pterodactyl cog
```bash

12
.editorconfig Normal file
View file

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

1
.envrc Normal file
View file

@ -0,0 +1 @@
use flake

View file

@ -1,8 +1,6 @@
name: Bug Report
about: File a bug report
title: "[Cog Name] "
labels: [bug]
ref: master
body:
- type: markdown
attributes:
@ -13,7 +11,7 @@ body:
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.
- label: I have checked that this bug does not already have an opened/closed [issue](https://www.coastalcommits.com/cswimr/SeaCogs/issues) or [pull request](https://www.coastalcommits.com/cswimr/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

View file

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

View file

@ -2,5 +2,5 @@
<!-- 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).
- [ ] By submitting this pull request, I permit [cswimr](https://www.coastalcommits.com/cswimr) to license my work under
the [Mozilla Public License Version 2.0](https://www.coastalcommits.com/cswimr/SeaCogs/src/branch/main/LICENSE).

View file

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

View file

@ -2,38 +2,46 @@ name: Actions
on:
push:
branches:
- 'main'
- main
pull_request:
jobs:
Lint Code (Ruff & Pylint):
lint:
name: Lint Code (Ruff & Pylint)
runs-on: docker
container: www.coastalcommits.com/seaswimmerthefsh/actionscontainers-seacogs:latest
container: www.coastalcommits.com/cswimr/actions:uv@sha256:211aaf7d9ac98087579ebf9fab87a9122f51b2697e3a3649ac9f4bd3b03b8e5d
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- name: Install python
run: uv python install 3.11
- name: Install dependencies
run: poetry install --with dev --no-root
run: uv sync
- name: Analysing code with Ruff
run: ./.venv/bin/ruff check $(git ls-files '*.py')
run: uv run ruff check $(git ls-files '*.py')
continue-on-error: true
- name: Analysing code with Pylint
run: ./.venv/bin/pylint --rcfile=.forgejo/workflows/config/.pylintrc $(git ls-files '*.py')
run: uv run pylint --rcfile=.forgejo/workflows/config/.pylintrc $(git ls-files '*.py')
Build Documentation (MkDocs):
docs:
name: Build Documentation (MkDocs)
runs-on: docker
container: www.coastalcommits.com/seaswimmerthefsh/actionscontainers-seacogs:latest
container: www.coastalcommits.com/cswimr/actions:docs@sha256:e405cd6b9b1182a570ddee32ed8dd1b2f899edc625d006c8b4b2f18c100e724f
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
with:
fetch-depth: 0
- name: Install python
run: uv python install 3.11
- name: Install dependencies
run: poetry install --with docs --no-root
run: uv sync --no-dev --extra=documentation
- name: Set environment variables
uses: actions/env@v2
@ -42,7 +50,7 @@ jobs:
run: |
export SITE_URL="https://$CI_ACTION_REF_NAME_SLUG.seacogs.coastalcommits.com"
export EDIT_URI="src/branch/$CI_ACTION_REF_NAME/.docs"
./.venv/bin/mkdocs build -v
uv run mkdocs build -v
- name: Deploy documentation
run: |
@ -58,7 +66,7 @@ jobs:
npx -p "@getmeli/cli" meli upload ./site \
--url "https://pages.coastalcommits.com" \
--site "${{ vars.MELI_SITE_ID }}" \
--token "${{ secrets.MELI_SECRET }}" \
--token "${{ secrets.MELI_TOKEN }}" \
--release "$CI_ACTION_REF_NAME_SLUG/${{ env.GITHUB_SHA }}" \
--branch "$CI_ACTION_REF_NAME_SLUG"

5
.gitignore vendored
View file

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

12
.vscode/launch.json vendored Normal file
View file

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

32
.vscode/settings.json vendored Normal file
View file

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

View file

@ -11,7 +11,7 @@ My assorted cogs for Red-DiscordBot.
To get started with a development environment, first clone this repository.
```sh
git clone https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs.git
git clone https://coastalcommits.com/cswimr/SeaCogs.git
```
Then, install Poetry.

View file

@ -9,14 +9,15 @@ 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
from redbot.core.utils.chat_formatting import bold, 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"
__author__ = ["[cswimr](https://www.coastalcommits.com/cswimr)"]
__git__ = "https://www.coastalcommits.com/cswimr/SeaCogs"
__version__ = "1.0.3"
__documentation__ = "https://seacogs.coastalcommits.com/antipolls/"
def __init__(self, bot: Red):
@ -38,17 +39,17 @@ class AntiPolls(commands.Cog):
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__}",
f"{bold('Cog Version:')} [{self.__version__}]({self.__git__})",
f"{bold('Author:')} {humanize_list(self.__author__)}",
f"{bold('Documentation:')} {self.__documentation__}",
]
return "\n".join(text)
async def red_delete_data_for_user(self, **kwargs): # pylint: disable=unused-argument
async def red_delete_data_for_user(self, **kwargs): # pylint: disable=unused-argument
"""Nothing to delete."""
return
@commands.Cog.listener('on_message')
@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")
@ -61,13 +62,13 @@ class AntiPolls(commands.Cog):
guild_config = await self.config.guild(message.guild).all()
if guild_config['manage_messages'] is True and message.author.guild_permissions.manage_messages:
if guild_config["manage_messages"] is True and message.author.guild_permissions.manage_messages:
return self.logger.verbose("Message from user with Manage Messages permission ignored")
if message.channel.id in guild_config['channel_whitelist']:
if message.channel.id in guild_config["channel_whitelist"]:
return self.logger.verbose("Message in whitelisted channel %s ignored", message.channel.id)
if any(role.id in guild_config['role_whitelist'] for role in message.author.roles):
if any(role.id in guild_config["role_whitelist"] for role in message.author.roles):
return self.logger.verbose("Message from whitelisted role %s ignored", message.author.roles)
if not message.content and not message.embeds and not message.attachments and not message.stickers:
@ -79,9 +80,9 @@ class AntiPolls(commands.Cog):
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)
return self.logger.verbose("Message %s is not a poll, ignoring", message.id)
@commands.group(name="antipolls", aliases=["ap"])
@commands.group(name="antipolls", aliases=["ap"]) # type: ignore
@commands.guild_only()
@commands.admin_or_permissions(manage_guild=True)
async def antipolls(self, ctx: commands.Context) -> None:
@ -94,6 +95,8 @@ class AntiPolls(commands.Cog):
@antipolls_roles.command(name="add")
async def antipolls_roles_add(self, ctx: commands.Context, *roles: discord.Role) -> None:
"""Add roles to the whitelist."""
assert ctx.guild is not None # using `assert` here and in the rest of this file to satisfy typecheckers
# this is safe because the commands are part of a guild-only command group
async with self.config.guild(ctx.guild).role_whitelist() as role_whitelist:
role_whitelist: list
failed: list[discord.Role] = []
@ -109,6 +112,7 @@ class AntiPolls(commands.Cog):
@antipolls_roles.command(name="remove")
async def antipolls_roles_remove(self, ctx: commands.Context, *roles: discord.Role) -> None:
"""Remove roles from the whitelist."""
assert ctx.guild is not None
async with self.config.guild(ctx.guild).role_whitelist() as role_whitelist:
role_whitelist: list
failed: list[discord.Role] = []
@ -122,13 +126,14 @@ class AntiPolls(commands.Cog):
await ctx.send(f"The following roles were not in the whitelist: {humanize_list([role.mention for role in failed])}", delete_after=10)
@antipolls_roles.command(name="list")
async def antipolls_roles_list(self, ctx: commands.Context) -> None:
async def antipolls_roles_list(self, ctx: commands.Context) -> discord.Message:
"""List roles in the whitelist."""
assert ctx.guild is not None
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]))
roles = [role for role in (ctx.guild.get_role(role) for role in role_whitelist) if role is not None]
return await ctx.send(humanize_list([role.mention for role in roles]))
@antipolls.group(name="channels")
async def antipolls_channels(self, ctx: commands.Context) -> None:
@ -137,6 +142,7 @@ class AntiPolls(commands.Cog):
@antipolls_channels.command(name="add")
async def antipolls_channels_add(self, ctx: commands.Context, *channels: discord.TextChannel) -> None:
"""Add channels to the whitelist."""
assert ctx.guild is not None
async with self.config.guild(ctx.guild).channel_whitelist() as channel_whitelist:
channel_whitelist: list
failed: list[discord.TextChannel] = []
@ -152,6 +158,7 @@ class AntiPolls(commands.Cog):
@antipolls_channels.command(name="remove")
async def antipolls_channels_remove(self, ctx: commands.Context, *channels: discord.TextChannel) -> None:
"""Remove channels from the whitelist."""
assert ctx.guild is not None
async with self.config.guild(ctx.guild).channel_whitelist() as channel_whitelist:
channel_whitelist: list
failed: list[discord.TextChannel] = []
@ -165,16 +172,21 @@ class AntiPolls(commands.Cog):
await ctx.send(f"The following channels were not in the whitelist: {humanize_list([channel.mention for channel in failed])}", delete_after=10)
@antipolls_channels.command(name="list")
async def antipolls_channels_list(self, ctx: commands.Context) -> None:
async def antipolls_channels_list(self, ctx: commands.Context) -> discord.Message:
"""List channels in the whitelist."""
assert ctx.guild is not None
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]))
channels = [channel for channel in (ctx.guild.get_channel(channel) for channel in channel_whitelist) if channel is not None]
for c in channels:
if not c:
channels.remove(c)
return 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."""
assert ctx.guild is not None
await self.config.guild(ctx.guild).manage_messages.set(enabled)
await ctx.tick()

View file

@ -1,17 +1,14 @@
{
"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.",
"$schema": "https://raw.githubusercontent.com/Cog-Creators/Red-DiscordBot/refs/heads/V3/develop/schema/red_cog_repo.schema.json",
"author": ["cswimr"],
"install_msg": "Thank you for installing AntiPolls!\nYou can find the source code of this cog [here](https://coastalcommits.com/cswimr/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": true,
"disabled": false,
"min_bot_version": "3.5.0",
"min_python_version": [3, 10, 0],
"tags": [
"automod",
"automoderation",
"polls"
]
"tags": ["automod", "automoderation", "polls"]
}

View file

@ -39,7 +39,7 @@ 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.
This cog stores all of its data in an SQLite database."""
__author__ = ["SeaswimmerTheFsh"]
__author__ = ["cswimr"]
__version__ = "2.1.3"
__documentation__ = "https://seacogs.coastalcommits.com/aurora/"

View file

@ -1,6 +1,6 @@
{
"author" : ["SeaswimmerTheFsh (seasw.)"],
"install_msg" : "Thank you for installing Aurora!\nMost of this cog's functionality requires enabling slash commands.\nYou can find the source code of this cog [here](https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs).",
"author" : ["cswimr"],
"install_msg" : "Thank you for installing Aurora!\nMost of this cog's functionality requires enabling slash commands.\nYou can find the source code of this cog [here](https://coastalcommits.com/cswimr/SeaCogs).",
"name" : "Aurora",
"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.",

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

25
flake.lock generated Normal file
View file

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

72
flake.nix Normal file
View file

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

5
hotreload/__init__.py Normal file
View file

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

191
hotreload/hotreload.py Normal file
View file

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

15
hotreload/info.json Normal file
View file

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

View file

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

View file

@ -1,36 +1,37 @@
site_name: SeaCogs Documentation
site_url: !ENV [SITE_URL, 'https://seacogs.coastalcommits.com']
site_url: !ENV [SITE_URL, "https://seacogs.coastalcommits.com"]
repo_name: CoastalCommits
repo_url: https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs
edit_uri: !ENV [EDIT_URI, 'src/branch/main/.docs']
copyright: Copyright &copy; 2023-2024, SeaswimmerTheFsh
repo_url: https://coastalcommits.com/cswimr/SeaCogs
edit_uri: !ENV [EDIT_URI, "src/branch/main/.docs"]
copyright: Copyright &copy; 2023-2024, cswimr
docs_dir: .docs
site_author: SeaswimmerTheFsh
site_author: cswimr
site_description: Documentation for my Red-DiscordBot Cogs.
nav:
- Home: index.md
- Aurora:
- aurora/index.md
- Moderation Commands: aurora/moderation-commands.md
- Case Commands: aurora/case-commands.md
- Configuration: aurora/configuration.md
- aurora/index.md
- Moderation Commands: aurora/moderation-commands.md
- Case Commands: aurora/case-commands.md
- Configuration: aurora/configuration.md
- Bible: bible.md
- Backup: backup.md
- EmojiInfo: emojiinfo.md
- HotReload: hotreload.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
- 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:
- git-authors
- search
#- social
- social
- git-revision-date-localized:
enable_creation_date: true
type: timeago
@ -72,7 +73,7 @@ markdown_extensions:
theme:
name: material
palette:
- media: '(prefers-color-scheme: light)'
- media: "(prefers-color-scheme: light)"
scheme: default
primary: white
accent: light blue
@ -80,7 +81,7 @@ theme:
icon: material/toggle-switch
name: Switch to dark mode
- media: '(prefers-color-scheme: dark)'
- media: "(prefers-color-scheme: dark)"
scheme: slate
primary: black
accent: light blue
@ -113,3 +114,5 @@ watch:
- ./bible
- ./nerdify
- ./pterodactyl
- ./emojiinfo
- ./antipolls

View file

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

View file

@ -12,13 +12,15 @@ from typing import Any, Optional, Union
import discord
from redbot.core import commands
from redbot.core.utils import chat_formatting, common_filters
from redbot.core.utils.chat_formatting import bold, humanize_list
class Nerdify(commands.Cog):
"""Nerdify your text."""
__author__ = ["SeaswimmerTheFsh"]
__version__ = "1.3.4"
__author__ = ["[cswimr](https://www.coastalcommits.com/cswimr)"]
__git__ = "https://www.coastalcommits.com/cswimr/SeaCogs"
__version__ = "1.3.5"
__documentation__ = "https://seacogs.coastalcommits.com/nerdify/"
def __init__(self, bot):
@ -29,21 +31,26 @@ class Nerdify(commands.Cog):
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__}"
f"{bold('Cog Version:')} [{self.__version__}]({self.__git__})",
f"{bold('Author:')} {humanize_list(self.__author__)}",
f"{bold('Documentation:')} {self.__documentation__}",
]
return "\n".join(text)
@commands.command(aliases=["nerd"])
async def nerdify(
self, ctx: commands.Context, *, text: Optional[str] = None
self,
ctx: commands.Context,
*,
text: Optional[str] = None,
) -> None:
"""Nerdify the replied to message, previous message, or your own text."""
if not text:
if hasattr(ctx.message, "reference") and ctx.message.reference:
with suppress(
discord.Forbidden, discord.NotFound, discord.HTTPException
discord.Forbidden,
discord.NotFound,
discord.HTTPException,
):
message_id = ctx.message.reference.message_id
if message_id:
@ -59,7 +66,9 @@ class Nerdify(commands.Cog):
ctx.channel,
self.nerdify_text(text),
allowed_mentions=discord.AllowedMentions(
everyone=False, users=False, roles=False
everyone=False,
users=False,
roles=False,
),
)
@ -74,7 +83,10 @@ class Nerdify(commands.Cog):
return f'"{text}" 🤓'
async def type_message(
self, destination: discord.abc.Messageable, content: str, **kwargs: Any
self,
destination: discord.abc.Messageable,
content: str,
**kwargs: Any,
) -> Union[discord.Message, None]:
"""Simulate typing and sending a message to a destination.

2574
poetry.lock generated

File diff suppressed because it is too large Load diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

View file

@ -1,19 +1,15 @@
{
"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.",
"$schema": "https://raw.githubusercontent.com/Cog-Creators/Red-DiscordBot/refs/heads/V3/develop/schema/red_cog_repo.schema.json",
"author": ["cswimr"],
"install_msg": "Thank you for installing Pterodactyl!\nYou can find the source code of this cog [here](https://coastalcommits.com/cswimr/SeaCogs).\nDocumentation can be found [here](https://seacogs.coastalcommits.com/pterodactyl ).",
"name": "Pterodactyl",
"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"
]
"requirements": ["git+https://github.com/cswimr/pydactyl", "websockets"],
"tags": ["pterodactyl", "minecraft", "server", "management"]
}

View file

@ -1,8 +1,8 @@
from red_commons import logging
from red_commons.logging import getLogger
logger = getLogger('red.SeaCogs.Pterodactyl')
websocket_logger = getLogger('red.SeaCogs.Pterodactyl.websocket')
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:

View file

@ -3,8 +3,8 @@ 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']:
async with session.get(f"https://api.mcsrvstat.us/2/{host}:{port}") as response:
response = await response.json() # noqa: PLW2901
if response["online"]:
return (True, response)
return (False, response)

View file

@ -1,6 +1,6 @@
import asyncio
import json
from typing import Mapping, Optional, Tuple, Union
from typing import AsyncIterable, Iterable, Mapping, Optional, Tuple, Union
import discord
import websockets
@ -9,8 +9,9 @@ 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.chat_formatting import bold, box, humanize_list
from redbot.core.utils.views import ConfirmView
from typing_extensions import override
from pterodactyl import mcsrvstatus
from pterodactyl.config import config, register_config
@ -20,55 +21,84 @@ 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"
__author__ = ["[cswimr](https://www.coastalcommits.com/cswimr)"]
__git__ = "https://www.coastalcommits.com/cswimr/SeaCogs"
__version__ = "2.0.6"
__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.websocket: Optional[websockets.ClientConnection] = None
self.retry_counter: int = 0
register_config(config)
self.task = self.get_task()
self.task = self._get_task()
self.update_topic.start()
@override
def format_help_for_context(self, ctx: commands.Context) -> str:
pre_processed = super().format_help_for_context(ctx) or ""
n = "\n" if "\n\n" not in pre_processed else ""
text = [
f"{pre_processed}{n}",
f"Cog Version: **{self.__version__}**",
f"Author: {humanize_list(self.__author__)}",
f"Documentation: {self.__documentation__}",
f"{bold('Cog Version:')} [{self.__version__}]({self.__git__})",
f"{bold('Author:')} {humanize_list(self.__author__)}",
f"{bold('Documentation:')} {self.__documentation__}",
]
return "\n".join(text)
@override
async def cog_load(self) -> None:
pterodactyl_keys = await self.bot.get_shared_api_tokens("pterodactyl")
api_key = pterodactyl_keys.get("api_key")
if api_key is None:
self.maybe_cancel_task()
logger.error("Pterodactyl API key not set. Please set it using `[p]set api`.")
return
base_url = await config.base_url()
if base_url is None:
self.maybe_cancel_task()
logger.error("Pterodactyl base URL not set. Please set it using `[p]pterodactyl config url`.")
return
server_id = await config.server_id()
if server_id is None:
self.maybe_cancel_task()
logger.error("Pterodactyl server ID not set. Please set it using `[p]pterodactyl config serverid`.")
return
self.client = PterodactylClient(base_url, api_key).client
@override
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
self.maybe_cancel_task()
def get_task(self) -> asyncio.Task:
def maybe_cancel_task(self, reset_retry_counter: bool = True) -> None:
if self.task:
self.task.cancel()
if reset_retry_counter:
self.retry_counter = 0
def _get_task(self) -> asyncio.Task:
from pterodactyl.websocket import establish_websocket_connection
task = self.bot.loop.create_task(establish_websocket_connection(self), name="Pterodactyl Websocket Connection")
task.add_done_callback(self.error_callback)
task.add_done_callback(self._error_callback)
return task
def error_callback(self, fut) -> None: #NOTE - Thanks flame442 and zephyrkul for helping me figure this out
def _error_callback(self, fut) -> None: # NOTE Thanks flame442 and zephyrkul for helping me figure this out
try:
fut.result()
except asyncio.CancelledError:
logger.info("WebSocket task has been cancelled.")
except Exception as e: # pylint: disable=broad-exception-caught
except Exception as e: # pylint: disable=broad-exception-caught
logger.error("WebSocket task has failed: %s", e, exc_info=e)
self.task.cancel()
self.maybe_cancel_task(reset_retry_counter=False)
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)
self.task = self.bot.loop.call_later(5 * self.retry_counter, self._get_task)
else:
logger.info("Retry limit reached. Stopping task.")
@ -79,9 +109,9 @@ class Pterodactyl(commands.Cog):
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)
await console.edit(topic=topic) # type: ignore
if chat:
await chat.edit(topic=topic)
await chat.edit(topic=topic) # type: ignore
@commands.Cog.listener()
async def on_message_without_command(self, message: discord.Message) -> None:
@ -92,13 +122,7 @@ class Pterodactyl(commands.Cog):
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()
await self._send(json.dumps({"event": "send command", "args": [message.content]}))
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())
@ -106,13 +130,22 @@ class Pterodactyl(commands.Cog):
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)
await self._send(message=msg)
async def _send(self, message: Union[websockets.Data, Iterable[websockets.Data], AsyncIterable[websockets.Data]], text: bool = False):
"""Send a message through the websocket connection. Restarts the websocket connection task if it is closed, and reinvokes itself."""
try:
await self.websocket.send(message=message, text=text) # type: ignore - we want this to error if `self.websocket` is none
except websockets.exceptions.ConnectionClosed as e:
logger.error("WebSocket connection closed: %s", e)
self.maybe_cancel_task()
self.task = self._get_task()
try:
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()
await asyncio.wait_for(fut=self.task, timeout=60)
await self._send(message=message, text=text)
except asyncio.TimeoutError:
logger.error("Timeout while waiting for websocket connection")
raise
async def get_topic(self) -> str:
topic: str = await config.topic()
@ -123,23 +156,27 @@ class Pterodactyl(commands.Cog):
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",
})
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",
})
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)
topic = topic.replace(".$" + key, value)
return topic
async def get_chat_command(self, message: discord.Message) -> str:
@ -148,115 +185,82 @@ class Pterodactyl(commands.Cog):
"C": str(message.author.color),
"D": message.author.discriminator,
"I": str(message.author.id),
"M": message.content.replace('"','').replace("\n", " "),
"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)
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']
if status and "list" in response["players"]:
output_str = "\n".join(response["players"]["list"])
return output_str, response["players"]["list"]
return None
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:
if player_list and isinstance(ctx.channel, discord.abc.Messageable):
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:
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
ctx = await self.bot.get_context(ctx)
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}.")
await ctx.send(f"Server is already {action_ing}.", ephemeral=True)
return
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.")
await ctx.send("Another power action is already in progress.", ephemeral=True)
return
view = ConfirmView(author, disable_buttons=True)
view = ConfirmView(ctx.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)
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 message.edit(content=f"Sending websocket command to {action} server...", view=None)
await self.websocket.send(json.dumps({"event": "set state", "args": [action]}))
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)
await message.edit(content=f"Server {action_ing}", view=None)
return
else:
if isinstance(ctx, discord.Interaction):
await ctx.edit_original_response(content="Cancelled.", view=None)
else:
await message.edit(content="Cancelled.", view=None)
await message.edit(content="Cancelled.", view=None)
return
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()
ctx = await self.bot.get_context(ctx)
if channel:
await channel.send(f"Received console command from {ctx.author.id}: {command[:1900]}", allowed_mentions=discord.AllowedMentions.none())
await self._websocket_send(json.dumps({"event": "send command", "args": [command]}))
await ctx.send(f"Command sent to server. {box(command, 'json')}")
@commands.Cog.listener()
async def on_red_api_tokens_update(self, service_name: str, api_tokens: Mapping[str,str]): # pylint: disable=unused-argument
async def on_red_api_tokens_update(self, service_name: str, api_tokens: Mapping[str, str]): # pylint: disable=unused-argument
if service_name == "pterodactyl":
logger.info("Configuration value set: api_key\nRestarting task...")
self.task.cancel()
self.retry_counter = 0
self.task = self.get_task()
self.maybe_cancel_task(reset_retry_counter=True)
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.")
@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.
@ -266,7 +270,7 @@ class Pterodactyl(commands.Cog):
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.")
@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)
@ -275,13 +279,8 @@ class Pterodactyl(commands.Cog):
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")
])
@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.
@ -295,11 +294,11 @@ class Pterodactyl(commands.Cog):
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"])
@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"])
@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)
@ -308,43 +307,43 @@ class Pterodactyl(commands.Cog):
else:
await ctx.send("No players online.")
@pterodactyl.command(name = "command", aliases = ["cmd", "execute", "exec"])
@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")
@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")
@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")
@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")
@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")
@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"])
@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")
@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.
@ -353,59 +352,57 @@ class Pterodactyl(commands.Cog):
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()
self.maybe_cancel_task(reset_retry_counter=True)
self.task = self._get_task()
@pterodactyl_config.command(name = "serverid")
@pterodactyl_config.command(name="serverid")
async def pterodactyl_config_server_id(self, ctx: commands.Context, *, server_id: str) -> None:
"""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()
self.maybe_cancel_task(reset_retry_counter=True)
self.task = self._get_task()
@pterodactyl_config.group(name = "console")
@pterodactyl_config.group(name="console")
async def pterodactyl_config_console(self, ctx: commands.Context):
"""Configure console settings."""
@pterodactyl_config_console.command(name = "channel")
@pterodactyl_config_console.command(name="channel")
async def pterodactyl_config_console_channel(self, ctx: commands.Context, channel: discord.TextChannel) -> None:
"""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")
@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")
@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")
@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"])
@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")
@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")
@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.
@ -421,17 +418,17 @@ class Pterodactyl(commands.Cog):
await config.topic.set(text)
await ctx.send(f"Topic set to:\n{box(text, 'yaml')}")
@pterodactyl_config.group(name = "chat")
@pterodactyl_config.group(name="chat")
async def pterodactyl_config_chat(self, ctx: commands.Context):
"""Configure chat settings."""
@pterodactyl_config_chat.command(name = "channel")
@pterodactyl_config_chat.command(name="channel")
async def pterodactyl_config_chat_channel(self, ctx: commands.Context, channel: discord.TextChannel) -> None:
"""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")
@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.
@ -440,11 +437,11 @@ class Pterodactyl(commands.Cog):
await config.chat_command.set(command)
await ctx.send(f"Chat command set to:\n{box(command, 'json')}")
@pterodactyl_config.group(name = "regex")
@pterodactyl_config.group(name="regex")
async def pterodactyl_config_regex(self, ctx: commands.Context) -> None:
"""Set regex patterns."""
@pterodactyl_config_regex.command(name = "chat")
@pterodactyl_config_regex.command(name="chat")
async def pterodactyl_config_regex_chat(self, ctx: commands.Context, *, regex: str) -> None:
"""Set the regex pattern to match chat messages on the server.
@ -452,7 +449,7 @@ class Pterodactyl(commands.Cog):
await config.chat_regex.set(regex)
await ctx.send(f"Chat regex set to:\n{box(regex, 'regex')}")
@pterodactyl_config_regex.command(name = "server")
@pterodactyl_config_regex.command(name="server")
async def pterodactyl_config_regex_server(self, ctx: commands.Context, *, regex: str) -> None:
"""Set the regex pattern to match server messages on the server.
@ -460,7 +457,7 @@ class Pterodactyl(commands.Cog):
await config.server_regex.set(regex)
await ctx.send(f"Server regex set to:\n{box(regex, 'regex')}")
@pterodactyl_config_regex.command(name = "join")
@pterodactyl_config_regex.command(name="join")
async def pterodactyl_config_regex_join(self, ctx: commands.Context, *, regex: str) -> None:
"""Set the regex pattern to match join messages on the server.
@ -468,7 +465,7 @@ class Pterodactyl(commands.Cog):
await config.join_regex.set(regex)
await ctx.send(f"Join regex set to:\n{box(regex, 'regex')}")
@pterodactyl_config_regex.command(name = "leave")
@pterodactyl_config_regex.command(name="leave")
async def pterodactyl_config_regex_leave(self, ctx: commands.Context, *, regex: str) -> None:
"""Set the regex pattern to match leave messages on the server.
@ -476,7 +473,7 @@ class Pterodactyl(commands.Cog):
await config.leave_regex.set(regex)
await ctx.send(f"Leave regex set to:\n{box(regex, 'regex')}")
@pterodactyl_config_regex.command(name = "achievement")
@pterodactyl_config_regex.command(name="achievement")
async def pterodactyl_config_regex_achievement(self, ctx: commands.Context, *, regex: str) -> None:
"""Set the regex pattern to match achievement messages on the server.
@ -484,41 +481,41 @@ class Pterodactyl(commands.Cog):
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'])
@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")
@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")
@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")
@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")
@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")
@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")
@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.
@ -527,11 +524,14 @@ class Pterodactyl(commands.Cog):
await config.api_endpoint.set(endpoint)
await ctx.send(f"API endpoint set to {endpoint}")
@pterodactyl_config_regex.group(name = "blacklist", aliases = ['block', 'blocklist'],)
@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")
@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:
@ -549,7 +549,7 @@ class Pterodactyl(commands.Cog):
else:
await msg.edit(content="Cancelled.")
@pterodactyl_config_regex_blacklist.command(name = "remove")
@pterodactyl_config_regex_blacklist.command(name="remove")
async def pterodactyl_config_regex_blacklist_remove(self, ctx: commands.Context, name: str) -> None:
"""Remove a regex pattern from the blacklist."""
async with config.regex_blacklist() as blacklist:
@ -566,7 +566,7 @@ class Pterodactyl(commands.Cog):
else:
await ctx.send(f"Name `{name}` does not exist in the blacklist.")
@pterodactyl_config.command(name = 'view', aliases = ['show'])
@pterodactyl_config.command(name="view", aliases=["show"])
async def pterodactyl_config_view(self, ctx: commands.Context) -> None:
"""View the current configuration."""
base_url = await config.base_url()
@ -591,7 +591,7 @@ class Pterodactyl(commands.Cog):
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 = 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}>
@ -607,19 +607,19 @@ class Pterodactyl(commands.Cog):
**Topic Hostname:** `{topic_hostname}`
**Topic Port:** `{topic_port}`
**Topic Text:** {box(topic_text, 'yaml')}
**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')}"""
**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")
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)
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:

View file

@ -1,13 +1,15 @@
# pylint: disable=cyclic-import
import json
import re
from typing import Optional, Union
from pathlib import Path
from typing import Any, Optional, Tuple, Union
import aiohttp
import discord
import websockets
from pydactyl import PterodactylClient
from redbot.core.data_manager import bundled_data_path
from redbot.core.utils.chat_formatting import bold, pagify
from websockets.asyncio.client import connect
from pterodactyl.config import config
from pterodactyl.logger import logger, websocket_logger
@ -17,46 +19,48 @@ 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
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:
async with 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']]})
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
while True: # pylint: disable=too-many-nested-blocks
message = json.loads(await websocket.recv())
if message['event'] in ('token expiring', 'token expired'):
if message["event"] in ("token expiring", "token expired"):
logger.info("Received token expiring/expired event. Refreshing token.")
websocket_credentials = await retrieve_websocket_credentials(coginstance)
auth_message = json.dumps({"event": "auth", "args": [websocket_credentials['data']['token']]})
auth_message = json.dumps({"event": "auth", "args": [websocket_credentials["data"]["token"]]})
await websocket.send(auth_message)
logger.info("Authentication message sent")
if message['event'] == 'auth success':
if message["event"] == "auth success":
logger.info("WebSocket authentication successful")
if message['event'] == 'console output' and await config.console_channel() is not None:
if message["event"] == "console output" and await config.console_channel() is not None:
regex_blacklist: dict = await config.regex_blacklist()
matches = [re.search(regex, message['args'][0]) for regex in regex_blacklist.values()]
matches = [re.search(regex, message["args"][0]) for regex in regex_blacklist.values()]
if await config.current_status() in ('running', '') and not any(matches):
content = remove_ansi_escape_codes(message['args'][0])
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())
assert isinstance(console_channel, discord.abc.Messageable)
chat_channel = coginstance.bot.get_channel(await config.chat_channel())
assert isinstance(chat_channel, discord.abc.Messageable)
if console_channel is not None:
if content.startswith('['):
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())
@ -64,21 +68,26 @@ async def establish_websocket_connection(coginstance: Pterodactyl) -> 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())
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'])
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'])
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')
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))
embed, img = await generate_join_leave_embed(coginstance=coginstance, username=join_message, join=True)
if img:
with open(img, "rb") as file:
await chat_channel.send(embed=embed, file=discord.File(fp=file))
else:
await chat_channel.send(embed=embed)
else:
await chat_channel.send(f"{join_message} joined the game", allowed_mentions=discord.AllowedMentions.none())
@ -86,7 +95,12 @@ async def establish_websocket_connection(coginstance: Pterodactyl) -> None:
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))
embed, img = await generate_join_leave_embed(coginstance=coginstance, username=leave_message, join=False)
if img:
with open(img, "rb") as file:
await chat_channel.send(embed=embed, file=discord.File(fp=file))
else:
await chat_channel.send(embed=embed)
else:
await chat_channel.send(f"{leave_message} left the game", allowed_mentions=discord.AllowedMentions.none())
@ -94,13 +108,17 @@ async def establish_websocket_connection(coginstance: Pterodactyl) -> None:
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']))
embed, img = await generate_achievement_embed(coginstance, achievement_message["username"], achievement_message["achievement"], achievement_message["challenge"])
if img:
await chat_channel.send(embed=embed, file=discord.File(fp=img))
else:
await chat_channel.send(embed=embed)
else:
await chat_channel.send(f"{achievement_message['username']} has {'completed the challenge' if achievement_message['challenge'] else 'made the advancement'} {achievement_message['achievement']}")
if message['event'] == 'status':
if message["event"] == "status":
old_status = await config.current_status()
current_status = message['args'][0]
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:
@ -108,81 +126,92 @@ async def establish_websocket_connection(coginstance: Pterodactyl) -> None:
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:
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:
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]:
async def retrieve_websocket_credentials(coginstance: Pterodactyl) -> 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()
coginstance.maybe_cancel_task()
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()
coginstance.maybe_cancel_task()
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()
coginstance.maybe_cancel_task()
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:
websocket_credentials: dict[str, Any] = client.servers.get_websocket(server_id).json()
if not websocket_credentials:
coginstance.maybe_cancel_task()
raise ValueError("Failed to retrieve websocket credentials. Please ensure the API details are correctly configured.")
logger.debug(
"""Websocket connection details retrieved:
Socket: %s
Token: %s...""",
websocket_credentials['data']['socket'],
websocket_credentials['data']['token'][:20]
)
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
# 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)
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]:
async def check_if_server_message(text: str) -> Optional[str]:
regex = await config.server_regex()
match: Optional[re.Match[str]] = re.match(regex, text)
if match:
logger.debug("Message is a server message")
logger.trace("Message is a server message")
return match.group(1)
return False
return None
async def check_if_chat_message(text: str) -> Union[bool, dict]:
async def check_if_chat_message(text: str) -> Optional[dict]:
regex = await config.chat_regex()
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))
logger.trace("Message is a chat message\n%s", json.dumps(groups))
return groups
return False
return None
async def check_if_join_message(text: str) -> Union[bool, str]:
async def check_if_join_message(text: str) -> Optional[str]:
regex = await config.join_regex()
match: Optional[re.Match[str]] = re.match(regex, text)
if match:
logger.debug("Message is a join message")
logger.trace("Message is a join message")
return match.group(1)
return False
return None
async def check_if_leave_message(text: str) -> Union[bool, str]:
async def check_if_leave_message(text: str) -> Optional[str]:
regex = await config.leave_regex()
match: Optional[re.Match[str]] = re.match(regex, text)
if match:
logger.debug("Message is a leave message")
logger.trace("Message is a leave message")
return match.group(1)
return False
return None
async def check_if_achievement_message(text: str) -> Union[bool, dict]:
async def check_if_achievement_message(text: str) -> Optional[dict]:
regex = await config.achievement_regex()
match: Optional[re.Match[str]] = re.match(regex, text)
if match:
@ -191,23 +220,25 @@ async def check_if_achievement_message(text: str) -> Union[bool, dict]:
groups["challenge"] = True
else:
groups["challenge"] = False
logger.debug("Message is an achievement message")
logger.trace("Message is an achievement message")
return groups
return False
return None
async def get_info(username: str) -> Optional[dict]:
logger.debug("Retrieving player info for %s", username)
logger.verbose("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)
logger.verbose("Player info retrieved for %s", username)
return await response.json()
logger.error("Failed to retrieve player info for %s: %s", username, response.status)
logger.warning("Failed to retrieve player info for %s: %s", username, response.status)
return None
async def send_chat_discord(coginstance: Pterodactyl, username: str, message: str, avatar_url: str) -> None:
logger.debug("Sending chat message to Discord")
logger.trace("Sending chat message to Discord")
channel = coginstance.bot.get_channel(await config.chat_channel())
if channel is not None:
webhooks = await channel.webhooks()
@ -215,37 +246,44 @@ async def send_chat_discord(coginstance: Pterodactyl, username: str, message: st
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")
logger.trace("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:
async def generate_join_leave_embed(coginstance: Pterodactyl, username: str, join: bool) -> Tuple[discord.Embed, Optional[Union[str, Path]]]:
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'])
img = None
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')
img = bundled_data_path(coginstance) / "unknown.png"
embed.set_author(name=username, icon_url="attachment://unknown.png")
embed.timestamp = discord.utils.utcnow()
return embed
return embed, img
async def generate_achievement_embed(username: str, achievement: str, challenge: bool) -> discord.Embed:
async def generate_achievement_embed(coginstance: Pterodactyl, username: str, achievement: str, challenge: bool) -> Tuple[discord.Embed, Optional[Union[str, Path]]]:
embed = discord.Embed()
embed.color = discord.Color.from_str('#a800a7') if challenge else discord.Color.from_str('#54fb54')
embed.color = discord.Color.from_str("#a800a7") if challenge else discord.Color.from_str("#54fb54")
embed.description = f"{bold(username)} has {'completed the challenge' if challenge else 'made the advancement'} {bold(achievement)}"
info = await get_info(username)
if info:
embed.set_author(name=username, icon_url=info['data']['player']['avatar'])
img = None
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')
img = bundled_data_path(coginstance) / "unknown.png"
embed.set_author(name=username, icon_url="attachment://unknown.png")
embed.timestamp = discord.utils.utcnow()
return embed
return embed, img
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)
return ".".join(r"\*" * len(octet) for octet in ip.split("."))
return re.sub(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", check, string)

View file

@ -1,75 +1,76 @@
[tool.poetry]
[project]
name = "seacogs"
version = "0.1.0"
description = "My assorted cogs for Red-DiscordBot."
authors = ["SeaswimmerTheFsh"]
license = "MPL 2"
authors = [{ name = "cswimr", email = "seaswimmerthefsh@gmail.com" }]
license = { file = "LICENSE" }
readme = "README.md"
package-mode = false
requires-python = ">=3.11"
dependencies = [
"aiosqlite>=0.20.0",
"beautifulsoup4>=4.12.3",
"colorthief>=0.2.1",
"markdownify>=0.14.1",
"numpy>=2.2.2",
"phx-class-registry>=5.1.1",
"pillow>=10.4.0",
"pip>=25.0",
"py-dactyl",
"pydantic>=2.10.6",
"red-discordbot>=3.5.14",
"watchdog>=6.0.0",
"websockets>=14.2",
]
[tool.poetry.dependencies]
python = ">=3.11,<3.12"
Red-DiscordBot = "^3.5.5"
py-dactyl = "^2.0.4"
websockets = "^12.0"
pillow = "^10.3.0"
numpy = "^1.26.4"
colorthief = "^0.2.1"
beautifulsoup4 = "^4.12.3"
markdownify = "^0.12.1"
[dependency-groups]
documentation = [
"mkdocs>=1.6.1",
"mkdocs-git-authors-plugin>=0.9.2",
"mkdocs-git-revision-date-localized-plugin>=1.3.0",
"mkdocs-material[imaging]>=9.5.50",
"mkdocs-redirects>=1.2.2",
"mkdocstrings[python]>=0.27.0",
]
[tool.poetry.group.dev]
optional = true
[tool.uv]
dev-dependencies = ["pylint>=3.3.3", "ruff>=0.9.3", "sqlite-web>=0.6.4"]
[tool.poetry.group.dev.dependencies]
ruff = "^0.3.1"
pylint = "^3.1.0"
sqlite-web = "^0.6.4"
[tool.uv.sources]
py-dactyl = { git = "https://github.com/cswimr/pydactyl" }
[tool.poetry.group.docs]
optional = true
[tool.poetry.group.docs.dependencies]
mkdocs = "1.5.3"
mkdocstrings = {extras = ["python"], version = "0.24.0"}
mkdocs-git-authors-plugin = "0.7.2"
mkdocs-git-revision-date-localized-plugin = "1.2.2"
mkdocs-material = {extras = ["imaging"], version = "^9.5.2"}
mkdocs-redirects = "^1.2.1"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
[tool.basedpyright]
typeCheckingMode = "basic"
reportAttributeAccessIssue = false # disabled because `commands.group.command` is listed as Any / Unknown for some reason
[tool.ruff]
# Exclude a variety of commonly ignored directories.
exclude = [
".bzr",
".direnv",
".eggs",
".git",
".git-rewrite",
".hg",
".ipynb_checkpoints",
".mypy_cache",
".nox",
".pants.d",
".pyenv",
".pytest_cache",
".pytype",
".ruff_cache",
".svn",
".tox",
".venv",
".vscode",
"__pypackages__",
"_build",
"buck-out",
"build",
"dist",
"node_modules",
"site-packages",
"venv",
".bzr",
".direnv",
".eggs",
".git",
".git-rewrite",
".hg",
".ipynb_checkpoints",
".mypy_cache",
".nox",
".pants.d",
".pyenv",
".pytest_cache",
".pytype",
".ruff_cache",
".svn",
".tox",
".venv",
".vscode",
"__pypackages__",
"_build",
"buck-out",
"build",
"dist",
"node_modules",
"site-packages",
"venv",
]
# Same as Black.
@ -83,8 +84,32 @@ target-version = "py311"
# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
# Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or
# McCabe complexity (`C901`) by default.
select = ["F", "W", "E", "C901"]
ignore = ["C901"]
select = [
"I",
"N",
"F",
"W",
"E",
"G",
"A",
"COM",
"INP",
"T20",
"PLC",
"PLE",
"PLW",
"PLR",
"LOG",
"SLF",
"ERA",
"FIX",
"PERF",
"C4",
"EM",
"RET",
"RSE",
]
ignore = ["PLR0911", "PLR0912", "PLR0915", "PLR2004", "PLR0913", "EM101"]
# Allow fix for all enabled rules (when `--fix`) is provided.
fixable = ["ALL"]

5
renovate.json Normal file
View file

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

View file

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

View file

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

1988
uv.lock generated Normal file

File diff suppressed because it is too large Load diff