Compare commits
626 commits
Author | SHA1 | Date | |
---|---|---|---|
8d8fd0c04f | |||
d0474a3707 | |||
d17a7e645f | |||
aaf9ac1b4e | |||
dbe6fc2390 | |||
b67b692201 | |||
15715dff3c | |||
73b0e73ff0 | |||
d9c123d441 | |||
4f38fc1f7d | |||
602d759e67 | |||
3da2d74a48 | |||
4344d26096 | |||
285257eed5 | |||
2b7f320d2a | |||
df970717c2 | |||
97b54b507b | |||
06e011f670 | |||
0955282325 | |||
19fc6adaad | |||
7ca836759f | |||
833d6954cc | |||
b9e06d6288 | |||
f28a8aad0e | |||
a9c2f18b5d | |||
f0bc915da8 | |||
46b7123fdd | |||
04c3b0e83c | |||
33ce8a147c | |||
01b249fbb3 | |||
f572a0d535 | |||
9f7244cd65 | |||
a4f2d21fa1 | |||
ba25078f3f | |||
3066848853 | |||
0ed7ab6727 | |||
f713780d49 | |||
5adaca755d | |||
09d7f634f2 | |||
069621eee8 | |||
76da85365c | |||
1edb08a127 | |||
43464db6a7 | |||
50d1d7900b | |||
6ec79c9f92 | |||
9f6e960a25 | |||
46b534ebf8 | |||
74f58162de | |||
39808f1766 | |||
014025f547 | |||
9b0a11a7bc | |||
6ab593390c | |||
7c16ec8df8 | |||
cbd9f28f38 | |||
c546fa597b | |||
7b859e07e9 | |||
5f4cb88ea8 | |||
4135cd4f98 | |||
d6bccf20e9 | |||
7a75266b01 | |||
25b26322d2 | |||
|
40b846123f | ||
4c603eea46 | |||
92e8ee2dc2 | |||
99dddf2fa7 | |||
ba7a5f9208 | |||
ddb9f30d6f | |||
3b5932bac9 | |||
f4efcb8ea5 | |||
6035aea5c6 | |||
03c14a0311 | |||
56522e51ad | |||
9eff010b35 | |||
c0195f44f6 | |||
fdb785ffd7 | |||
178a92559c | |||
ae31a61436 | |||
9e826d6ba5 | |||
b5362ff153 | |||
2e5fa81eac | |||
c65fdd698c | |||
497f6a0a1a | |||
f059145681 | |||
41a8d575d4 | |||
dd62b7d7ce | |||
bbb54f0f55 | |||
f033f6a483 | |||
1bb7e22b95 | |||
f707b70097 | |||
64ab2fbf82 | |||
9d64c15a87 | |||
8c58e1746e | |||
52be531807 | |||
80cb729e72 | |||
df92bc34cc | |||
b2f27f9490 | |||
093a6b9077 | |||
8639615c49 | |||
dec154fb4c | |||
aaba9ebd59 | |||
75adf692c1 | |||
85d5316f43 | |||
13dba790b7 | |||
d01985eea6 | |||
0baad46298 | |||
3d3c5f708e | |||
34c34e745a | |||
87dfc03812 | |||
eecf1fb70f | |||
9b153a4799 | |||
0496454030 | |||
e2389cec08 | |||
58e88f2dd6 | |||
9106675276 | |||
72d8ff4782 | |||
9e92d82817 | |||
1ad721f380 | |||
088bf6b8dc | |||
bf3f0f9782 | |||
e6231bf1a7 | |||
4020ab7847 | |||
f6ebbae583 | |||
5c2bfea238 | |||
a52a991ae6 | |||
6e2776b63a | |||
4c7526b157 | |||
6cdab8363a | |||
464483b4c9 | |||
3d7337c42c | |||
8ccb174913 | |||
3e18894bb5 | |||
1263f59cee | |||
385c94c97e | |||
a7a42be4ed | |||
1f51cb2a27 | |||
eb5fdfa84e | |||
030291113b | |||
7e4d4b348a | |||
4c234502f7 | |||
26e5bd9129 | |||
8fdf9eb239 | |||
3a52efeac0 | |||
882b0386f2 | |||
45797361a6 | |||
12862ccea7 | |||
0b0afa53d6 | |||
9e8bcb952a | |||
0882a498b6 | |||
d1966fb05f | |||
987a29afff | |||
f93223fd36 | |||
306148ea69 | |||
fb177ff8ad | |||
e9523d5f70 | |||
6a02381e89 | |||
b75bacb811 | |||
88c77b4aa5 | |||
af29b950c2 | |||
95bf863f7e | |||
dab56bed94 | |||
4979e44b7c | |||
1bc1c7a90e | |||
a166168507 | |||
8b50c0376d | |||
a0b1773185 | |||
b6819192b0 | |||
b775439967 | |||
f2d54ce23b | |||
b7f5ae644a | |||
684f2559e2 | |||
a1a33ebfca | |||
8b1e42716b | |||
837bf4aa34 | |||
1bbabd495f | |||
8cbad26e1d | |||
6f4f13e623 | |||
b18b99075e | |||
3795d7d13a | |||
dd6184ccd0 | |||
afc5868e9e | |||
7e03696e10 | |||
8954df4c1d | |||
f2c56e0382 | |||
bd7aa54efe | |||
f91cd82d1b | |||
2fbd8cde9e | |||
7a39c9a75d | |||
d39f0ba104 | |||
a4f68d55eb | |||
8387064ab4 | |||
9e63b4e798 | |||
0d21a52ce3 | |||
457f1da7f4 | |||
c0289a86fc | |||
7f8d70ccae | |||
2bf8629e4c | |||
e1c98aa78f | |||
417f297193 | |||
37cdca09ec | |||
84b0201662 | |||
839ead56eb | |||
9e15730af9 | |||
de5d0194c8 | |||
ef7f574306 | |||
07835e7b13 | |||
cccc941e26 | |||
0aa17e8807 | |||
366bafcd27 | |||
d5600e8cf7 | |||
97213a5025 | |||
2e4b664760 | |||
925e402819 | |||
502ffbee84 | |||
f87f4ee37f | |||
50dd5c64b4 | |||
579855af02 | |||
2fb201a9cb | |||
236cb1d815 | |||
f588caf25f | |||
4108bb22bb | |||
76aa99c3f9 | |||
f792ad58a0 | |||
5a4dc4866c | |||
d3cc445802 | |||
4174bc4be7 | |||
d00b70758a | |||
b0a110e4f8 | |||
9023ea160b | |||
0e638ca9e3 | |||
5dc55b52e7 | |||
4f95955a04 | |||
510f8c788e | |||
a791c27fc3 | |||
07e2497aac | |||
e12ded9d42 | |||
ee6e900e7d | |||
f42c536f7c | |||
7e728087c4 | |||
9a698fbac6 | |||
dab7343ca6 | |||
239f7cf613 | |||
39ae8b5ea0 | |||
142336e233 | |||
f6f0a31763 | |||
ec2cd09f8e | |||
c740cdc6dc | |||
a8f60b1aec | |||
d297a2181d | |||
60f94c4499 | |||
ccbce180dd | |||
2017cbb226 | |||
caa03a63e6 | |||
b7635f06f5 | |||
ff93fd8527 | |||
3d8f479347 | |||
0961985168 | |||
cebc2223d9 | |||
d9f5d14f40 | |||
7b83513d63 | |||
48634ac903 | |||
2312cce011 | |||
09d48082e5 | |||
08cd13d7c7 | |||
d391aeeb7b | |||
e6ca4071f3 | |||
6738ab17ca | |||
fbb31dc0d4 | |||
8a22d5ce23 | |||
f485df856c | |||
95a947b019 | |||
84543fbd73 | |||
92b031c54e | |||
bd3a08fe97 | |||
98396c17e2 | |||
be27d882f2 | |||
d092f78502 | |||
d92831f3db | |||
2d4e372784 | |||
5e3ab08d6d | |||
f377dc9250 | |||
680f92572c | |||
ea84044e73 | |||
53adeb4b80 | |||
9d4d8b8267 | |||
6e6559d80c | |||
dcf0165a8a | |||
6158d05960 | |||
57c7bce6cd | |||
5d1f8818eb | |||
858a1bae8a | |||
e34d621e6d | |||
dd9e221e2d | |||
5aff4afad1 | |||
9c293750cb | |||
516e4539e8 | |||
eafd02bb53 | |||
1aa12e88ac | |||
69482c9f45 | |||
35ad7a77a7 | |||
f7d2f1a564 | |||
db7c06b044 | |||
afb961799d | |||
3506274a2a | |||
09ce2c7d73 | |||
21d5266bb6 | |||
660b2ddb10 | |||
e57e0d53ce | |||
c7fb47ad2f | |||
f615e9f61d | |||
ad2cf39e3e | |||
0ccad57476 | |||
067ded28f3 | |||
cf5e146f88 | |||
3dce020a65 | |||
3813d3de02 | |||
6be92f05db | |||
ba5b128afc | |||
7d2b71667a | |||
21dabccb48 | |||
c1d2e6d28a | |||
5b18b6612a | |||
4d321006c8 | |||
d1afd62114 | |||
efe16cefac | |||
4ca9760284 | |||
c9c2e1f955 | |||
a83a63dd6a | |||
018eb5ed28 | |||
6d8e139b19 | |||
eb9d744a3f | |||
fa3b353704 | |||
519e3056ab | |||
323b4808cb | |||
fda80d4e41 | |||
09302403b8 | |||
21e256c4fb | |||
2c14be64ea | |||
d1c0ed2e14 | |||
e6b72e80ee | |||
b86707a6b4 | |||
08b3553c2c | |||
09e91da62f | |||
83edd36d6b | |||
7597dcf5f7 | |||
acc883af20 | |||
e71fc9f154 | |||
0980c7cbf2 | |||
d24d8f9603 | |||
220e8da790 | |||
5d68f91169 | |||
6f04290cba | |||
4dfbc91ced | |||
f3db29beef | |||
fb2e607af1 | |||
88aad510b9 | |||
ad7616bef6 | |||
8883f68cf0 | |||
a25a1e73ba | |||
633c9022bb | |||
13e7bb81dd | |||
337d873ad5 | |||
f8770ef5fe | |||
a4b23d38e9 | |||
4bf439c5c7 | |||
bd093ca311 | |||
2841fb12a5 | |||
6df92da12f | |||
c37a58d687 | |||
44179ad42d | |||
ad0cd41be4 | |||
8da6f0d8de | |||
4a4ffcd1ee | |||
feac213017 | |||
9e2697b08b | |||
005d0c1c8b | |||
e1746281c8 | |||
aa745cc03f | |||
3b28ba3277 | |||
0a07e2dfa8 | |||
46685eee82 | |||
52a440ff3e | |||
95cd7fdcb5 | |||
2f945af866 | |||
b9fba23415 | |||
bb53343ecc | |||
8941aabf81 | |||
7f2555218c | |||
5652e13ad7 | |||
1c8037274b | |||
162d669502 | |||
89bdf5583c | |||
a432050056 | |||
9e8c5239fd | |||
c196cca6c2 | |||
bf700f138c | |||
ad32a0fa67 | |||
660f561109 | |||
894b1a3714 | |||
a14ec9bceb | |||
3e824bca91 | |||
267e048bc0 | |||
4c98d00641 | |||
39fafede67 | |||
3398100a0f | |||
960ec4c83a | |||
f21526573f | |||
71d99babe5 | |||
71b900fa08 | |||
053b5b7472 | |||
49907e7803 | |||
22237a21b1 | |||
4e70145d38 | |||
f57b2c5196 | |||
7766b94a9e | |||
a00bfc3f93 | |||
756265503c | |||
9b930fc05b | |||
f33ebd29e9 | |||
57c129c9ce | |||
acf89e090f | |||
8327270e61 | |||
760059f8f0 | |||
f4f174ce81 | |||
417ee9bde4 | |||
6dfeb97180 | |||
fdb5d323eb | |||
add1e3ef1d | |||
bbecff3ed0 | |||
fa6fcfb75f | |||
d7b5c5f239 | |||
3662ce3b23 | |||
7fdb106fad | |||
ac761d9284 | |||
037ef84dcc | |||
c07c7317f4 | |||
c2aa674bff | |||
168f62d43f | |||
5eb762d9fe | |||
2dd8663e78 | |||
702de21448 | |||
52f8439383 | |||
d0375c3bdb | |||
26b085231b | |||
045d51bc23 | |||
35ffec9c3f | |||
932c9f61ed | |||
6fbfa96cf2 | |||
7fa6cd5922 | |||
abc9927dea | |||
fa7faec4c2 | |||
818e974318 | |||
e1fbe66da2 | |||
8357d4d498 | |||
e069da1cc4 | |||
712484986c | |||
860eccb52a | |||
5da523d0c4 | |||
b9ca8d32d3 | |||
eb79025d2a | |||
226a36884a | |||
7f9e804a70 | |||
657cac904b | |||
8cee869907 | |||
5b601da46b | |||
a7d8a20c57 | |||
950d4abf6a | |||
46a290aad3 | |||
3b8506cba8 | |||
fc86db94da | |||
78a5103b1f | |||
3d4b6800a5 | |||
4db7c912cb | |||
4d8aa465b1 | |||
fecde10b1c | |||
2037f385d1 | |||
a4a0ec924a | |||
630381328b | |||
7476fcaa8d | |||
464fa9f97a | |||
4788f3189c | |||
d8def3cfc8 | |||
89a3e958b2 | |||
4226f1a14c | |||
4a262dc6a1 | |||
13e82f8768 | |||
a88a3dbf65 | |||
3cbc8a744c | |||
45286ded55 | |||
f97f010dec | |||
d83e1bf731 | |||
aaf6fcaa37 | |||
7c6322041d | |||
0bf6143bf3 | |||
4795fac5ac | |||
d20cb4c3bc | |||
56857554e9 | |||
045af7788b | |||
6d7b551f25 | |||
b53ca9cac4 | |||
fe50eddc25 | |||
c55cb53a41 | |||
c0ab9e89f3 | |||
219b18e34b | |||
a43f3de8bc | |||
98a2c463b9 | |||
7ae16ea258 | |||
ffcaeec653 | |||
acf2484cbb | |||
1e9a6abe74 | |||
a7f6cff625 | |||
a5b0055256 | |||
900eb16aa9 | |||
14705efddd | |||
ebccec54bf | |||
74a857ca30 | |||
b86a91882f | |||
a7dc1400c4 | |||
656823611c | |||
fb9ee7381d | |||
e27349a2ab | |||
de5f21eb20 | |||
8fe8800853 | |||
a475a51910 | |||
e28e32d0c0 | |||
606cd76ec4 | |||
166f5bc1ea | |||
bb3da8d03b | |||
e394518aad | |||
a373f63756 | |||
d99df7f898 | |||
ad9675e60e | |||
e73616774a | |||
1a46ca33b0 | |||
c42b4eca2d | |||
a1b038057e | |||
04101cfd1b | |||
90e80d1018 | |||
719f02bde7 | |||
aefb68e913 | |||
e4d7c5757a | |||
66600757da | |||
826d76253d | |||
6d8b99cf76 | |||
ca244b234a | |||
078ce53dc9 | |||
2fc43a7933 | |||
b85d4553fd | |||
c8441a4a9c | |||
8ebf16b542 | |||
9bfec3a50f | |||
0e42d7ce39 | |||
7bf7988617 | |||
22e20abe1f | |||
17dc9c169a | |||
a5dc282fc4 | |||
8bbe69d78f | |||
f1ca475003 | |||
53747bbd1e | |||
909ad1748e | |||
1576ac5d73 | |||
66f26e8481 | |||
9323d77059 | |||
ddd12a020a | |||
c0f076add0 | |||
fcf369387c | |||
3d8a064bed | |||
d8d5d8cd57 | |||
ab5eff0e5c | |||
44ecbce671 | |||
8252393474 | |||
1409676264 | |||
58820b41d9 | |||
49d3b9ba0c | |||
1b9bed700f | |||
3f8aaa290b | |||
87dbcca240 | |||
c15c6a2025 | |||
66c596a3da | |||
9e73029fc2 | |||
760ece280a | |||
e3824ad22a | |||
9ecfc229e4 | |||
e004e1de90 | |||
f1f75522e7 | |||
a725ec1073 | |||
77fae4f6d7 | |||
b21b783aa6 | |||
828c8a540d | |||
243cec20e7 | |||
7eea8d2362 | |||
b85b0fd4b2 | |||
b7c50f6cf1 | |||
fd60adc2ae | |||
63a204cf2b | |||
a95e1e996f | |||
82effbb387 | |||
c1eeed3f4f | |||
e4ddee9daa | |||
b483d73368 | |||
7edbaa7c41 | |||
032f823717 | |||
8129fee36a | |||
1f4254e9ca | |||
539052eb00 | |||
038c9413ce | |||
5d6c03e576 | |||
b7da03f701 | |||
dd4e319a0a | |||
b5c27b2ed7 | |||
f2b983ea52 | |||
21e84d941e | |||
9bd41317c6 | |||
47f74d2259 | |||
1ff240706c | |||
78071ac475 | |||
70eec9cc47 | |||
a0a7d397a7 | |||
50c5785245 | |||
497c287019 | |||
0e2d69f106 | |||
a9af61076e | |||
d2e7d755e8 | |||
4e989bfd9b | |||
f65abc34e8 | |||
a96f461a63 | |||
eaf08f2e08 |
4
.docs/.markdownlint.json
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
{
|
||||||
|
"MD013": false,
|
||||||
|
"MD007": { "indent": 4 }
|
||||||
|
}
|
52
.docs/aurora/case-commands.md
Normal file
|
@ -0,0 +1,52 @@
|
||||||
|
# Case Commands
|
||||||
|
|
||||||
|
/// admonition | These commands are slash commands.
|
||||||
|
type: warning
|
||||||
|
Please make sure to enable them with [`[p]slash enable <command>`](https://docs.discord.red/en/stable/cog_guides/core.html#slash-enable), then sync them with [`[p]slash sync`](https://docs.discord.red/en/stable/cog_guides/core.html#slash-sync).
|
||||||
|
///
|
||||||
|
|
||||||
|
## history
|
||||||
|
|
||||||
|
/// admonition | All of the arguments for this command are optional.
|
||||||
|
type: info
|
||||||
|
///
|
||||||
|
|
||||||
|
- Usage: `/history [target] [moderator] [pagesize] [page] [ephemeral] [inline] [export]`
|
||||||
|
- If both `target` and `moderator` are not present, all moderations for the server will be queried.
|
||||||
|
- `target:` User whose infractions to query, overrides moderator if both are given
|
||||||
|
- `moderator:` Moderator whose infractions to query
|
||||||
|
- `pagesize:` Amount of infractions to list per page
|
||||||
|
- `page:` Page to select
|
||||||
|
- `ephemeral:` Hide the command response
|
||||||
|
- `inline:` Display infractions in a grid arrangement
|
||||||
|
- `export:` Exports the server's entire moderation history to a JSON file
|
||||||
|
|
||||||
|
List previous infractions.
|
||||||
|
|
||||||
|
## resolve
|
||||||
|
|
||||||
|
- Usage: `/resolve <case> [reason]`
|
||||||
|
- `case:` (Required) Case number of the case you're trying to resolve
|
||||||
|
- `reason:` (Optional) Reason for resolving case
|
||||||
|
|
||||||
|
Resolve a specific case.
|
||||||
|
|
||||||
|
## case
|
||||||
|
|
||||||
|
- Usage: `/case <case> [ephemeral] [evidenceformat] [changes] [export]`
|
||||||
|
- `case:` (Required) What case are you looking up?
|
||||||
|
- `ephemeral:` (Optional) Hide the command response
|
||||||
|
- `evidenceformat:` (Optional) …
|
||||||
|
- `changes:` (Optional) List the changes made to the case
|
||||||
|
- `export:` (Optional) Export the case to a JSON file or codeblock
|
||||||
|
|
||||||
|
Check the details of a specific case.
|
||||||
|
|
||||||
|
## edit
|
||||||
|
|
||||||
|
- Usage: `/edit <case> <reason> [duration]`
|
||||||
|
- `case:` (Required) What case are you editing?
|
||||||
|
- `reason:` (Required) What is the new reason?
|
||||||
|
- `duration:` (Optional) What is the new duration? Does not reapply the moderation if it has already expired.
|
||||||
|
|
||||||
|
Edit the reason of a specific case.
|
88
.docs/aurora/configuration.md
Normal file
|
@ -0,0 +1,88 @@
|
||||||
|
# Configuration
|
||||||
|
|
||||||
|
/// admonition | Work in progress
|
||||||
|
type: warning
|
||||||
|
This page is still a work in progress.
|
||||||
|
///
|
||||||
|
|
||||||
|
## aurora
|
||||||
|
|
||||||
|
- Usage: `[p]aurora`
|
||||||
|
- Aliases: `moderation and mod`
|
||||||
|
|
||||||
|
Settings and miscellaneous commands for Aurora.
|
||||||
|
|
||||||
|
### aurora import
|
||||||
|
|
||||||
|
- Usage: `[p]aurora import`
|
||||||
|
- Restricted to: `ADMIN`
|
||||||
|
- Checks: `server_only`
|
||||||
|
|
||||||
|
Import moderation history from other bots.
|
||||||
|
|
||||||
|
#### aurora import aurora
|
||||||
|
|
||||||
|
- Usage: `[p]aurora import aurora`
|
||||||
|
- Restricted to: `ADMIN`
|
||||||
|
|
||||||
|
Import moderation history from another bot using Aurora.
|
||||||
|
|
||||||
|
#### aurora import galacticbot
|
||||||
|
|
||||||
|
- Usage: `[p]aurora import galacticbot`
|
||||||
|
- Restricted to: `ADMIN`
|
||||||
|
|
||||||
|
Import moderation history from GalacticBot.
|
||||||
|
|
||||||
|
### aurora settings
|
||||||
|
|
||||||
|
- Usage: `[p]aurora settings`
|
||||||
|
- Aliases: `config, options, and set`
|
||||||
|
|
||||||
|
Configure Aurora's settings.
|
||||||
|
|
||||||
|
#### aurora settings server
|
||||||
|
|
||||||
|
- Usage: `[p]aurora settings server`
|
||||||
|
- Restricted to: `ADMIN`
|
||||||
|
- Aliases: `server`
|
||||||
|
- Checks: `server_only`
|
||||||
|
|
||||||
|
Manage Aurora's server settings.
|
||||||
|
|
||||||
|
#### aurora settings overrides
|
||||||
|
|
||||||
|
- Usage: `[p]aurora settings overrides`
|
||||||
|
- Aliases: `override and user`
|
||||||
|
|
||||||
|
Manage Aurora's user overriddable settings.
|
||||||
|
|
||||||
|
#### aurora settings addrole
|
||||||
|
|
||||||
|
- Usage: `[p]aurora settings addrole`
|
||||||
|
- Restricted to: `ADMIN`
|
||||||
|
- Aliases: `removerole`
|
||||||
|
- Checks: `server_only`
|
||||||
|
|
||||||
|
Manage the addrole whitelist.
|
||||||
|
Roles added to this list are also applied to `/removerole`.
|
||||||
|
|
||||||
|
#### aurora settings immunity
|
||||||
|
|
||||||
|
- Usage: `[p]aurora settings immunity`
|
||||||
|
- Restricted to: `ADMIN`
|
||||||
|
- Checks: `server_only`
|
||||||
|
|
||||||
|
Manage the immunity whitelist.
|
||||||
|
|
||||||
|
### aurora timedelta
|
||||||
|
|
||||||
|
- Usage: `[p]aurora timedelta <duration>`
|
||||||
|
- Aliases: `tdc, td, and timedeltaconvert`
|
||||||
|
|
||||||
|
This command converts a duration to a [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) Python object.
|
||||||
|
|
||||||
|
**Example usage**
|
||||||
|
`[p]timedelta 1 day 15hr 82 minutes 52s`
|
||||||
|
**Output**
|
||||||
|
`1 day, 16:22:52`
|
16
.docs/aurora/index.md
Normal file
|
@ -0,0 +1,16 @@
|
||||||
|
# Aurora
|
||||||
|
|
||||||
|
/// admonition | This project is in active development
|
||||||
|
type: warning
|
||||||
|
These docs are not complete yet, and there is a lot still to do.
|
||||||
|
///
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
[p]repo add seacogs https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs
|
||||||
|
[p]cog install seacogs aurora
|
||||||
|
[p]cog load aurora
|
||||||
|
```
|
86
.docs/aurora/moderation-commands.md
Normal file
|
@ -0,0 +1,86 @@
|
||||||
|
# Moderation Commands
|
||||||
|
|
||||||
|
/// admonition | These commands are slash commands.
|
||||||
|
type: warning
|
||||||
|
Please make sure to enable them with [`[p]slash enable <command>`](https://docs.discord.red/en/stable/cog_guides/core.html#slash-enable), then sync them with [`[p]slash sync`](https://docs.discord.red/en/stable/cog_guides/core.html#slash-sync).
|
||||||
|
///
|
||||||
|
|
||||||
|
## note
|
||||||
|
|
||||||
|
- Usage: `/note <target> <reason> [silent]`
|
||||||
|
- `target:` (Required) Who are you noting?
|
||||||
|
- `reason:` (Required) Why are you noting this user?
|
||||||
|
- `silent:` (Optional) Should the user be messaged?
|
||||||
|
|
||||||
|
Add a note to a user.
|
||||||
|
|
||||||
|
## warn
|
||||||
|
|
||||||
|
- Usage: `/warn <target> <reason> [silent]`
|
||||||
|
- `target:` (Required) Who are you warning?
|
||||||
|
- `reason:` (Required) Why are you warning this user?
|
||||||
|
- `silent:` (Optional) Should the user be messaged?
|
||||||
|
|
||||||
|
Warn a user.
|
||||||
|
|
||||||
|
## blacklist
|
||||||
|
|
||||||
|
/// admonition | This command is unfinished, and doesn't currently work.
|
||||||
|
type: warning
|
||||||
|
///
|
||||||
|
|
||||||
|
- Usage: `/blacklist <target> <role> <reason> [silent]`
|
||||||
|
- `target:` (Required) Who are you blacklisting?
|
||||||
|
- `role:` (Required) What blacklist type are you applying to the target?
|
||||||
|
- `reason:` (Required) Why are you blacklisting this user?
|
||||||
|
- `silent:` (Optional) Should the user be messaged?
|
||||||
|
|
||||||
|
Add a blacklist role to a user.
|
||||||
|
|
||||||
|
## mute
|
||||||
|
|
||||||
|
- Usage: `/mute <target> <duration> <reason> [silent]`
|
||||||
|
- `target:` (Required) Who are you unbanning?
|
||||||
|
- `duration:` (Required) How long are you muting this user for?
|
||||||
|
- `reason:` (Required) Why are you unbanning this user?
|
||||||
|
- `silent:` (Optional) Should the user be messaged?
|
||||||
|
|
||||||
|
Mute a user.
|
||||||
|
|
||||||
|
## unmute
|
||||||
|
|
||||||
|
- Usage: `/unmute <target> [reason] [silent]`
|
||||||
|
- `target:` (Required) Who are you unmuting?
|
||||||
|
- `reason:` (Optional) Why are you unmuting this user?
|
||||||
|
- `silent:` (Optional) Should the user be messaged?
|
||||||
|
|
||||||
|
Unmute a user.
|
||||||
|
|
||||||
|
## kick
|
||||||
|
|
||||||
|
- Usage: `/kick <target> <reason> [silent]`
|
||||||
|
- `target:` (Required) Who are you kicking?
|
||||||
|
- `reason:` (Required) Why are you kicking this user?
|
||||||
|
- `silent:` (Optional) Should the user be messaged?
|
||||||
|
|
||||||
|
Kick a user.
|
||||||
|
|
||||||
|
## ban
|
||||||
|
|
||||||
|
- Usage: `/ban <target> <reason> [duration] [delete_messages] [silent]`
|
||||||
|
- `target:` (Required) Who are you banning?
|
||||||
|
- `reason:` (Required) Why are you banning this user?
|
||||||
|
- `duration:` (Optional) How long are you banning this user for?
|
||||||
|
- `delete_messages:` (Optional) How many days of messages to delete?
|
||||||
|
- `silent:` (Optional) Should the user be messaged?
|
||||||
|
|
||||||
|
Ban a user.
|
||||||
|
|
||||||
|
## unban
|
||||||
|
|
||||||
|
- Usage: `/unban <target> [reason] [silent]`
|
||||||
|
- `target:` (Required) Who are you unbanning?
|
||||||
|
- `reason:` (Optional) Why are you unbanning this user?
|
||||||
|
- `silent:` (Optional) Should the user be messaged?
|
||||||
|
|
||||||
|
Unban a user.
|
33
.docs/backup.md
Normal file
|
@ -0,0 +1,33 @@
|
||||||
|
# Backup
|
||||||
|
|
||||||
|
Backup allows you to export a JSON list of all of your installed repositories and cogs, then reimport them and automatically reinstall/reload the cogs.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
[p]repo add seacogs https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs
|
||||||
|
[p]cog install seacogs backup
|
||||||
|
[p]cog load backup
|
||||||
|
```
|
||||||
|
|
||||||
|
## Version Compatibility
|
||||||
|
|
||||||
|
As of commit [1edb08a](https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs/commit/1edb08a1271f12098ca0bed11a735f7162cedd14), the Backup cog no longer supports Red versions older than 3.5.6. If you want to use the cog on an earlier version (3.5.0 - 3.5.5), install the cog pinned to this commit: `43464db6a7c51bc69282b1ae3dc507a4aae851de`.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
[p]cog installversion sea-cogs 43464db6a7c51bc69282b1ae3dc507a4aae851de backup
|
||||||
|
```
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
### backup export
|
||||||
|
|
||||||
|
- Usage: `[p]backup export`
|
||||||
|
|
||||||
|
Exports a JSON list of all of your added repositories, and their installed cogs.
|
||||||
|
|
||||||
|
### backup import
|
||||||
|
|
||||||
|
- Usage: `[p]backup import`
|
||||||
|
|
||||||
|
Reinstalls repositories and cogs from a valid export. Requires the JSON export to be attached to the invoking message as an attachment. Ignores itself and PyLav cogs, due to possible conflicts with Docker images.
|
36
.docs/bible.md
Normal file
|
@ -0,0 +1,36 @@
|
||||||
|
# Bible
|
||||||
|
|
||||||
|
Bible allows you to get a specific (or random) Bible verse from the [API.Bible](https://scripture.api.bible/) API.
|
||||||
|
This cog does require an api key to work.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
[p]repo add seacogs https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs
|
||||||
|
[p]cog install seacogs bible
|
||||||
|
[p]cog load bible
|
||||||
|
```
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
|
||||||
|
This cog requires an [API.Bible](https://scripture.api.bible/) API key to function. You can sign up for an account [here](https://scripture.api.bible/signup). This will also generate your first API key for you.
|
||||||
|
|
||||||
|
Then, you can use `[p]set api` to set the API key. Make sure your formatting matches the screenshot below.
|
||||||
|
![image](img/bible/set-api.png)
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
### bible passage
|
||||||
|
- Usage: `[p]bible passage <book> <passage>`
|
||||||
|
- Aliases: `verse`
|
||||||
|
|
||||||
|
Get a Bible passage.
|
||||||
|
|
||||||
|
Example usage:
|
||||||
|
`[p]bible passage Genesis 1:1`
|
||||||
|
`[p]bible passage John 3:16-3:17`
|
||||||
|
|
||||||
|
### bible random
|
||||||
|
- Usage: `[p]bible random`
|
||||||
|
|
||||||
|
Get a random Bible verse.
|
BIN
.docs/img/bible/set-api.png
Normal file
After Width: | Height: | Size: 9.6 KiB |
BIN
.docs/img/logo.png
Normal file
After Width: | Height: | Size: 657 B |
BIN
.docs/img/pterodactyl/installing-red/1.png
Normal file
After Width: | Height: | Size: 181 KiB |
BIN
.docs/img/pterodactyl/installing-red/2.png
Normal file
After Width: | Height: | Size: 168 KiB |
BIN
.docs/img/pterodactyl/installing-red/3.png
Normal file
After Width: | Height: | Size: 274 KiB |
BIN
.docs/img/pterodactyl/setup/1.png
Normal file
After Width: | Height: | Size: 167 KiB |
BIN
.docs/img/pterodactyl/setup/10.png
Normal file
After Width: | Height: | Size: 31 KiB |
BIN
.docs/img/pterodactyl/setup/2.png
Normal file
After Width: | Height: | Size: 52 KiB |
BIN
.docs/img/pterodactyl/setup/3.png
Normal file
After Width: | Height: | Size: 114 KiB |
BIN
.docs/img/pterodactyl/setup/4.png
Normal file
After Width: | Height: | Size: 129 KiB |
BIN
.docs/img/pterodactyl/setup/5.png
Normal file
After Width: | Height: | Size: 135 KiB |
BIN
.docs/img/pterodactyl/setup/6.png
Normal file
After Width: | Height: | Size: 35 KiB |
BIN
.docs/img/pterodactyl/setup/7.png
Normal file
After Width: | Height: | Size: 3.2 KiB |
BIN
.docs/img/pterodactyl/setup/8.png
Normal file
After Width: | Height: | Size: 38 KiB |
BIN
.docs/img/pterodactyl/setup/9.png
Normal file
After Width: | Height: | Size: 150 KiB |
4
.docs/index.md
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
# Welcome to SeaCogs
|
||||||
|
|
||||||
|
This is the documentation for my Red-DiscordBot Cogs.
|
||||||
|
See the top bar for a list of cogs and their documentation.
|
21
.docs/nerdify.md
Normal file
|
@ -0,0 +1,21 @@
|
||||||
|
# Nerdify
|
||||||
|
|
||||||
|
Nerdify allows you to nerdify other people's text.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
[p]repo add seacogs https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs
|
||||||
|
[p]cog install seacogs nerdify
|
||||||
|
[p]cog load nerdify
|
||||||
|
```
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
### nerdify
|
||||||
|
|
||||||
|
- Usage: `[p]nerdify [text]`
|
||||||
|
- Aliases: `nerd`
|
||||||
|
|
||||||
|
Nerdify the replied to message, previous message, or your own text.
|
||||||
|
If `[text]` is not provided, the bot will try to nerdify either the previous message or the replied to message, if the invocation message is a reply.
|
199
.docs/pterodactyl/configuration.md
Normal file
|
@ -0,0 +1,199 @@
|
||||||
|
# Configuration
|
||||||
|
|
||||||
|
This page will go over all of the configuration options for the Pterodactyl cog.
|
||||||
|
All of the commands below can be accessed through `[p]pterodactyl config`.
|
||||||
|
|
||||||
|
## `api`
|
||||||
|
|
||||||
|
This option determines which [PlayerDB](https://playerdb.co/) endpoint the cog will use to retrieve player avatars.
|
||||||
|
This is only used for webhook avatars in the chat integration system. You should probably leave this as default.
|
||||||
|
|
||||||
|
Default value: `minecraft`
|
||||||
|
|
||||||
|
## `chat`
|
||||||
|
|
||||||
|
### `channel`
|
||||||
|
|
||||||
|
This option determines what channel chat messages will be sent to. If this is unset, the chat integration won't work.
|
||||||
|
**Make sure the bot has permissions to speak in this channel!**
|
||||||
|
|
||||||
|
Default value: `None`
|
||||||
|
|
||||||
|
### `command`
|
||||||
|
|
||||||
|
This option determines what command will be sent to the server whenever a message is sent in the configured chat channel. The JSON format Minecraft uses for this is very janky sometimes, if you need help with changing the command, you can join my [Discord server](https://discord.gg/eMUMe77Yb8).
|
||||||
|
|
||||||
|
Available placeholders:
|
||||||
|
|
||||||
|
- `.$C` - replaced with hex color of the author's top colored role
|
||||||
|
- `.$D` - replaced with the author's discriminator (will usually be 0, you shouldn't use this)
|
||||||
|
- `.$I` - replaced with the author's ID
|
||||||
|
- `.$M` - replaced with message content
|
||||||
|
- `.$N` - replaced with author's display name (or guild nickname, if set)
|
||||||
|
- `.$U` - replaced with the author's username (NOT display name, you should usually use `.$N`)
|
||||||
|
- `.$V` - replaced with the configured invite link
|
||||||
|
|
||||||
|
Default value:
|
||||||
|
|
||||||
|
```json
|
||||||
|
tellraw @a ["",{"text":".$N ","color":".$C","insertion":"<@.$I>","hoverEvent":{"action":"show_text","contents":"Shift click to mention this user inside Discord"}},{"text":"(DISCORD):","color":"blue","clickEvent":{"action":"open_url","value":".$V"},"hoverEvent":{"action":"show_text","contents":"Click to join the Discord Server"}},{"text":" .$M","color":"white"}]
|
||||||
|
```
|
||||||
|
|
||||||
|
## `console`
|
||||||
|
|
||||||
|
### `channel`
|
||||||
|
|
||||||
|
/// admonition | Only give access to the console channel to people you trust!
|
||||||
|
type: danger
|
||||||
|
If a user account has access to the console channel, they can execute ***any*** command on your server, including some power actions.
|
||||||
|
They will also be able to see potentially sensitive information, such as player IPs, if [IP Masking](configuration.md#ip) is disabled.
|
||||||
|
///
|
||||||
|
|
||||||
|
This option determines what channel console logs will be sent to. If this is unset, the console integration won't work.
|
||||||
|
**Make sure the bot has permissions to speak in this channel!**
|
||||||
|
Server status changes, Discord --> Minecraft chat messages, and command executions will all be logged here.
|
||||||
|
|
||||||
|
/// admonition
|
||||||
|
type: info
|
||||||
|
Please note that, in order to avoid Discord ratelimits, logs will not be posted when the server status is one of the following:
|
||||||
|
|
||||||
|
- `starting`
|
||||||
|
- `stopping`
|
||||||
|
|
||||||
|
This is to prevent the console channel from flooding and getting backed up by Discord's message ratelimits.
|
||||||
|
///
|
||||||
|
|
||||||
|
Default value: `None`
|
||||||
|
|
||||||
|
### `commands`
|
||||||
|
|
||||||
|
/// admonition | This has no effect on the `[p]pterodactyl command` text command, or the matching slash command.
|
||||||
|
type: danger
|
||||||
|
If you want to disable the ability to execute commands on the server through Discord, use the following commands:
|
||||||
|
`[p]pterodactyl config console commands False` - this command
|
||||||
|
`[p]command disable pterodactyl command` - disables the text command that lets you execute commands on the server
|
||||||
|
`[p]slash disable pterodactyl` - due to how slash commands are laid out, this is the only way to disable the ability to execute commands on the server
|
||||||
|
`[p]slash sync` - apply above slash command change
|
||||||
|
///
|
||||||
|
|
||||||
|
This option determines if commands sent to the console channel will be sent to the Pterodactyl console.
|
||||||
|
|
||||||
|
Default value: `False`
|
||||||
|
|
||||||
|
## `invite`
|
||||||
|
|
||||||
|
This option determines what url the chat command will substitute in for the Discord invite placeholder.
|
||||||
|
|
||||||
|
Default value: `None`
|
||||||
|
|
||||||
|
## `ip`
|
||||||
|
|
||||||
|
This option determines whether or not IP's will be redacted when posted in chat or to the console channel.
|
||||||
|
|
||||||
|
Default value: `True`
|
||||||
|
|
||||||
|
## `messages`
|
||||||
|
|
||||||
|
### `join`
|
||||||
|
|
||||||
|
This option determines what the description in embeds will be when a user joins the server. Has no effect if embeds aren't used.
|
||||||
|
|
||||||
|
Default value: `Welcome to the server! 👋`
|
||||||
|
|
||||||
|
### `leave`
|
||||||
|
|
||||||
|
This option determines what the description in embeds will be when a user leaves the server. Has no effect if embeds aren't used.
|
||||||
|
|
||||||
|
Default value: `Goodbye! 👋`
|
||||||
|
|
||||||
|
### `shutdown`
|
||||||
|
|
||||||
|
This option determines what the bot will send in the chat channel when the server stops.
|
||||||
|
|
||||||
|
Default value: `Server stopped!`
|
||||||
|
|
||||||
|
### `startup`
|
||||||
|
|
||||||
|
This option determines what the bot will send in the chat channel when the server is started.
|
||||||
|
|
||||||
|
Default value: `Server started!`
|
||||||
|
|
||||||
|
## `regex`
|
||||||
|
|
||||||
|
If you're not running on recent versions of Paper, which this cog was developed against, or you're otherwise changing for format of chat messages, you'll need to add custom regex through the `[p]pterodactyl config regex` command. Same thing applies if any other type of message isn't being detected. I recomend using ChatGPT or something similar for this, or if you need help, you can join my [Discord server](https://discord.gg/eMUMe77Yb8).
|
||||||
|
See [Regex Examples](regex.md) for default values.
|
||||||
|
|
||||||
|
### `blacklist`
|
||||||
|
|
||||||
|
This group of commands allows you to add regex patterns that will be ignored by the console logger. The intended use for this is if you're getting ratelimited by messages that flood the console after the server sets its status to `running` but before it actually finishes starting.
|
||||||
|
|
||||||
|
### `achievement`
|
||||||
|
|
||||||
|
This regex pattern is used to detect advacnements/challenges. The default should work for most Minecraft servers.
|
||||||
|
|
||||||
|
### `chat`
|
||||||
|
|
||||||
|
This regex pattern is used to detect chat messages. You will probably have to change this if you're using any plugins or mods that use custom chat formatting, like EssentialsX Chat or Styled Chat.
|
||||||
|
|
||||||
|
### `join`
|
||||||
|
|
||||||
|
This regex pattern is used to detect whenever a user joins the server. You shouldn't usually need to change this.
|
||||||
|
|
||||||
|
### `leave`
|
||||||
|
|
||||||
|
This regex pattern is used to detect whenever a user leaves the server. You shouldn't usually need to change this.
|
||||||
|
|
||||||
|
### `server`
|
||||||
|
|
||||||
|
This regex pattern is used to detect whenever a server message is sent. You will have to change this if you aren't running on Paper, most likely.
|
||||||
|
|
||||||
|
## `serverid`
|
||||||
|
|
||||||
|
This option determines which server's websocket to connect to. See [Getting Started](getting-started.md#getting-server-information) for more information on this.
|
||||||
|
|
||||||
|
Default value: `None`
|
||||||
|
|
||||||
|
## `topic`
|
||||||
|
|
||||||
|
### `host`
|
||||||
|
|
||||||
|
This option determines the hostname of your server that will be used to retrieve server information.
|
||||||
|
|
||||||
|
### `port`
|
||||||
|
|
||||||
|
This option determines the port of your server that will be used to retrieve server information.
|
||||||
|
|
||||||
|
Default value: `25565`
|
||||||
|
|
||||||
|
### `text`
|
||||||
|
|
||||||
|
This option determines what the channel topic will be set to.
|
||||||
|
|
||||||
|
Available placeholders:
|
||||||
|
|
||||||
|
- `.$H` - replaced with the server's hostname
|
||||||
|
- `.$O` - replaced with the server's port
|
||||||
|
|
||||||
|
Available with a Minecraft server:
|
||||||
|
|
||||||
|
- `.$I` - replaced with the server's ip address
|
||||||
|
- `.$M` - replaced with maximum player count
|
||||||
|
- `.$P` - replaced with current online player count
|
||||||
|
- `.$V` - replaced with the server's current version
|
||||||
|
- `.$D` - replaced with the server's description / message of the day
|
||||||
|
|
||||||
|
Default value:
|
||||||
|
|
||||||
|
```
|
||||||
|
Server IP: .$H\nServer Players: .$P/.$M
|
||||||
|
```
|
||||||
|
|
||||||
|
## `url`
|
||||||
|
|
||||||
|
This option determines what panel the cog will send requests to. See [Getting Started](getting-started.md#getting-server-information) for more information on this.
|
||||||
|
|
||||||
|
Default value: `None`
|
||||||
|
|
||||||
|
## `view`
|
||||||
|
|
||||||
|
Lists all of the configuration options offered by the cog.
|
104
.docs/pterodactyl/getting-started.md
Normal file
|
@ -0,0 +1,104 @@
|
||||||
|
# Getting Started
|
||||||
|
|
||||||
|
This page will go over the steps required to get started with the Pterodactyl cog.
|
||||||
|
|
||||||
|
/// admonition | Screenshots may be visually distinct
|
||||||
|
type: info
|
||||||
|
For the purpose of this guide, I'll be using [Bloom Host's](https://bloom.host/) [Pterodactyl fork](https://mc.bloom.host/).
|
||||||
|
The steps should be basically identical for other panels, but screenshots will look visually different.
|
||||||
|
If in doubt, contact your host's support.
|
||||||
|
///
|
||||||
|
|
||||||
|
## Installing the cog
|
||||||
|
|
||||||
|
This project is a [cog](https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html) made for use with *specifically* instances of [Red-DiscordBot](https://github.com/Cog-Creators/Red-DiscordBot).
|
||||||
|
See the [Red documentation](https://docs.discord.red/en/stable/install_guides/index.html) for information on how to run an instance of Red. Once you've got it running, come back here.
|
||||||
|
|
||||||
|
/// admonition | `[p]` is your bot's prefix
|
||||||
|
type: tip
|
||||||
|
///
|
||||||
|
|
||||||
|
Now, load the Downloader cog:
|
||||||
|
|
||||||
|
```
|
||||||
|
[p]load downloader
|
||||||
|
```
|
||||||
|
|
||||||
|
The Downloader cog allows you to add Git repositories to your bot in order to download cogs from them.
|
||||||
|
Now, use Downloader to add my repository to your bot:
|
||||||
|
|
||||||
|
```
|
||||||
|
[p]repo add sea-cogs https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs
|
||||||
|
```
|
||||||
|
|
||||||
|
Now, install the Pterodactyl cog:
|
||||||
|
|
||||||
|
```
|
||||||
|
[p]cog install sea-cogs pterodactyl
|
||||||
|
[p]load pterodactyl
|
||||||
|
```
|
||||||
|
|
||||||
|
## Creating a sub-user
|
||||||
|
|
||||||
|
This is **optional**, but highly recommended, for security reasons.
|
||||||
|
|
||||||
|
Navigate to your `Users` page, and click the `New User` button.
|
||||||
|
Type in an email address, and scroll down to the `Control` header.
|
||||||
|
Click the checkmark on that header to select all of the permissions contained under the header.
|
||||||
|
Now, scroll back up to the top of the prompt and press `Invite User`.
|
||||||
|
|
||||||
|
![image](../img/pterodactyl/setup/1.png)
|
||||||
|
![image](../img/pterodactyl/setup/2.png)
|
||||||
|
|
||||||
|
Now, you'll need to check the email you just entered into the subusers page, and create an account. I won't cover this, as it'll change depending on what host you're using.
|
||||||
|
|
||||||
|
## Getting an API Key
|
||||||
|
|
||||||
|
**Log out of your primary account, and switch to the sub-user you just created.**
|
||||||
|
|
||||||
|
Navigate to your sub-user account's `API Credentials` page.
|
||||||
|
|
||||||
|
![image](../img/pterodactyl/setup/3.png)
|
||||||
|
|
||||||
|
Create a new API key.
|
||||||
|
|
||||||
|
![image](../img/pterodactyl/setup/4.png)
|
||||||
|
|
||||||
|
You don't have to specify an allowed IP if you don't want to, but I recommend it. If you chose to, you'll need to retrieve your bot's IP address. You can do this through SSH or through a cog like [AAA3A's IP cog](https://github.com/AAA3A-AAA3A/AAA3A-cogs).
|
||||||
|
|
||||||
|
![image](../img/pterodactyl/setup/5.png)
|
||||||
|
|
||||||
|
Now, use the `[p]set api` command on your bot to add the API key.
|
||||||
|
The format is as follows:
|
||||||
|
|
||||||
|
```
|
||||||
|
# Service: pterodactyl
|
||||||
|
# Keys and Tokens: api_key ptlc_...
|
||||||
|
```
|
||||||
|
|
||||||
|
![image](../img/pterodactyl/setup/6.png)
|
||||||
|
|
||||||
|
## Getting server information
|
||||||
|
|
||||||
|
There's some other information that the Pterodactyl cog needs to function.
|
||||||
|
|
||||||
|
First, get the base url for your panel. This does not include any extra information, like server ids, or whatnot. In my case, I'm using `https://mc.bloom.host/`.
|
||||||
|
|
||||||
|
![image](../img/pterodactyl/setup/7.png)
|
||||||
|
|
||||||
|
Use the `[p]pterodactyl config url` command to set the URL the cog will use.
|
||||||
|
In my case, I'd use `-pterodactyl config url https://mc.bloom.host/`.
|
||||||
|
|
||||||
|
![image](../img/pterodactyl/setup/8.png)
|
||||||
|
|
||||||
|
Now, we need to get the id of your server. Navigate to the `Settings` page in your panel.
|
||||||
|
|
||||||
|
![image](../img/pterodactyl/setup/9.png)
|
||||||
|
|
||||||
|
Use the `[p]pterodactyl config serverid` command to add the server id to the bot.
|
||||||
|
In my case, I'd use `-pterodactyl config serverid ad712016-df3d-47a5-b1df-6b71baf50340`.
|
||||||
|
|
||||||
|
![image](../img/pterodactyl/setup/10.png)
|
||||||
|
|
||||||
|
Once you've done all of this, you should see a connection message in the bot's logs. Now, we need to configure some other things.
|
||||||
|
See the [Configuration](configuration.md) page for more information.
|
16
.docs/pterodactyl/index.md
Normal file
|
@ -0,0 +1,16 @@
|
||||||
|
# Pterodactyl
|
||||||
|
|
||||||
|
/// admonition | This project is in active development
|
||||||
|
type: warning
|
||||||
|
These docs are not complete yet, and there is a lot still to do.
|
||||||
|
///
|
||||||
|
|
||||||
|
Pterodactyl allows for connecting to a Pterodactyl server through websockets. It is intended primarily for use with Minecraft servers, as it allows for version & server platform-agnostic Discord integration, including console logging and two-way chat bridging.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
[p]repo add seacogs https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs
|
||||||
|
[p]cog install seacogs pterodactyl
|
||||||
|
[p]cog load aurora
|
||||||
|
```
|
74
.docs/pterodactyl/installing-red.md
Normal file
|
@ -0,0 +1,74 @@
|
||||||
|
# Installing Red
|
||||||
|
|
||||||
|
This guide will explain how to create an instance of [Red-DiscordBot]() (referred to as 'Red') on a Pterodactyl panel.
|
||||||
|
|
||||||
|
Running the bot on Pterodactyl is not required to use the Pterodactyl cog. If you already have a working instance of Red, you should look at [Getting Started](getting-started.md).
|
||||||
|
|
||||||
|
/// admonition | Caveats
|
||||||
|
type: warning
|
||||||
|
There are a few caveats to running an instance of Red on Pterodactyl.
|
||||||
|
|
||||||
|
- You will not receive any support from the Red developers.
|
||||||
|
- The built-in Audio cog will not work.
|
||||||
|
- Depending on your host, you might have to request a [`tmpfs` size increase](https://github.com/ign-gg/Pterodactyl-Eggs/tree/master/bots/discord/redbot#additional-requirements).
|
||||||
|
|
||||||
|
If these are unacceptable to you, you should [install Red normally](https://docs.discord.red/en/stable/install_guides/index.html).
|
||||||
|
///
|
||||||
|
|
||||||
|
/// admonition | Requirements
|
||||||
|
type: info
|
||||||
|
- A Discord bot token (see [Creating a bot account](https://docs.discord.red/en/stable/bot_application_guide.html))
|
||||||
|
- A panel host with the [Red-DiscordBot Pterodactyl egg](https://github.com/ign-gg/Pterodactyl-Eggs/tree/master/bots/discord/redbot)
|
||||||
|
- A panel with support for server splitting, like [Bloom.host](https://bloom.host/)'s DuckPanel.
|
||||||
|
///
|
||||||
|
|
||||||
|
## Creating a Server Split
|
||||||
|
|
||||||
|
1. Navigate to your host's server split option.
|
||||||
|
2. Select `Discord Bots` in the `Server Category` dropdown
|
||||||
|
3. Select `Red` in the `Server Type` dropdown
|
||||||
|
4. Allocate 1gb of RAM to Red. You can get away with less, but for the purposes of this guide we'll be using 1gb.
|
||||||
|
5. Allocate 5gb of storage space to Red.
|
||||||
|
6. Click the `Split Server` button. The installation process will take a few minutes, once it's done, continue to the next section.
|
||||||
|
|
||||||
|
![server-split-img](../img/pterodactyl/installing-red/1.png)
|
||||||
|
|
||||||
|
## Configuring Startup Variables
|
||||||
|
|
||||||
|
1. Navigate to the `Startup` page of your new server split.
|
||||||
|
2. Enter in your bot token.
|
||||||
|
3. If you want to change the default prefix that the bot will respond to, do so here.
|
||||||
|
4. If you want to change the owner of the bot, you can do so here. This defaults to the owner of the application the bot user is from.
|
||||||
|
|
||||||
|
![server-startup-img](../img/pterodactyl/installing-red/2.png)
|
||||||
|
|
||||||
|
## Inviting the Bot
|
||||||
|
|
||||||
|
1. Navigate to the `Console` page of your server split.
|
||||||
|
2. Click the `Start` button.
|
||||||
|
3. Click the Invite URL in your console, once the bot starts.
|
||||||
|
|
||||||
|
![console-img](../img/pterodactyl/installing-red/3.png)
|
||||||
|
|
||||||
|
## Initial Setup
|
||||||
|
|
||||||
|
Red is quite a large bot, so I'll focus on the specifics of getting the bot working with my Pterodactyl cog specifically.
|
||||||
|
|
||||||
|
/// admonition | `[p]` is your bot's prefix
|
||||||
|
type: tip
|
||||||
|
///
|
||||||
|
|
||||||
|
1. Load the `Downloader` cog.
|
||||||
|
```bash
|
||||||
|
[p]load downloader
|
||||||
|
```
|
||||||
|
2. Add my repository to the bot
|
||||||
|
```bash
|
||||||
|
[p]repo add sea-cogs https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs
|
||||||
|
```
|
||||||
|
3. Install and load the Pterodactyl cog
|
||||||
|
```bash
|
||||||
|
[p]cog install sea-cogs pterodactyl
|
||||||
|
[p]load pterodactyl
|
||||||
|
```
|
||||||
|
4. Follow the instructions given in [Getting Started](getting-started.md)
|
65
.docs/pterodactyl/regex.md
Normal file
|
@ -0,0 +1,65 @@
|
||||||
|
# Regex Examples
|
||||||
|
|
||||||
|
## 1.20.4 - Paper (Default)
|
||||||
|
|
||||||
|
### Achievements
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2} INFO\]: (.*) has (made the advancement|completed the challenge) \[(.*)\]$
|
||||||
|
```
|
||||||
|
|
||||||
|
### Chat
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2}\sINFO\]: (?!\[(?:Server|Rcon)\])(?:<|\[)(\w+)(?:>|\]) (.*)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Join
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2} INFO\]: ([^<\n]+) joined the game$
|
||||||
|
```
|
||||||
|
|
||||||
|
### Leave
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2} INFO\]: ([^<\n]+) left the game$
|
||||||
|
```
|
||||||
|
|
||||||
|
### Server
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2} INFO\]:(?: \[Not Secure\])? \[(?:Server|Rcon)\] (.*)
|
||||||
|
```
|
||||||
|
|
||||||
|
## 1.20.1 - Forge
|
||||||
|
|
||||||
|
### Achievements
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2}\] \[Server thread\/INFO\] \[minecraft\/MinecraftServer\]: (.*) has (made the advancement|completed the challenge) \[(.*)\]$
|
||||||
|
```
|
||||||
|
|
||||||
|
### Chat
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2}\] \[Server thread\/INFO\] \[minecraft\/MinecraftServer\]: (?!\[(?:Server|Rcon)\])(?:<|\[)(\w+)(?:>|\]) (.*)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Join
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2}\] \[Server thread\/INFO\] \[minecraft\/MinecraftServer\]: ([^<\n]+) joined the game$
|
||||||
|
```
|
||||||
|
|
||||||
|
### Leave
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2}\] \[Server thread\/INFO\] \[minecraft\/MinecraftServer\]: ([^<\n]+) left the game$
|
||||||
|
```
|
||||||
|
|
||||||
|
### Server
|
||||||
|
|
||||||
|
```re
|
||||||
|
^\[\d{2}:\d{2}:\d{2}\] \[Server thread\/INFO\] \[minecraft\/MinecraftServer\]: \[(?:Server|Rcon)\] (.*)
|
||||||
|
```
|
|
@ -17,4 +17,5 @@
|
||||||
import-outside-toplevel,
|
import-outside-toplevel,
|
||||||
import-self,
|
import-self,
|
||||||
relative-beyond-top-level,
|
relative-beyond-top-level,
|
||||||
|
too-many-instance-attributes,
|
||||||
duplicate-code
|
duplicate-code
|
||||||
|
|
|
@ -1,28 +0,0 @@
|
||||||
name: Pylint
|
|
||||||
on: [push]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
Pylint:
|
|
||||||
runs-on: docker
|
|
||||||
strategy:
|
|
||||||
matrix:
|
|
||||||
python-version: ["3.11"]
|
|
||||||
container: catthehacker/ubuntu:act-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v3.6.0
|
|
||||||
- name: Set up Python
|
|
||||||
uses: actions/setup-python@v4
|
|
||||||
with:
|
|
||||||
python-version: ${{ matrix.python-version }}
|
|
||||||
- name: Install Poetry
|
|
||||||
run: curl -sSL https://cdn.seaswimmer.cc/go/poetry | python${{ matrix.python-version }} -
|
|
||||||
- name: Install dependencies
|
|
||||||
run: |
|
|
||||||
export PATH="$HOME/.local/bin:$PATH"
|
|
||||||
poetry env use ${{ matrix.python-version }}
|
|
||||||
poetry install --with dev
|
|
||||||
- name: Analysing the code with Pylint
|
|
||||||
run: |
|
|
||||||
export PATH="$HOME/.local/bin:$PATH"
|
|
||||||
poetry run pylint --rcfile .forgejo/workflows/config/.pylintrc $(git ls-files '*.py')
|
|
68
.forgejo/workflows/workflow.yaml
Normal file
|
@ -0,0 +1,68 @@
|
||||||
|
name: Actions
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- 'main'
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
Lint Code (Ruff & Pylint):
|
||||||
|
runs-on: docker
|
||||||
|
container: www.coastalcommits.com/seaswimmerthefsh/actionscontainers-seacogs:latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: poetry install --with dev --no-root
|
||||||
|
|
||||||
|
- name: Analysing code with Ruff
|
||||||
|
run: ./.venv/bin/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')
|
||||||
|
|
||||||
|
Build Documentation (MkDocs):
|
||||||
|
runs-on: docker
|
||||||
|
container: www.coastalcommits.com/seaswimmerthefsh/actionscontainers-seacogs:latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: poetry install --with docs --no-root
|
||||||
|
|
||||||
|
- name: Set environment variables
|
||||||
|
uses: actions/env@v2
|
||||||
|
|
||||||
|
- name: Build documentation
|
||||||
|
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
|
||||||
|
|
||||||
|
- name: Deploy documentation
|
||||||
|
run: |
|
||||||
|
GREEN='\033[0;32m'
|
||||||
|
YELLOW='\033[0;33m'
|
||||||
|
BLUE='\033[0;34m'
|
||||||
|
|
||||||
|
unset GITHUB_TOKEN
|
||||||
|
unset GITLAB_TOKEN
|
||||||
|
|
||||||
|
echo "${YELLOW}Deploying to ${BLUE}Meli ${YELLOW}on branch ${GREEN}$CI_ACTION_REF_NAME_SLUG${YELLOW}...\n"
|
||||||
|
|
||||||
|
npx -p "@getmeli/cli" meli upload ./site \
|
||||||
|
--url "https://pages.coastalcommits.com" \
|
||||||
|
--site "${{ vars.MELI_SITE_ID }}" \
|
||||||
|
--token "${{ secrets.MELI_SITE_SECRET }}" \
|
||||||
|
--release "$CI_ACTION_REF_NAME_SLUG/${{ env.GITHUB_SHA }}" \
|
||||||
|
--branch "$CI_ACTION_REF_NAME_SLUG"
|
||||||
|
|
||||||
|
echo "\n${YELLOW}Deployed to ${BLUE}Meli ${YELLOW}on branch ${GREEN}$CI_ACTION_REF_NAME_SLUG${YELLOW}!"
|
||||||
|
echo "${GREEN}https://$CI_ACTION_REF_NAME_SLUG.seacogs.coastalcommits.com/"
|
||||||
|
env:
|
||||||
|
GITEA_TOKEN: ${{ secrets.COASTALCOMMITSTOKEN }}
|
4
.gitignore
vendored
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
.cache
|
||||||
|
.vscode
|
||||||
|
site
|
||||||
|
.venv
|
|
@ -1,5 +1,9 @@
|
||||||
# SeaCogs
|
# SeaCogs
|
||||||
|
|
||||||
|
[![Discord](https://img.shields.io/discord/1070058354925383681?logo=discord&color=%235661f6)](https://discord.gg/eMUMe77Yb8)
|
||||||
|
[![Documentation](https://img.shields.io/badge/docs-CoastalCommits%20Pages-3e83fd?logo=materialformkdocs)](https://seacogs.coastalcommits.com)
|
||||||
|
![Python Versions](https://img.shields.io/badge/python-3.10%20%7C%203.11-%233776ab?logo=python)
|
||||||
|
|
||||||
My assorted cogs for Red-DiscordBot.
|
My assorted cogs for Red-DiscordBot.
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
5
antipolls/__init__.py
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
from .antipolls import AntiPolls
|
||||||
|
|
||||||
|
|
||||||
|
async def setup(bot):
|
||||||
|
await bot.add_cog(AntiPolls(bot))
|
180
antipolls/antipolls.py
Normal file
|
@ -0,0 +1,180 @@
|
||||||
|
# _____ _
|
||||||
|
# / ____| (_)
|
||||||
|
# | (___ ___ __ _ _____ ___ _ __ ___ _ __ ___ ___ _ __
|
||||||
|
# \___ \ / _ \/ _` / __\ \ /\ / / | '_ ` _ \| '_ ` _ \ / _ \ '__|
|
||||||
|
# ____) | __/ (_| \__ \\ V V /| | | | | | | | | | | | __/ |
|
||||||
|
# |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_|
|
||||||
|
|
||||||
|
import discord
|
||||||
|
from red_commons.logging import getLogger
|
||||||
|
from redbot.core import commands
|
||||||
|
from redbot.core.bot import Config, Red
|
||||||
|
from redbot.core.utils.chat_formatting import humanize_list
|
||||||
|
|
||||||
|
|
||||||
|
class AntiPolls(commands.Cog):
|
||||||
|
"""AntiPolls deletes messages that contain polls, with a configurable per-guild role and channel whitelist and support for default Discord permissions (Manage Messages)."""
|
||||||
|
|
||||||
|
__author__ = ["SeaswimmerTheFsh"]
|
||||||
|
__version__ = "1.0.0"
|
||||||
|
__documentation__ = "https://seacogs.coastalcommits.com/antipolls/"
|
||||||
|
|
||||||
|
def __init__(self, bot: Red):
|
||||||
|
super().__init__()
|
||||||
|
self.bot = bot
|
||||||
|
self.logger = getLogger("red.SeaCogs.AntiPolls")
|
||||||
|
self.config = Config.get_conf(self, identifier=23517395243, force_registration=True)
|
||||||
|
self.config.register_guild(
|
||||||
|
role_whitelist=[],
|
||||||
|
channel_whitelist=[],
|
||||||
|
manage_messages=True,
|
||||||
|
)
|
||||||
|
if not self.bot.intents.message_content:
|
||||||
|
self.logger.error("Message Content intent is not enabled, cog will not load.")
|
||||||
|
raise RuntimeError("This cog requires the Message Content intent to function. To prevent potentially destructive behavior, the cog will not load without the intent enabled.")
|
||||||
|
|
||||||
|
def format_help_for_context(self, ctx: commands.Context) -> str:
|
||||||
|
pre_processed = super().format_help_for_context(ctx) or ""
|
||||||
|
n = "\n" if "\n\n" not in pre_processed else ""
|
||||||
|
text = [
|
||||||
|
f"{pre_processed}{n}",
|
||||||
|
f"Cog Version: **{self.__version__}**",
|
||||||
|
f"Author: {humanize_list(self.__author__)}",
|
||||||
|
f"Documentation: {self.__documentation__}",
|
||||||
|
]
|
||||||
|
return "\n".join(text)
|
||||||
|
|
||||||
|
async def red_delete_data_for_user(self, **kwargs): # pylint: disable=unused-argument
|
||||||
|
"""Nothing to delete."""
|
||||||
|
return
|
||||||
|
|
||||||
|
@commands.Cog.listener('on_message')
|
||||||
|
async def polls_listener(self, message: discord.Message) -> None:
|
||||||
|
if message.guild is None:
|
||||||
|
return self.logger.verbose("Message in direct messages ignored")
|
||||||
|
|
||||||
|
if message.author.bot:
|
||||||
|
return self.logger.verbose("Message from bot ignored")
|
||||||
|
|
||||||
|
if await self.bot.cog_disabled_in_guild(self, message.guild):
|
||||||
|
return self.logger.verbose("Message ignored, cog is disabled in guild %s", message.guild.id)
|
||||||
|
|
||||||
|
guild_config = await self.config.guild(message.guild).all()
|
||||||
|
|
||||||
|
if guild_config['manage_messages'] is True and message.author.guild_permissions.manage_messages:
|
||||||
|
return self.logger.verbose("Message from user with Manage Messages permission ignored")
|
||||||
|
|
||||||
|
if message.channel.id in guild_config['channel_whitelist']:
|
||||||
|
return self.logger.verbose("Message in whitelisted channel %s ignored", message.channel.id)
|
||||||
|
|
||||||
|
if any(role.id in guild_config['role_whitelist'] for role in message.author.roles):
|
||||||
|
return self.logger.verbose("Message from whitelisted role %s ignored", message.author.roles)
|
||||||
|
|
||||||
|
if not message.content and not message.embeds and not message.attachments and not message.stickers:
|
||||||
|
self.logger.trace("Message %s is a poll, attempting to delete", message.id)
|
||||||
|
|
||||||
|
try:
|
||||||
|
await message.delete()
|
||||||
|
except discord.HTTPException as e:
|
||||||
|
return self.logger.error("Failed to delete message: %s", e)
|
||||||
|
|
||||||
|
return self.logger.trace("Deleted poll message %s", message.id)
|
||||||
|
self.logger.verbose("Message %s is not a poll, ignoring", message.id)
|
||||||
|
|
||||||
|
@commands.group(name="antipolls", aliases=["ap"])
|
||||||
|
@commands.guild_only()
|
||||||
|
@commands.admin_or_permissions(manage_guild=True)
|
||||||
|
async def antipolls(self, ctx: commands.Context) -> None:
|
||||||
|
"""Manage AntiPolls settings."""
|
||||||
|
|
||||||
|
@antipolls.group(name="roles")
|
||||||
|
async def antipolls_roles(self, ctx: commands.Context) -> None:
|
||||||
|
"""Manage role whitelist."""
|
||||||
|
|
||||||
|
@antipolls_roles.command(name="add")
|
||||||
|
async def antipolls_roles_add(self, ctx: commands.Context, *roles: discord.Role) -> None:
|
||||||
|
"""Add roles to the whitelist."""
|
||||||
|
async with self.config.guild(ctx.guild).role_whitelist() as role_whitelist:
|
||||||
|
role_whitelist: list
|
||||||
|
failed: list[discord.Role] = []
|
||||||
|
for role in roles:
|
||||||
|
if role.id in role_whitelist:
|
||||||
|
failed.append(role)
|
||||||
|
continue
|
||||||
|
role_whitelist.append(role.id)
|
||||||
|
await ctx.tick()
|
||||||
|
if failed:
|
||||||
|
await ctx.send(f"The following roles were already in the whitelist: {humanize_list([role.mention for role in failed])}", delete_after=10)
|
||||||
|
|
||||||
|
@antipolls_roles.command(name="remove")
|
||||||
|
async def antipolls_roles_remove(self, ctx: commands.Context, *roles: discord.Role) -> None:
|
||||||
|
"""Remove roles from the whitelist."""
|
||||||
|
async with self.config.guild(ctx.guild).role_whitelist() as role_whitelist:
|
||||||
|
role_whitelist: list
|
||||||
|
failed: list[discord.Role] = []
|
||||||
|
for role in roles:
|
||||||
|
if role.id not in role_whitelist:
|
||||||
|
failed.append(role)
|
||||||
|
continue
|
||||||
|
role_whitelist.remove(role.id)
|
||||||
|
await ctx.tick()
|
||||||
|
if failed:
|
||||||
|
await ctx.send(f"The following roles were not in the whitelist: {humanize_list([role.mention for role in failed])}", delete_after=10)
|
||||||
|
|
||||||
|
@antipolls_roles.command(name="list")
|
||||||
|
async def antipolls_roles_list(self, ctx: commands.Context) -> None:
|
||||||
|
"""List roles in the whitelist."""
|
||||||
|
role_whitelist = await self.config.guild(ctx.guild).role_whitelist()
|
||||||
|
if not role_whitelist:
|
||||||
|
return await ctx.send("No roles in the whitelist.")
|
||||||
|
roles = [ctx.guild.get_role(role) for role in role_whitelist]
|
||||||
|
await ctx.send(humanize_list([role.mention for role in roles]))
|
||||||
|
|
||||||
|
@antipolls.group(name="channels")
|
||||||
|
async def antipolls_channels(self, ctx: commands.Context) -> None:
|
||||||
|
"""Manage channel whitelist."""
|
||||||
|
|
||||||
|
@antipolls_channels.command(name="add")
|
||||||
|
async def antipolls_channels_add(self, ctx: commands.Context, *channels: discord.TextChannel) -> None:
|
||||||
|
"""Add channels to the whitelist."""
|
||||||
|
async with self.config.guild(ctx.guild).channel_whitelist() as channel_whitelist:
|
||||||
|
channel_whitelist: list
|
||||||
|
failed: list[discord.TextChannel] = []
|
||||||
|
for channel in channels:
|
||||||
|
if channel.id in channel_whitelist:
|
||||||
|
failed.append(channel)
|
||||||
|
continue
|
||||||
|
channel_whitelist.append(channel.id)
|
||||||
|
await ctx.tick()
|
||||||
|
if failed:
|
||||||
|
await ctx.send(f"The following channels were already in the whitelist: {humanize_list([channel.mention for channel in failed])}", delete_after=10)
|
||||||
|
|
||||||
|
@antipolls_channels.command(name="remove")
|
||||||
|
async def antipolls_channels_remove(self, ctx: commands.Context, *channels: discord.TextChannel) -> None:
|
||||||
|
"""Remove channels from the whitelist."""
|
||||||
|
async with self.config.guild(ctx.guild).channel_whitelist() as channel_whitelist:
|
||||||
|
channel_whitelist: list
|
||||||
|
failed: list[discord.TextChannel] = []
|
||||||
|
for channel in channels:
|
||||||
|
if channel.id not in channel_whitelist:
|
||||||
|
failed.append(channel)
|
||||||
|
continue
|
||||||
|
channel_whitelist.remove(channel.id)
|
||||||
|
await ctx.tick()
|
||||||
|
if failed:
|
||||||
|
await ctx.send(f"The following channels were not in the whitelist: {humanize_list([channel.mention for channel in failed])}", delete_after=10)
|
||||||
|
|
||||||
|
@antipolls_channels.command(name="list")
|
||||||
|
async def antipolls_channels_list(self, ctx: commands.Context) -> None:
|
||||||
|
"""List channels in the whitelist."""
|
||||||
|
channel_whitelist = await self.config.guild(ctx.guild).channel_whitelist()
|
||||||
|
if not channel_whitelist:
|
||||||
|
return await ctx.send("No channels in the whitelist.")
|
||||||
|
channels = [ctx.guild.get_channel(channel) for channel in channel_whitelist]
|
||||||
|
await ctx.send(humanize_list([channel.mention for channel in channels]))
|
||||||
|
|
||||||
|
@antipolls.command(name="managemessages")
|
||||||
|
async def antipolls_managemessages(self, ctx: commands.Context, enabled: bool) -> None:
|
||||||
|
"""Toggle Manage Messages permission check."""
|
||||||
|
await self.config.guild(ctx.guild).manage_messages.set(enabled)
|
||||||
|
await ctx.tick()
|
17
antipolls/info.json
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
{
|
||||||
|
"author" : ["SeaswimmerTheFsh (seasw.)"],
|
||||||
|
"install_msg" : "Thank you for installing AntiPolls!\nYou can find the source code of this cog [here](https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs).",
|
||||||
|
"name" : "AntiPolls",
|
||||||
|
"short" : "AntiPolls deletes messages that contain polls.",
|
||||||
|
"description" : "AntiPolls deletes messages that contain polls, with a configurable per-guild role and channel whitelist and support for default Discord permissions (Manage Messages).",
|
||||||
|
"end_user_data_statement" : "This cog does not store any user data.",
|
||||||
|
"hidden": false,
|
||||||
|
"disabled": false,
|
||||||
|
"min_bot_version": "3.5.0",
|
||||||
|
"min_python_version": [3, 10, 0],
|
||||||
|
"tags": [
|
||||||
|
"automod",
|
||||||
|
"automoderation",
|
||||||
|
"polls"
|
||||||
|
]
|
||||||
|
}
|
|
@ -1,5 +0,0 @@
|
||||||
from .art import Art
|
|
||||||
|
|
||||||
|
|
||||||
async def setup(bot):
|
|
||||||
await bot.add_cog(Art(bot))
|
|
141
art/art.py
|
@ -1,141 +0,0 @@
|
||||||
# _____ _
|
|
||||||
# / ____| (_)
|
|
||||||
# | (___ ___ __ _ _____ ___ _ __ ___ _ __ ___ ___ _ __
|
|
||||||
# \___ \ / _ \/ _` / __\ \ /\ / / | '_ ` _ \| '_ ` _ \ / _ \ '__|
|
|
||||||
# ____) | __/ (_| \__ \\ V V /| | | | | | | | | | | | __/ |
|
|
||||||
# |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_|
|
|
||||||
|
|
||||||
import re
|
|
||||||
|
|
||||||
import discord
|
|
||||||
from redbot.core import app_commands, checks, commands
|
|
||||||
|
|
||||||
from .config import config, register_config
|
|
||||||
|
|
||||||
|
|
||||||
class Art(commands.Cog):
|
|
||||||
"""TODO. Broken until Discord.py 2.4 is released."""
|
|
||||||
|
|
||||||
__author__ = "SeaswimmerTheFsh"
|
|
||||||
__version__ = "0.1.0"
|
|
||||||
|
|
||||||
def __init__(self, bot):
|
|
||||||
self.bot = bot
|
|
||||||
register_config(config)
|
|
||||||
|
|
||||||
async def cog_load(self) -> None:
|
|
||||||
self.add_dynamic_items(ApproveButton)
|
|
||||||
self.add_dynamic_items(DenyButton)
|
|
||||||
|
|
||||||
@app_commands.command()
|
|
||||||
async def art(self, interaction: discord.Interaction, art: discord.Attachment):
|
|
||||||
"""Submit art.
|
|
||||||
|
|
||||||
Parameters
|
|
||||||
-----------
|
|
||||||
art: discord.Attachment
|
|
||||||
Upload your art submission here.
|
|
||||||
"""
|
|
||||||
await interaction.response.defer(ephemeral=True)
|
|
||||||
art_submission_channel = interaction.guild.get_channel(await config.guild(interaction.guild).art_submission_channel())
|
|
||||||
if art_submission_channel is None:
|
|
||||||
await interaction.followup.send("Art submission channel not set. Report this error to the server administrators.", ephemeral=True)
|
|
||||||
return
|
|
||||||
msg = await art_submission_channel.send(f"Art submission from {interaction.user.mention} ({interaction.user.id}):", file=await art.to_file())
|
|
||||||
view = discord.ui.View(timeout=None)
|
|
||||||
view.add_item(ApproveButton(interaction.id, msg, self.bot))
|
|
||||||
view.add_item(DenyButton(interaction.id, msg, self.bot))
|
|
||||||
msg.edit(view=view)
|
|
||||||
await interaction.followup.send("Art submitted.", ephemeral=True)
|
|
||||||
|
|
||||||
@commands.group()
|
|
||||||
@checks.admin_or_permissions(manage_guild=True)
|
|
||||||
async def artset(self, ctx: commands.Context):
|
|
||||||
"""Art submission settings."""
|
|
||||||
|
|
||||||
@artset.command()
|
|
||||||
async def submission(self, ctx: commands.Context, channel: discord.TextChannel):
|
|
||||||
"""Set the art submission channel."""
|
|
||||||
await config.guild(ctx.guild).art_submission_channel.set(channel.id)
|
|
||||||
await ctx.send(f"Art submission channel set to {channel.mention}.")
|
|
||||||
|
|
||||||
@artset.command()
|
|
||||||
async def result(self, ctx: commands.Context, channel: discord.TextChannel):
|
|
||||||
"""Set the art channel."""
|
|
||||||
await config.guild(ctx.guild).art_channel.set(channel.id)
|
|
||||||
await ctx.send(f"Art channel set to {channel.mention}.")
|
|
||||||
|
|
||||||
@artset.command()
|
|
||||||
async def list(self, ctx: commands.Context):
|
|
||||||
"""List all settings."""
|
|
||||||
art_channel = ctx.guild.get_channel(await config.guild(ctx.guild).art_channel())
|
|
||||||
art_submission_channel = ctx.guild.get_channel(await config.guild(ctx.guild).art_submission_channel())
|
|
||||||
if art_channel:
|
|
||||||
response_str = f"Art channel: {art_channel.mention}\n"
|
|
||||||
else:
|
|
||||||
response_str = "Art channel not set.\n"
|
|
||||||
if art_submission_channel:
|
|
||||||
response_str += f"Art submission channel: {art_submission_channel.mention}"
|
|
||||||
else:
|
|
||||||
response_str += "Art submission channel not set."
|
|
||||||
await ctx.send(response_str)
|
|
||||||
|
|
||||||
class ApproveButton(discord.ui.DynamicItem[discord.ui.Button], template=r'button:interaction:(?P<id>[0-9]+)'):
|
|
||||||
def __init__(self, interaction_id: int, msg: discord.Message, bot) -> None:
|
|
||||||
super().__init__(
|
|
||||||
discord.ui.Button(
|
|
||||||
label='Approve',
|
|
||||||
style=discord.ButtonStyle.green,
|
|
||||||
custom_id=f'art:approve:interaction:{interaction_id}',
|
|
||||||
emoji='\N{THUMBS UP SIGN}',
|
|
||||||
)
|
|
||||||
)
|
|
||||||
self.interaction_id: int = interaction_id
|
|
||||||
self.msg = msg
|
|
||||||
self.bot = bot
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
async def from_custom_id(cls, interaction: discord.Interaction, item: discord.ui.Button, match: re.Match[str], /):
|
|
||||||
interaction_id = int(match['id'])
|
|
||||||
return cls(interaction_id)
|
|
||||||
|
|
||||||
async def interaction_check(self, interaction: discord.Interaction) -> bool:
|
|
||||||
return self.bot.is_mod(interaction.user)
|
|
||||||
|
|
||||||
async def callback(self, interaction: discord.Interaction):
|
|
||||||
art_channel = interaction.guild.get_channel(await config.guild(interaction.guild).art_channel())
|
|
||||||
if art_channel is None:
|
|
||||||
await interaction.followup.send("Art channel not set. Report this error to the server administrators.", ephemeral=True)
|
|
||||||
return
|
|
||||||
content = self.msg.content
|
|
||||||
await self.msg.edit(content=content + f"\n\n*This art submission was approved by {interaction.user.mention} ({interaction.user.id}).*")
|
|
||||||
msg: discord.Message = await art_channel.send(f"Art submission from {interaction.user.mention} ({interaction.user.id}):", file=self.msg.attachments[0])
|
|
||||||
await msg.add_reaction('\N{THUMBS UP SIGN}')
|
|
||||||
await msg.add_reaction('\N{THUMBS DOWN SIGN}')
|
|
||||||
|
|
||||||
|
|
||||||
class DenyButton(discord.ui.DynamicItem[discord.ui.Button], template=r'button:interaction:(?P<id>[0-9]+)'):
|
|
||||||
def __init__(self, interaction_id: int, msg: discord.Message, bot) -> None:
|
|
||||||
super().__init__(
|
|
||||||
discord.ui.Button(
|
|
||||||
label='Deny',
|
|
||||||
style=discord.ButtonStyle.red,
|
|
||||||
custom_id=f'art:deny:interaction:{interaction_id}',
|
|
||||||
emoji='\N{THUMBS DOWN SIGN}',
|
|
||||||
)
|
|
||||||
)
|
|
||||||
self.interaction_id: int = interaction_id
|
|
||||||
self.msg = msg
|
|
||||||
self.bot = bot
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
async def from_custom_id(cls, interaction: discord.Interaction, item: discord.ui.Button, match: re.Match[str], /):
|
|
||||||
interaction_id = int(match['id'])
|
|
||||||
return cls(interaction_id)
|
|
||||||
|
|
||||||
async def interaction_check(self, interaction: discord.Interaction) -> bool:
|
|
||||||
return self.bot.is_mod(interaction.user)
|
|
||||||
|
|
||||||
async def callback(self, interaction: discord.Interaction):
|
|
||||||
content = self.msg.content
|
|
||||||
await self.msg.edit(content=content + f"\n\n*This art submission was denied by {interaction.user.mention} ({interaction.user.id}).*")
|
|
|
@ -1,9 +0,0 @@
|
||||||
from redbot.core import Config
|
|
||||||
|
|
||||||
config: Config = Config.get_conf(None, identifier=2347831296542324, cog_name="Art")
|
|
||||||
|
|
||||||
def register_config(config_obj: Config):
|
|
||||||
config_obj.register_guild(
|
|
||||||
art_channel=None,
|
|
||||||
art_submission_channel=None
|
|
||||||
)
|
|
|
@ -1,10 +0,0 @@
|
||||||
{
|
|
||||||
"author" : ["SeaswimmerTheFsh"],
|
|
||||||
"install_msg" : "Thank you for installing Art!\nYou can find the source code of this cog [here](https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs).",
|
|
||||||
"name" : "Art",
|
|
||||||
"short" : "TODO",
|
|
||||||
"description" : "TODO",
|
|
||||||
"end_user_data_statement" : "This cog does not store end user data.",
|
|
||||||
"hidden": true,
|
|
||||||
"disabled": true
|
|
||||||
}
|
|
1557
aurora/aurora.py
|
@ -1,9 +1,11 @@
|
||||||
|
# pylint: disable=duplicate-code
|
||||||
import json
|
import json
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from typing import Dict
|
from typing import Dict
|
||||||
|
|
||||||
from discord import ButtonStyle, Interaction, Message, ui
|
from discord import ButtonStyle, Interaction, Message, ui
|
||||||
from redbot.core import commands
|
from redbot.core import commands
|
||||||
|
from redbot.core.utils.chat_formatting import box, warning
|
||||||
|
|
||||||
from ..utilities.database import connect, create_guild_table, mysql_log
|
from ..utilities.database import connect, create_guild_table, mysql_log
|
||||||
|
|
||||||
|
@ -39,7 +41,7 @@ class ImportAuroraView(ui.View):
|
||||||
await interaction.edit_original_response(content="Importing moderations...")
|
await interaction.edit_original_response(content="Importing moderations...")
|
||||||
|
|
||||||
file = await self.ctx.message.attachments[0].read()
|
file = await self.ctx.message.attachments[0].read()
|
||||||
data: [dict] = sorted(json.loads(file), key=lambda x: x["moderation_id"])
|
data: list[dict] = sorted(json.loads(file), key=lambda x: x["moderation_id"])
|
||||||
|
|
||||||
user_mod_types = ["NOTE", "WARN", "MUTE", "UNMUTE", "KICK", "BAN", "UNBAN"]
|
user_mod_types = ["NOTE", "WARN", "MUTE", "UNMUTE", "KICK", "BAN", "UNBAN"]
|
||||||
|
|
||||||
|
@ -67,10 +69,8 @@ class ImportAuroraView(ui.View):
|
||||||
metadata = {}
|
metadata = {}
|
||||||
else:
|
else:
|
||||||
metadata: Dict[str, any] = json.loads(case["metadata"])
|
metadata: Dict[str, any] = json.loads(case["metadata"])
|
||||||
if not metadata.get('imported_from'):
|
if not metadata.get("imported_from"):
|
||||||
metadata.update({
|
metadata.update({"imported_from": "Aurora"})
|
||||||
'imported_from': 'Aurora'
|
|
||||||
})
|
|
||||||
|
|
||||||
if case["duration"] != "NULL":
|
if case["duration"] != "NULL":
|
||||||
hours, minutes, seconds = map(int, case["duration"].split(":"))
|
hours, minutes, seconds = map(int, case["duration"].split(":"))
|
||||||
|
@ -100,7 +100,9 @@ class ImportAuroraView(ui.View):
|
||||||
await interaction.edit_original_response(content="Import complete.")
|
await interaction.edit_original_response(content="Import complete.")
|
||||||
if failed_cases:
|
if failed_cases:
|
||||||
await interaction.edit_original_response(
|
await interaction.edit_original_response(
|
||||||
content=f"Import complete.\n*Failed to import the following cases:*\n```{failed_cases}```"
|
content="Import complete.\n"
|
||||||
|
+ warning("Failed to import the following cases:\n")
|
||||||
|
+ box(failed_cases)
|
||||||
)
|
)
|
||||||
|
|
||||||
@ui.button(label="No", style=ButtonStyle.danger)
|
@ui.button(label="No", style=ButtonStyle.danger)
|
||||||
|
|
|
@ -1,8 +1,10 @@
|
||||||
|
# pylint: disable=duplicate-code
|
||||||
import json
|
import json
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
|
||||||
from discord import ButtonStyle, Interaction, Message, ui
|
from discord import ButtonStyle, Interaction, Message, ui
|
||||||
from redbot.core import commands
|
from redbot.core import commands
|
||||||
|
from redbot.core.utils.chat_formatting import box, warning
|
||||||
|
|
||||||
from ..utilities.database import connect, create_guild_table, mysql_log
|
from ..utilities.database import connect, create_guild_table, mysql_log
|
||||||
|
|
||||||
|
@ -14,9 +16,13 @@ class ImportGalacticBotView(ui.View):
|
||||||
self.message: Message = message
|
self.message: Message = message
|
||||||
|
|
||||||
@ui.button(label="Yes", style=ButtonStyle.success)
|
@ui.button(label="Yes", style=ButtonStyle.success)
|
||||||
async def import_button_y(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
async def import_button_y(
|
||||||
|
self, interaction: Interaction, button: ui.Button
|
||||||
|
): # pylint: disable=unused-argument
|
||||||
await self.message.delete()
|
await self.message.delete()
|
||||||
await interaction.response.send_message("Deleting original table...", ephemeral=True)
|
await interaction.response.send_message(
|
||||||
|
"Deleting original table...", ephemeral=True
|
||||||
|
)
|
||||||
|
|
||||||
database = connect()
|
database = connect()
|
||||||
cursor = database.cursor()
|
cursor = database.cursor()
|
||||||
|
@ -34,94 +40,94 @@ class ImportGalacticBotView(ui.View):
|
||||||
await interaction.edit_original_response(content="Importing moderations...")
|
await interaction.edit_original_response(content="Importing moderations...")
|
||||||
|
|
||||||
accepted_types = [
|
accepted_types = [
|
||||||
'NOTE',
|
"NOTE",
|
||||||
'WARN',
|
"WARN",
|
||||||
'MUTE',
|
"MUTE",
|
||||||
'UNMUTE',
|
"UNMUTE",
|
||||||
'KICK',
|
"KICK",
|
||||||
'SOFTBAN',
|
"SOFTBAN",
|
||||||
'BAN',
|
"BAN",
|
||||||
'UNBAN',
|
"UNBAN",
|
||||||
'SLOWMODE',
|
"SLOWMODE",
|
||||||
'LOCKDOWN'
|
"LOCKDOWN",
|
||||||
]
|
]
|
||||||
|
|
||||||
file = await self.ctx.message.attachments[0].read()
|
file = await self.ctx.message.attachments[0].read()
|
||||||
data = sorted(json.loads(file), key=lambda x: x['case'])
|
data = sorted(json.loads(file), key=lambda x: x["case"])
|
||||||
|
|
||||||
failed_cases = []
|
failed_cases = []
|
||||||
|
|
||||||
for case in data:
|
for case in data:
|
||||||
if case['type'] not in accepted_types:
|
if case["type"] not in accepted_types:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
timestamp = round(case['timestamp'] / 1000)
|
timestamp = round(case["timestamp"] / 1000)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if case['duration'] is not None and float(case['duration']) != 0:
|
if case["duration"] is not None and float(case["duration"]) != 0:
|
||||||
duration = timedelta(seconds=round(float(case['duration']) / 1000))
|
duration = timedelta(seconds=round(float(case["duration"]) / 1000))
|
||||||
else:
|
else:
|
||||||
duration = 'NULL'
|
duration = "NULL"
|
||||||
except OverflowError:
|
except OverflowError:
|
||||||
failed_cases.append(case['case'])
|
failed_cases.append(case["case"])
|
||||||
continue
|
continue
|
||||||
|
|
||||||
metadata = {
|
metadata = {"imported_from": "GalacticBot"}
|
||||||
'imported_from': 'GalacticBot'
|
|
||||||
}
|
|
||||||
|
|
||||||
if case['type'] == 'SLOWMODE':
|
if case["type"] == "SLOWMODE":
|
||||||
metadata['seconds'] = case['data']['seconds']
|
metadata["seconds"] = case["data"]["seconds"]
|
||||||
|
|
||||||
if case['resolved']:
|
if case["resolved"]:
|
||||||
resolved = 1
|
resolved = 1
|
||||||
resolved_by = None
|
resolved_by = None
|
||||||
resolved_reason = None
|
resolved_reason = None
|
||||||
resolved_timestamp = None
|
resolved_timestamp = None
|
||||||
if case['changes']:
|
if case["changes"]:
|
||||||
for change in case['changes']:
|
for change in case["changes"]:
|
||||||
if change['type'] == 'RESOLVE':
|
if change["type"] == "RESOLVE":
|
||||||
resolved_by = change['staff']
|
resolved_by = change["staff"]
|
||||||
resolved_reason = change['reason']
|
resolved_reason = change["reason"]
|
||||||
resolved_timestamp = round(change['timestamp'] / 1000)
|
resolved_timestamp = round(change["timestamp"] / 1000)
|
||||||
break
|
break
|
||||||
if resolved_by is None:
|
if resolved_by is None:
|
||||||
resolved_by = '?'
|
resolved_by = "?"
|
||||||
if resolved_reason is None:
|
if resolved_reason is None:
|
||||||
resolved_reason = 'Could not get resolve reason during moderation import.'
|
resolved_reason = (
|
||||||
|
"Could not get resolve reason during moderation import."
|
||||||
|
)
|
||||||
if resolved_timestamp is None:
|
if resolved_timestamp is None:
|
||||||
resolved_timestamp = timestamp
|
resolved_timestamp = timestamp
|
||||||
changes = [
|
changes = [
|
||||||
{
|
{
|
||||||
'type': "ORIGINAL",
|
"type": "ORIGINAL",
|
||||||
'reason': case['reason'],
|
"reason": case["reason"],
|
||||||
'user_id': case['executor'],
|
"user_id": case["executor"],
|
||||||
'timestamp': timestamp
|
"timestamp": timestamp,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
'type': "RESOLVE",
|
"type": "RESOLVE",
|
||||||
'reason': resolved_reason,
|
"reason": resolved_reason,
|
||||||
'user_id': resolved_by,
|
"user_id": resolved_by,
|
||||||
'timestamp': resolved_timestamp
|
"timestamp": resolved_timestamp,
|
||||||
}
|
},
|
||||||
]
|
]
|
||||||
else:
|
else:
|
||||||
resolved = 0
|
resolved = 0
|
||||||
resolved_by = 'NULL'
|
resolved_by = "NULL"
|
||||||
resolved_reason = 'NULL'
|
resolved_reason = "NULL"
|
||||||
changes = []
|
changes = []
|
||||||
|
|
||||||
if case['reason'] and case['reason'] != "N/A":
|
if case["reason"] and case["reason"] != "N/A":
|
||||||
reason = case['reason']
|
reason = case["reason"]
|
||||||
else:
|
else:
|
||||||
reason = "NULL"
|
reason = "NULL"
|
||||||
|
|
||||||
await mysql_log(
|
await mysql_log(
|
||||||
self.ctx.guild.id,
|
self.ctx.guild.id,
|
||||||
case['executor'],
|
case["executor"],
|
||||||
case['type'],
|
case["type"],
|
||||||
case['targetType'],
|
case["targetType"],
|
||||||
case['target'],
|
case["target"],
|
||||||
0,
|
0,
|
||||||
duration,
|
duration,
|
||||||
reason,
|
reason,
|
||||||
|
@ -131,15 +137,21 @@ class ImportGalacticBotView(ui.View):
|
||||||
resolved_reason=resolved_reason,
|
resolved_reason=resolved_reason,
|
||||||
changes=changes,
|
changes=changes,
|
||||||
metadata=metadata,
|
metadata=metadata,
|
||||||
database=database
|
database=database,
|
||||||
)
|
)
|
||||||
|
|
||||||
await interaction.edit_original_response(content="Import complete.")
|
await interaction.edit_original_response(content="Import complete.")
|
||||||
if failed_cases:
|
if failed_cases:
|
||||||
await interaction.edit_original_response(content=f"Import complete.\n*Failed to import the following cases:*\n```{failed_cases}```")
|
await interaction.edit_original_response(
|
||||||
|
content="Import complete.\n"
|
||||||
|
+ warning("Failed to import the following cases:\n")
|
||||||
|
+ box(failed_cases)
|
||||||
|
)
|
||||||
|
|
||||||
@ui.button(label="No", style=ButtonStyle.danger)
|
@ui.button(label="No", style=ButtonStyle.danger)
|
||||||
async def import_button_n(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
async def import_button_n(
|
||||||
|
self, interaction: Interaction, button: ui.Button
|
||||||
|
): # pylint: disable=unused-argument
|
||||||
await self.message.edit(content="Import cancelled.", view=None)
|
await self.message.edit(content="Import cancelled.", view=None)
|
||||||
await self.message.delete(10)
|
await self.message.delete(10)
|
||||||
await self.ctx.message.delete(10)
|
await self.ctx.message.delete(10)
|
||||||
|
|
|
@ -1,11 +1,27 @@
|
||||||
{
|
{
|
||||||
"author" : ["SeaswimmerTheFsh"],
|
"author" : ["SeaswimmerTheFsh (seasw.)"],
|
||||||
"install_msg" : "Thank you for installing Aurora!\nYou can find the source code of this cog [here](https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs).",
|
"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).",
|
||||||
"name" : "Aurora",
|
"name" : "Aurora",
|
||||||
"short" : "A full replacement for Red's core Mod cogs.",
|
"short" : "A full replacement for Red's core Mod cogs.",
|
||||||
"description" : "Aurora is a fully-featured moderation system. It is heavily inspired by GalacticBot, and is designed to be a more user-friendly alternative to Red's core Mod cogs. This cog stores all of its data in an SQLite database.",
|
"description" : "Aurora is a fully-featured moderation system. It is heavily inspired by GalacticBot, and is designed to be a more user-friendly alternative to Red's core Mod cogs. This cog stores all of its data in an SQLite database.",
|
||||||
"end_user_data_statement" : "This cog stores the following information:\n- User IDs of accounts who moderate users or are moderated\n- Guild IDs of guilds with the cog enabled\n- Timestamps of moderations\n- Other information relating to moderations",
|
"end_user_data_statement" : "This cog stores the following information:\n- User IDs of accounts who moderate users or are moderated\n- Guild IDs of guilds with the cog enabled\n- Timestamps of moderations\n- Other information relating to moderations",
|
||||||
"requirements": ["humanize", "pytimeparse2"],
|
|
||||||
"hidden": false,
|
"hidden": false,
|
||||||
"disabled": false
|
"disabled": false,
|
||||||
|
"min_bot_version": "3.5.0",
|
||||||
|
"min_python_version": [3, 10, 0],
|
||||||
|
"tags": [
|
||||||
|
"mod",
|
||||||
|
"moderate",
|
||||||
|
"moderation",
|
||||||
|
"warn",
|
||||||
|
"warning",
|
||||||
|
"mute",
|
||||||
|
"timeout",
|
||||||
|
"unmute",
|
||||||
|
"untimeout",
|
||||||
|
"kick",
|
||||||
|
"ban",
|
||||||
|
"unban",
|
||||||
|
"tempban"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
|
0
aurora/menus/__init__.py
Normal file
43
aurora/menus/addrole.py
Normal file
|
@ -0,0 +1,43 @@
|
||||||
|
from discord import ButtonStyle, Interaction, ui
|
||||||
|
from redbot.core import commands
|
||||||
|
from redbot.core.utils.chat_formatting import error
|
||||||
|
|
||||||
|
from aurora.utilities.config import config
|
||||||
|
from aurora.utilities.factory import addrole_embed
|
||||||
|
|
||||||
|
|
||||||
|
class Addrole(ui.View):
|
||||||
|
def __init__(self, ctx: commands.Context):
|
||||||
|
super().__init__()
|
||||||
|
self.ctx = ctx
|
||||||
|
|
||||||
|
@ui.select(cls=ui.RoleSelect, placeholder="Select a role", min_values=0, max_values=25)
|
||||||
|
async def addrole_select(self, interaction: Interaction, select: ui.RoleSelect):
|
||||||
|
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||||
|
await interaction.response.send_message(error("You must have the manage guild permission to add roles to the addrole whitelist."), ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.response.defer()
|
||||||
|
async with config.guild(self.ctx.guild).addrole_whitelist() as addrole_whitelist:
|
||||||
|
addrole_whitelist: list # type hint
|
||||||
|
for value in select.values:
|
||||||
|
if value.id in addrole_whitelist:
|
||||||
|
addrole_whitelist.remove(value.id)
|
||||||
|
else:
|
||||||
|
addrole_whitelist.append(value.id)
|
||||||
|
await interaction.message.edit(embed=await addrole_embed(self.ctx))
|
||||||
|
|
||||||
|
@ui.button(label="Clear", style=ButtonStyle.red, row=1)
|
||||||
|
async def clear(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
||||||
|
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||||
|
await interaction.response.send_message(error("You must have the manage guild permission to clear the guild's addrole whitelist."), ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.response.defer()
|
||||||
|
await config.guild(self.ctx.guild).addrole_whitelist.clear()
|
||||||
|
await interaction.message.edit(embed=await addrole_embed(self.ctx))
|
||||||
|
|
||||||
|
@ui.button(label="Close", style=ButtonStyle.gray)
|
||||||
|
async def close(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
||||||
|
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||||
|
await interaction.response.send_message(error("You can't do that!"), ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.message.delete()
|
135
aurora/menus/guild.py
Normal file
|
@ -0,0 +1,135 @@
|
||||||
|
from discord import ButtonStyle, Interaction, ui
|
||||||
|
from redbot.core import commands
|
||||||
|
|
||||||
|
from aurora.utilities.config import config
|
||||||
|
from aurora.utilities.factory import guild_embed
|
||||||
|
from aurora.utilities.utils import create_pagesize_options
|
||||||
|
|
||||||
|
|
||||||
|
class Guild(ui.View):
|
||||||
|
def __init__(self, ctx: commands.Context):
|
||||||
|
super().__init__()
|
||||||
|
self.ctx = ctx
|
||||||
|
|
||||||
|
@ui.button(label="Show Moderator", style=ButtonStyle.green, row=0)
|
||||||
|
async def show_moderator(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
||||||
|
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||||
|
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.response.defer()
|
||||||
|
current_setting = await config.guild(interaction.guild).show_moderator
|
||||||
|
await config.guild(interaction.guild).show_moderator.set(not current_setting)
|
||||||
|
await interaction.message.edit(embed=await guild_embed(self.ctx))
|
||||||
|
|
||||||
|
@ui.button(label="Use Discord Permissions", style=ButtonStyle.green, row=0)
|
||||||
|
async def use_discord_permissions(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
||||||
|
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||||
|
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.response.defer()
|
||||||
|
current_setting = await config.guild(interaction.guild).use_discord_permissions()
|
||||||
|
await config.guild(interaction.guild).use_discord_permissions.set(not current_setting)
|
||||||
|
await interaction.message.edit(embed=await guild_embed(self.ctx))
|
||||||
|
|
||||||
|
@ui.button(label="Respect Hierarchy", style=ButtonStyle.green, row=0)
|
||||||
|
async def respect_heirarchy(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
||||||
|
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||||
|
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.response.defer()
|
||||||
|
current_setting = await config.guild(interaction.guild).respect_hierarchy()
|
||||||
|
await config.guild(interaction.guild).respect_hierarchy.set(not current_setting)
|
||||||
|
await interaction.message.edit(embed=await guild_embed(self.ctx))
|
||||||
|
|
||||||
|
@ui.button(label="Ignore Modlog", style=ButtonStyle.green, row=0)
|
||||||
|
async def ignore_modlog(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
||||||
|
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||||
|
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.response.defer()
|
||||||
|
current_setting = await config.guild(interaction.guild).ignore_modlog()
|
||||||
|
await config.guild(interaction.guild).ignore_modlog.set(not current_setting)
|
||||||
|
await interaction.message.edit(embed=await guild_embed(self.ctx))
|
||||||
|
|
||||||
|
@ui.button(label="Ignore Other Bots", style=ButtonStyle.green, row=0)
|
||||||
|
async def ignore_other_bots(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
||||||
|
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||||
|
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.response.defer()
|
||||||
|
current_setting = await config.guild(interaction.guild).ignore_other_bots()
|
||||||
|
await config.guild(interaction.guild).ignore_other_bots.set(not current_setting)
|
||||||
|
await interaction.message.edit(embed=await guild_embed(self.ctx))
|
||||||
|
|
||||||
|
@ui.button(label="DM Users", style=ButtonStyle.green, row=1)
|
||||||
|
async def dm_users(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
||||||
|
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||||
|
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.response.defer()
|
||||||
|
current_setting = await config.guild(interaction.guild).dm_users()
|
||||||
|
await config.guild(interaction.guild).dm_users.set(not current_setting)
|
||||||
|
await interaction.message.edit(embed=await guild_embed(self.ctx))
|
||||||
|
|
||||||
|
@ui.button(label="Auto Evidence Format", style=ButtonStyle.green, row=1)
|
||||||
|
async def auto_evidenceformat(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
||||||
|
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||||
|
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.response.defer()
|
||||||
|
current_setting = await config.guild(interaction.guild).auto_evidenceformat()
|
||||||
|
await config.guild(interaction.guild).auto_evidenceformat.set(not current_setting)
|
||||||
|
await interaction.message.edit(embed=await guild_embed(self.ctx))
|
||||||
|
|
||||||
|
@ui.button(label="Ephemeral", style=ButtonStyle.green, row=1)
|
||||||
|
async def ephemeral(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
||||||
|
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||||
|
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.response.defer()
|
||||||
|
current_setting = await config.guild(interaction.guild).history_ephemeral()
|
||||||
|
await config.guild(interaction.guild).history_ephemeral.set(not current_setting)
|
||||||
|
await interaction.message.edit(embed=await guild_embed(self.ctx))
|
||||||
|
|
||||||
|
@ui.button(label="History Inline", style=ButtonStyle.green, row=1)
|
||||||
|
async def inline(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
||||||
|
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||||
|
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.response.defer()
|
||||||
|
current_setting = await config.guild(interaction.guild).history_inline()
|
||||||
|
await config.guild(interaction.guild).history_inline.set(not current_setting)
|
||||||
|
await interaction.message.edit(embed=await guild_embed(self.ctx))
|
||||||
|
|
||||||
|
@ui.select(placeholder="History Pagesize", options=create_pagesize_options(), row=2)
|
||||||
|
async def pagesize(self, interaction: Interaction, select: ui.Select,):
|
||||||
|
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||||
|
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
|
||||||
|
return
|
||||||
|
if select.values[0] == "default":
|
||||||
|
await config.guild(interaction.guild).history_pagesize.clear()
|
||||||
|
else:
|
||||||
|
await config.guild(interaction.guild).history_pagesize.set(int(select.values[0]))
|
||||||
|
await interaction.response.defer()
|
||||||
|
await interaction.message.edit(embed=await guild_embed(self.ctx))
|
||||||
|
|
||||||
|
@ui.select(placeholder="History Inline Pagesize", options=create_pagesize_options(), row=3)
|
||||||
|
async def inline_pagesize(self, interaction: Interaction, select: ui.Select,):
|
||||||
|
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||||
|
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
|
||||||
|
return
|
||||||
|
if select.values[0] == "default":
|
||||||
|
await config.guild(interaction.guild).history_inline_pagesize.clear()
|
||||||
|
else:
|
||||||
|
await config.guild(interaction.guild).history_inline_pagesize.set(int(select.values[0]))
|
||||||
|
await interaction.response.defer()
|
||||||
|
await interaction.message.edit(embed=await guild_embed(self.ctx))
|
||||||
|
|
||||||
|
@ui.select(placeholder="Log Channel", cls=ui.ChannelSelect, row=4)
|
||||||
|
async def log_channel(self, interaction: Interaction, select: ui.ChannelSelect):
|
||||||
|
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||||
|
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.response.defer()
|
||||||
|
await config.guild(interaction.guild).log_channel.set(select.values[0].id)
|
||||||
|
await interaction.message.edit(embed=await guild_embed(self.ctx))
|
43
aurora/menus/immune.py
Normal file
|
@ -0,0 +1,43 @@
|
||||||
|
from discord import ButtonStyle, Interaction, ui
|
||||||
|
from redbot.core import commands
|
||||||
|
from redbot.core.utils.chat_formatting import error
|
||||||
|
|
||||||
|
from aurora.utilities.config import config
|
||||||
|
from aurora.utilities.factory import immune_embed
|
||||||
|
|
||||||
|
|
||||||
|
class Immune(ui.View):
|
||||||
|
def __init__(self, ctx: commands.Context):
|
||||||
|
super().__init__()
|
||||||
|
self.ctx = ctx
|
||||||
|
|
||||||
|
@ui.select(cls=ui.RoleSelect, placeholder="Select a role", min_values=0, max_values=25)
|
||||||
|
async def immune_select(self, interaction: Interaction, select: ui.RoleSelect):
|
||||||
|
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||||
|
await interaction.response.send_message(error("You must have the manage guild permission to add immune roles."), ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.response.defer()
|
||||||
|
async with config.guild(self.ctx.guild).immune_roles() as immune_roles:
|
||||||
|
immune_roles: list # type hint
|
||||||
|
for value in select.values:
|
||||||
|
if value.id in immune_roles:
|
||||||
|
immune_roles.remove(value.id)
|
||||||
|
else:
|
||||||
|
immune_roles.append(value.id)
|
||||||
|
await interaction.message.edit(embed=await immune_embed(self.ctx))
|
||||||
|
|
||||||
|
@ui.button(label="Clear", style=ButtonStyle.red, row=1)
|
||||||
|
async def clear(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
||||||
|
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||||
|
await interaction.response.send_message(error("You must have the manage guild permission to clear the guild's immune roles."), ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.response.defer()
|
||||||
|
await config.guild(self.ctx.guild).immune_roles.clear()
|
||||||
|
await interaction.message.edit(embed=await immune_embed(self.ctx))
|
||||||
|
|
||||||
|
@ui.button(label="Close", style=ButtonStyle.gray)
|
||||||
|
async def close(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
||||||
|
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||||
|
await interaction.response.send_message(error("You can't do that!"), ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.message.delete()
|
81
aurora/menus/overrides.py
Normal file
|
@ -0,0 +1,81 @@
|
||||||
|
from discord import ButtonStyle, Interaction, ui
|
||||||
|
from redbot.core import commands
|
||||||
|
|
||||||
|
from aurora.utilities.config import config
|
||||||
|
from aurora.utilities.factory import overrides_embed
|
||||||
|
from aurora.utilities.utils import create_pagesize_options
|
||||||
|
|
||||||
|
|
||||||
|
class Overrides(ui.View):
|
||||||
|
def __init__(self, ctx: commands.Context):
|
||||||
|
super().__init__()
|
||||||
|
self.ctx = ctx
|
||||||
|
|
||||||
|
@ui.button(label="Auto Evidence Format", style=ButtonStyle.green, row=0)
|
||||||
|
async def auto_evidenceformat(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
||||||
|
if self.ctx.author != interaction.user:
|
||||||
|
await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.response.defer()
|
||||||
|
current_setting = await config.user(self.ctx.author).auto_evidenceformat()
|
||||||
|
if current_setting is False:
|
||||||
|
await config.user(self.ctx.author).auto_evidenceformat.clear()
|
||||||
|
elif current_setting is None:
|
||||||
|
await config.user(self.ctx.author).auto_evidenceformat.set(True)
|
||||||
|
else:
|
||||||
|
await config.user(self.ctx.author).auto_evidenceformat.set(False)
|
||||||
|
await interaction.message.edit(embed=await overrides_embed(self.ctx))
|
||||||
|
|
||||||
|
@ui.button(label="Ephemeral", style=ButtonStyle.green, row=0)
|
||||||
|
async def ephemeral(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
||||||
|
if self.ctx.author != interaction.user:
|
||||||
|
await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.response.defer()
|
||||||
|
current_setting = await config.user(self.ctx.author).history_ephemeral()
|
||||||
|
if current_setting is False:
|
||||||
|
await config.user(self.ctx.author).history_ephemeral.clear()
|
||||||
|
elif current_setting is None:
|
||||||
|
await config.user(self.ctx.author).history_ephemeral.set(True)
|
||||||
|
else:
|
||||||
|
await config.user(self.ctx.author).history_ephemeral.set(False)
|
||||||
|
await interaction.message.edit(embed=await overrides_embed(self.ctx))
|
||||||
|
|
||||||
|
@ui.button(label="Inline", style=ButtonStyle.green, row=0)
|
||||||
|
async def inline(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
||||||
|
if self.ctx.author != interaction.user:
|
||||||
|
await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.response.defer()
|
||||||
|
current_setting = await config.user(self.ctx.author).history_inline()
|
||||||
|
if current_setting is False:
|
||||||
|
await config.user(self.ctx.author).history_inline.clear()
|
||||||
|
elif current_setting is None:
|
||||||
|
await config.user(self.ctx.author).history_inline.set(True)
|
||||||
|
else:
|
||||||
|
await config.user(self.ctx.author).history_inline.set(False)
|
||||||
|
await interaction.message.edit(embed=await overrides_embed(self.ctx))
|
||||||
|
|
||||||
|
@ui.select(placeholder="Inline Pagesize", options=create_pagesize_options(), row=1)
|
||||||
|
async def inline_pagesize(self, interaction: Interaction, select: ui.Select,):
|
||||||
|
if self.ctx.author != interaction.user:
|
||||||
|
await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.response.defer()
|
||||||
|
if select.values[0] == "default":
|
||||||
|
await config.user(self.ctx.author).history_inline_pagesize.clear()
|
||||||
|
else:
|
||||||
|
await config.user(self.ctx.author).history_inline_pagesize.set(int(select.values[0]))
|
||||||
|
await interaction.message.edit(embed=await overrides_embed(self.ctx))
|
||||||
|
|
||||||
|
@ui.select(placeholder="Pagesize", options=create_pagesize_options(), row=2)
|
||||||
|
async def pagesize(self, interaction: Interaction, select: ui.Select,):
|
||||||
|
if self.ctx.author != interaction.user:
|
||||||
|
await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True)
|
||||||
|
return
|
||||||
|
await interaction.response.defer()
|
||||||
|
if select.values[0] == "default":
|
||||||
|
await config.user(self.ctx.author).history_pagesize.clear()
|
||||||
|
else:
|
||||||
|
await config.user(self.ctx.author).history_pagesize.set(int(select.values[0]))
|
||||||
|
await interaction.message.edit(embed=await overrides_embed(self.ctx))
|
|
@ -2,25 +2,28 @@ from redbot.core import Config
|
||||||
|
|
||||||
config: Config = Config.get_conf(None, identifier=481923957134912, cog_name="Aurora")
|
config: Config = Config.get_conf(None, identifier=481923957134912, cog_name="Aurora")
|
||||||
|
|
||||||
|
|
||||||
def register_config(config_obj: Config):
|
def register_config(config_obj: Config):
|
||||||
config_obj.register_guild(
|
config_obj.register_guild(
|
||||||
show_moderator = True,
|
show_moderator=True,
|
||||||
use_discord_permissions = True,
|
use_discord_permissions=True,
|
||||||
ignore_other_bots = True,
|
respect_hierarchy=True,
|
||||||
dm_users = True,
|
ignore_modlog=True,
|
||||||
log_channel = " ",
|
ignore_other_bots=True,
|
||||||
immune_roles = [],
|
dm_users=True,
|
||||||
history_ephemeral = False,
|
log_channel=" ",
|
||||||
history_inline = False,
|
immune_roles=[],
|
||||||
history_pagesize = 5,
|
history_ephemeral=False,
|
||||||
history_inline_pagesize = 6,
|
history_inline=False,
|
||||||
auto_evidenceformat = False,
|
history_pagesize=5,
|
||||||
blacklist_roles = []
|
history_inline_pagesize=6,
|
||||||
|
auto_evidenceformat=False,
|
||||||
|
addrole_whitelist=[],
|
||||||
)
|
)
|
||||||
config_obj.register_user(
|
config_obj.register_user(
|
||||||
history_ephemeral = None,
|
history_ephemeral=None,
|
||||||
history_inline = None,
|
history_inline=None,
|
||||||
history_pagesize = None,
|
history_pagesize=None,
|
||||||
history_inline_pagesize = None,
|
history_inline_pagesize=None,
|
||||||
auto_evidenceformat = None
|
auto_evidenceformat=None,
|
||||||
)
|
)
|
||||||
|
|
|
@ -1,21 +1,23 @@
|
||||||
# pylint: disable=cyclic-import
|
# pylint: disable=cyclic-import
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import time
|
|
||||||
import sqlite3
|
import sqlite3
|
||||||
|
import time
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
from discord import Guild
|
from discord import Guild
|
||||||
from redbot.core import data_manager
|
from redbot.core import data_manager
|
||||||
|
|
||||||
from .logger import logger
|
from .logger import logger
|
||||||
from .utils import generate_dict, get_next_case_number, convert_timedelta_to_str
|
from .utils import (convert_timedelta_to_str, generate_dict,
|
||||||
|
get_next_case_number)
|
||||||
|
|
||||||
|
|
||||||
def connect() -> sqlite3.Connection:
|
def connect() -> sqlite3.Connection:
|
||||||
"""Connects to the SQLite database, and returns a connection object."""
|
"""Connects to the SQLite database, and returns a connection object."""
|
||||||
try:
|
try:
|
||||||
connection = sqlite3.connect(database=data_manager.cog_data_path(raw_name='Aurora') / 'aurora.db')
|
connection = sqlite3.connect(
|
||||||
|
database=data_manager.cog_data_path(raw_name="Aurora") / "aurora.db"
|
||||||
|
)
|
||||||
return connection
|
return connection
|
||||||
|
|
||||||
except sqlite3.OperationalError as e:
|
except sqlite3.OperationalError as e:
|
||||||
|
@ -85,8 +87,8 @@ async def create_guild_table(guild: Guild):
|
||||||
"NULL",
|
"NULL",
|
||||||
"NULL",
|
"NULL",
|
||||||
0,
|
0,
|
||||||
json.dumps([]), # pylint: disable=dangerous-default-value
|
json.dumps([]),
|
||||||
json.dumps({}), # pylint: disable=dangerous-default-value
|
json.dumps({}),
|
||||||
)
|
)
|
||||||
cursor.execute(insert_query, insert_values)
|
cursor.execute(insert_query, insert_values)
|
||||||
|
|
||||||
|
@ -102,7 +104,6 @@ async def create_guild_table(guild: Guild):
|
||||||
database.close()
|
database.close()
|
||||||
|
|
||||||
|
|
||||||
# pylint: disable=dangerous-default-value
|
|
||||||
async def mysql_log(
|
async def mysql_log(
|
||||||
guild_id: str,
|
guild_id: str,
|
||||||
author_id: str,
|
author_id: str,
|
||||||
|
@ -118,8 +119,8 @@ async def mysql_log(
|
||||||
resolved_by: str = None,
|
resolved_by: str = None,
|
||||||
resolved_reason: str = None,
|
resolved_reason: str = None,
|
||||||
expired: bool = None,
|
expired: bool = None,
|
||||||
changes: list = [],
|
changes: list = None,
|
||||||
metadata: dict = {},
|
metadata: dict = None,
|
||||||
) -> int:
|
) -> int:
|
||||||
if not timestamp:
|
if not timestamp:
|
||||||
timestamp = int(time.time())
|
timestamp = int(time.time())
|
||||||
|
@ -169,8 +170,8 @@ async def mysql_log(
|
||||||
resolved_by,
|
resolved_by,
|
||||||
resolved_reason,
|
resolved_reason,
|
||||||
expired,
|
expired,
|
||||||
json.dumps(changes),
|
json.dumps(changes if changes else []),
|
||||||
json.dumps(metadata),
|
json.dumps(metadata if metadata else {}),
|
||||||
)
|
)
|
||||||
cursor.execute(sql, val)
|
cursor.execute(sql, val)
|
||||||
|
|
||||||
|
|
|
@ -1,212 +0,0 @@
|
||||||
# pylint: disable=cyclic-import
|
|
||||||
|
|
||||||
from datetime import datetime, timedelta
|
|
||||||
|
|
||||||
import humanize
|
|
||||||
from discord import Color, Embed, Guild, Interaction, InteractionMessage
|
|
||||||
|
|
||||||
from .config import config
|
|
||||||
from .utils import fetch_channel_dict, fetch_user_dict, get_next_case_number
|
|
||||||
|
|
||||||
|
|
||||||
async def embed_factory(embed_type: str, color: Color, /, interaction: Interaction = None, case_dict: dict = None, guild: Guild = None, reason: str = None, moderation_type: str = None, response: InteractionMessage = None, duration: timedelta = None, resolved: bool = False):
|
|
||||||
"""This method creates an embed from set parameters, meant for either moderation logging or contacting the moderated user.
|
|
||||||
|
|
||||||
Valid arguments for 'embed_type':
|
|
||||||
- 'message'
|
|
||||||
- 'log'
|
|
||||||
- 'case'
|
|
||||||
- 'changes'
|
|
||||||
|
|
||||||
Required arguments for 'message':
|
|
||||||
- guild
|
|
||||||
- reason
|
|
||||||
- moderation_type
|
|
||||||
- response
|
|
||||||
- duration (optional)
|
|
||||||
|
|
||||||
Required arguments for 'log':
|
|
||||||
- interaction
|
|
||||||
- case_dict
|
|
||||||
- resolved (optional)
|
|
||||||
|
|
||||||
Required arguments for 'case', 'changes', and `evidenceformat`:
|
|
||||||
- interaction
|
|
||||||
- case_dict"""
|
|
||||||
codeblock = '```'
|
|
||||||
if embed_type == 'message':
|
|
||||||
|
|
||||||
if moderation_type in ["kicked", "banned", "tempbanned", "unbanned"]:
|
|
||||||
guild_name = guild.name
|
|
||||||
else:
|
|
||||||
guild_name = f"[{guild.name}]({response.jump_url})"
|
|
||||||
|
|
||||||
if moderation_type in ["tempbanned", "muted"] and duration:
|
|
||||||
embed_duration = f" for {humanize.precisedelta(duration)}"
|
|
||||||
else:
|
|
||||||
embed_duration = ""
|
|
||||||
|
|
||||||
if moderation_type == "note":
|
|
||||||
embed_desc = "received a"
|
|
||||||
else:
|
|
||||||
embed_desc = "been"
|
|
||||||
|
|
||||||
embed = Embed(title=str.title(moderation_type), description=f"You have {embed_desc} {moderation_type}{embed_duration} in {guild_name}.", color=color, timestamp=datetime.now())
|
|
||||||
|
|
||||||
if await config.guild(guild).show_moderator():
|
|
||||||
embed.add_field(name='Moderator', value=f"`{interaction.user.name} ({interaction.user.id})`", inline=False)
|
|
||||||
|
|
||||||
embed.add_field(name='Reason', value=f"`{reason}`", inline=False)
|
|
||||||
|
|
||||||
if guild.icon.url is not None:
|
|
||||||
embed.set_author(name=guild.name, icon_url=guild.icon.url)
|
|
||||||
else:
|
|
||||||
embed.set_author(name=guild.name)
|
|
||||||
|
|
||||||
embed.set_footer(text=f"Case #{await get_next_case_number(guild.id):,}", icon_url="https://cdn.discordapp.com/attachments/1070822161389994054/1159469476773904414/arrow-right-circle-icon-512x512-2p1e2aaw.png?ex=65312319&is=651eae19&hm=3cebdd28e805c13a79ec48ef87c32ca532ffa6b9ede2e48d0cf8e5e81f3a6818&")
|
|
||||||
|
|
||||||
return embed
|
|
||||||
|
|
||||||
if embed_type == 'case':
|
|
||||||
if case_dict['target_type'] == 'USER':
|
|
||||||
target_user = await fetch_user_dict(interaction, case_dict['target_id'])
|
|
||||||
target_name = f"`{target_user['name']}`" if target_user['discriminator'] == "0" else f"`{target_user['name']}#{target_user['discriminator']}`"
|
|
||||||
elif case_dict['target_type'] == 'CHANNEL':
|
|
||||||
target_user = await fetch_channel_dict(interaction, case_dict['target_id'])
|
|
||||||
if target_user['mention']:
|
|
||||||
target_name = f"{target_user['mention']}"
|
|
||||||
else:
|
|
||||||
target_name = f"`{target_user['name']}`"
|
|
||||||
|
|
||||||
moderator_user = await fetch_user_dict(interaction, case_dict['moderator_id'])
|
|
||||||
moderator_name = f"`{moderator_user['name']}`" if moderator_user['discriminator'] == "0" else f"`{moderator_user['name']}#{moderator_user['discriminator']}`"
|
|
||||||
|
|
||||||
embed = Embed(title=f"📕 Case #{case_dict['moderation_id']:,}", color=color)
|
|
||||||
embed.description = f"**Type:** {str.title(case_dict['moderation_type'])}\n**Target:** {target_name} ({target_user['id']})\n**Moderator:** {moderator_name} ({moderator_user['id']})\n**Resolved:** {bool(case_dict['resolved'])}\n**Timestamp:** <t:{case_dict['timestamp']}> | <t:{case_dict['timestamp']}:R>"
|
|
||||||
|
|
||||||
if case_dict['duration'] != 'NULL':
|
|
||||||
td = timedelta(**{unit: int(val) for unit, val in zip(["hours", "minutes", "seconds"], case_dict["duration"].split(":"))})
|
|
||||||
duration_embed = f"{humanize.precisedelta(td)} | <t:{case_dict['end_timestamp']}:R>" if bool(case_dict['expired']) is False else str(humanize.precisedelta(td))
|
|
||||||
embed.description += f"\n**Duration:** {duration_embed}\n**Expired:** {bool(case_dict['expired'])}"
|
|
||||||
|
|
||||||
embed.description += f"\n**Changes:** {len(case_dict['changes']) - 1}" if case_dict['changes'] else "\n**Changes:** 0"
|
|
||||||
|
|
||||||
if case_dict['metadata']:
|
|
||||||
if case_dict['metadata']['imported_from']:
|
|
||||||
embed.description += f"\n**Imported From:** {case_dict['metadata']['imported_from']}"
|
|
||||||
|
|
||||||
embed.add_field(name='Reason', value=f"{codeblock}{case_dict['reason']}{codeblock}", inline=False)
|
|
||||||
|
|
||||||
if case_dict['resolved'] == 1:
|
|
||||||
resolved_user = await fetch_user_dict(interaction, case_dict['resolved_by'])
|
|
||||||
resolved_name = f"`{resolved_user['name']}`" if resolved_user['discriminator'] == "0" else f"`{resolved_user['name']}#{resolved_user['discriminator']}`"
|
|
||||||
embed.add_field(name='Resolve Reason', value=f"Resolved by {resolved_name} ({resolved_user['id']}) for:\n{codeblock}{case_dict['resolve_reason']}{codeblock}", inline=False)
|
|
||||||
|
|
||||||
return embed
|
|
||||||
|
|
||||||
if embed_type == 'changes':
|
|
||||||
embed = Embed(title=f"📕 Case #{case_dict['moderation_id']:,} Changes", color=color)
|
|
||||||
|
|
||||||
memory_dict = {}
|
|
||||||
|
|
||||||
if case_dict['changes']:
|
|
||||||
for change in case_dict['changes']:
|
|
||||||
if change['user_id'] not in memory_dict:
|
|
||||||
memory_dict[str(change['user_id'])] = await fetch_user_dict(interaction, change['user_id'])
|
|
||||||
|
|
||||||
user = memory_dict[str(change['user_id'])]
|
|
||||||
name = user['name'] if user['discriminator'] == "0" else f"{user['name']}#{user['discriminator']}"
|
|
||||||
|
|
||||||
timestamp = f"<t:{change['timestamp']}> | <t:{change['timestamp']}:R>"
|
|
||||||
|
|
||||||
if change['type'] == 'ORIGINAL':
|
|
||||||
embed.add_field(name='Original', value=f"**User:** `{name}` ({user['id']})\n**Reason:** {change['reason']}\n**Timestamp:** {timestamp}", inline=False)
|
|
||||||
|
|
||||||
elif change['type'] == 'EDIT':
|
|
||||||
embed.add_field(name='Edit', value=f"**User:** `{name}` ({user['id']})\n**Reason:** {change['reason']}\n**Timestamp:** {timestamp}", inline=False)
|
|
||||||
|
|
||||||
elif change['type'] == 'RESOLVE':
|
|
||||||
embed.add_field(name='Resolve', value=f"**User:** `{name}` ({user['id']})\n**Reason:** {change['reason']}\n**Timestamp:** {timestamp}", inline=False)
|
|
||||||
|
|
||||||
else:
|
|
||||||
embed.description = "*No changes have been made to this case.* 🙁"
|
|
||||||
|
|
||||||
return embed
|
|
||||||
|
|
||||||
if embed_type == 'evidenceformat':
|
|
||||||
if case_dict['target_type'] == 'USER':
|
|
||||||
target_user = await fetch_user_dict(interaction, case_dict['target_id'])
|
|
||||||
target_name = target_user['name'] if target_user['discriminator'] == "0" else f"{target_user['name']}#{target_user['discriminator']}"
|
|
||||||
|
|
||||||
elif case_dict['target_type'] == 'CHANNEL':
|
|
||||||
target_user = await fetch_channel_dict(interaction, case_dict['target_id'])
|
|
||||||
target_name = target_user['name']
|
|
||||||
|
|
||||||
moderator_user = await fetch_user_dict(interaction, case_dict['moderator_id'])
|
|
||||||
moderator_name = moderator_user['name'] if moderator_user['discriminator'] == "0" else f"{moderator_user['name']}#{moderator_user['discriminator']}"
|
|
||||||
|
|
||||||
content = f"{codeblock}prolog\nCase: {case_dict['moderation_id']:,} ({str.title(case_dict['moderation_type'])})\nTarget: {target_name} ({target_user['id']})\nModerator: {moderator_name} ({moderator_user['id']})"
|
|
||||||
|
|
||||||
if case_dict['duration'] != 'NULL':
|
|
||||||
hours, minutes, seconds = map(int, case_dict['duration'].split(':'))
|
|
||||||
td = timedelta(hours=hours, minutes=minutes, seconds=seconds)
|
|
||||||
content += f"\nDuration: {humanize.precisedelta(td)}"
|
|
||||||
|
|
||||||
content += f"\nReason: {case_dict['reason']}{codeblock}"
|
|
||||||
|
|
||||||
return content
|
|
||||||
|
|
||||||
if embed_type == 'log':
|
|
||||||
if resolved:
|
|
||||||
if case_dict['target_type'] == 'USER':
|
|
||||||
target_user = await fetch_user_dict(interaction, case_dict['target_id'])
|
|
||||||
target_name = f"`{target_user['name']}`" if target_user['discriminator'] == "0" else f"`{target_user['name']}#{target_user['discriminator']}`"
|
|
||||||
elif case_dict['target_type'] == 'CHANNEL':
|
|
||||||
target_user = await fetch_channel_dict(interaction, case_dict['target_id'])
|
|
||||||
if target_user['mention']:
|
|
||||||
target_name = f"{target_user['mention']}"
|
|
||||||
else:
|
|
||||||
target_name = f"`{target_user['name']}`"
|
|
||||||
|
|
||||||
moderator_user = await fetch_user_dict(interaction, case_dict['moderator_id'])
|
|
||||||
moderator_name = f"`{moderator_user['name']}`" if moderator_user['discriminator'] == "0" else f"`{moderator_user['name']}#{moderator_user['discriminator']}`"
|
|
||||||
|
|
||||||
embed = Embed(title=f"📕 Case #{case_dict['moderation_id']:,} Resolved", color=color)
|
|
||||||
|
|
||||||
embed.description = f"**Type:** {str.title(case_dict['moderation_type'])}\n**Target:** {target_name} ({target_user['id']})\n**Moderator:** {moderator_name} ({moderator_user['id']})\n**Timestamp:** <t:{case_dict['timestamp']}> | <t:{case_dict['timestamp']}:R>"
|
|
||||||
|
|
||||||
if case_dict['duration'] != 'NULL':
|
|
||||||
td = timedelta(**{unit: int(val) for unit, val in zip(["hours", "minutes", "seconds"], case_dict["duration"].split(":"))})
|
|
||||||
duration_embed = f"{humanize.precisedelta(td)} | <t:{case_dict['end_timestamp']}:R>" if case_dict["expired"] == '0' else str(humanize.precisedelta(td))
|
|
||||||
embed.description = embed.description + f"\n**Duration:** {duration_embed}\n**Expired:** {bool(case_dict['expired'])}"
|
|
||||||
|
|
||||||
embed.add_field(name='Reason', value=f"{codeblock}{case_dict['reason']}{codeblock}", inline=False)
|
|
||||||
|
|
||||||
resolved_user = await fetch_user_dict(interaction, case_dict['resolved_by'])
|
|
||||||
resolved_name = resolved_user['name'] if resolved_user['discriminator'] == "0" else f"{resolved_user['name']}#{resolved_user['discriminator']}"
|
|
||||||
embed.add_field(name='Resolve Reason', value=f"Resolved by {resolved_name} ({resolved_user['id']}) for:\n{codeblock}{case_dict['resolve_reason']}{codeblock}", inline=False)
|
|
||||||
else:
|
|
||||||
if case_dict['target_type'] == 'USER':
|
|
||||||
target_user = await fetch_user_dict(interaction, case_dict['target_id'])
|
|
||||||
target_name = f"`{target_user['name']}`" if target_user['discriminator'] == "0" else f"`{target_user['name']}#{target_user['discriminator']}`"
|
|
||||||
elif case_dict['target_type'] == 'CHANNEL':
|
|
||||||
target_user = await fetch_channel_dict(interaction, case_dict['target_id'])
|
|
||||||
if target_user['mention']:
|
|
||||||
target_name = target_user['mention']
|
|
||||||
else:
|
|
||||||
target_name = f"`{target_user['name']}`"
|
|
||||||
|
|
||||||
moderator_user = await fetch_user_dict(interaction, case_dict['moderator_id'])
|
|
||||||
moderator_name = f"`{moderator_user['name']}`" if moderator_user['discriminator'] == "0" else f"`{moderator_user['name']}#{moderator_user['discriminator']}`"
|
|
||||||
|
|
||||||
embed = Embed(title=f"📕 Case #{case_dict['moderation_id']:,}", color=color)
|
|
||||||
embed.description = f"**Type:** {str.title(case_dict['moderation_type'])}\n**Target:** {target_name} ({target_user['id']})\n**Moderator:** {moderator_name} ({moderator_user['id']})\n**Timestamp:** <t:{case_dict['timestamp']}> | <t:{case_dict['timestamp']}:R>"
|
|
||||||
|
|
||||||
if case_dict['duration'] != 'NULL':
|
|
||||||
td = timedelta(**{unit: int(val) for unit, val in zip(["hours", "minutes", "seconds"], case_dict["duration"].split(":"))})
|
|
||||||
embed.description = embed.description + f"\n**Duration:** {humanize.precisedelta(td)} | <t:{case_dict['end_timestamp']}:R>"
|
|
||||||
|
|
||||||
embed.add_field(name='Reason', value=f"{codeblock}{case_dict['reason']}{codeblock}", inline=False)
|
|
||||||
return embed
|
|
||||||
|
|
||||||
raise(TypeError("'type' argument is invalid!"))
|
|
615
aurora/utilities/factory.py
Normal file
|
@ -0,0 +1,615 @@
|
||||||
|
# pylint: disable=cyclic-import
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from typing import Union
|
||||||
|
|
||||||
|
from discord import (Color, Embed, Guild, Interaction, InteractionMessage,
|
||||||
|
Member, Role, User)
|
||||||
|
from redbot.core import commands
|
||||||
|
from redbot.core.utils.chat_formatting import (bold, box, error,
|
||||||
|
humanize_timedelta, warning)
|
||||||
|
|
||||||
|
from aurora.utilities.config import config
|
||||||
|
from aurora.utilities.utils import (fetch_channel_dict, fetch_user_dict,
|
||||||
|
get_bool_emoji, get_next_case_number,
|
||||||
|
get_pagesize_str)
|
||||||
|
|
||||||
|
|
||||||
|
async def message_factory(
|
||||||
|
color: Color,
|
||||||
|
guild: Guild,
|
||||||
|
reason: str,
|
||||||
|
moderation_type: str,
|
||||||
|
moderator: Union[Member, User] = None,
|
||||||
|
duration: timedelta = None,
|
||||||
|
response: InteractionMessage = None,
|
||||||
|
role: Role = None,
|
||||||
|
) -> Embed:
|
||||||
|
"""This function creates a message from set parameters, meant for contacting the moderated user.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
color (Color): The color of the embed.
|
||||||
|
guild (Guild): The guild the moderation occurred in.
|
||||||
|
reason (str): The reason for the moderation.
|
||||||
|
moderation_type (str): The type of moderation.
|
||||||
|
moderator (Union[Member, User], optional): The moderator who performed the moderation. Defaults to None.
|
||||||
|
duration (timedelta, optional): The duration of the moderation. Defaults to None.
|
||||||
|
response (InteractionMessage, optional): The response message. Defaults to None.
|
||||||
|
role (Role, optional): The role that was added or removed. Defaults to None.
|
||||||
|
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
embed: The message embed.
|
||||||
|
"""
|
||||||
|
if response is not None and moderation_type not in [
|
||||||
|
"kicked",
|
||||||
|
"banned",
|
||||||
|
"tempbanned",
|
||||||
|
"unbanned",
|
||||||
|
]:
|
||||||
|
guild_name = f"[{guild.name}]({response.jump_url})"
|
||||||
|
else:
|
||||||
|
guild_name = guild.name
|
||||||
|
|
||||||
|
if moderation_type in ["tempbanned", "muted"] and duration:
|
||||||
|
embed_duration = f" for {humanize_timedelta(timedelta=duration)}"
|
||||||
|
else:
|
||||||
|
embed_duration = ""
|
||||||
|
|
||||||
|
if moderation_type == "note":
|
||||||
|
embed_desc = "received a"
|
||||||
|
elif moderation_type == "addrole":
|
||||||
|
embed_desc = f"received the {role.name} role"
|
||||||
|
elif moderation_type == "removerole":
|
||||||
|
embed_desc = f"lost the {role.name} role"
|
||||||
|
else:
|
||||||
|
embed_desc = "been"
|
||||||
|
|
||||||
|
embed = Embed(
|
||||||
|
title=str.title(moderation_type),
|
||||||
|
description=f"You have {embed_desc} {moderation_type}{embed_duration} in {guild_name}.",
|
||||||
|
color=color,
|
||||||
|
timestamp=datetime.now(),
|
||||||
|
)
|
||||||
|
|
||||||
|
if await config.guild(guild).show_moderator() and moderator is not None:
|
||||||
|
embed.add_field(
|
||||||
|
name="Moderator", value=f"`{moderator.name} ({moderator.id})`", inline=False
|
||||||
|
)
|
||||||
|
|
||||||
|
embed.add_field(name="Reason", value=f"`{reason}`", inline=False)
|
||||||
|
|
||||||
|
if guild.icon.url is not None:
|
||||||
|
embed.set_author(name=guild.name, icon_url=guild.icon.url)
|
||||||
|
else:
|
||||||
|
embed.set_author(name=guild.name)
|
||||||
|
|
||||||
|
embed.set_footer(
|
||||||
|
text=f"Case #{await get_next_case_number(guild.id):,}",
|
||||||
|
icon_url="https://cdn.discordapp.com/attachments/1070822161389994054/1159469476773904414/arrow-right-circle-icon-512x512-2p1e2aaw.png?ex=65312319&is=651eae19&hm=3cebdd28e805c13a79ec48ef87c32ca532ffa6b9ede2e48d0cf8e5e81f3a6818&",
|
||||||
|
)
|
||||||
|
|
||||||
|
return embed
|
||||||
|
|
||||||
|
|
||||||
|
async def log_factory(
|
||||||
|
interaction: Interaction, case_dict: dict, resolved: bool = False
|
||||||
|
) -> Embed:
|
||||||
|
"""This function creates a log embed from set parameters, meant for moderation logging.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
interaction (Interaction): The interaction object.
|
||||||
|
case_dict (dict): The case dictionary.
|
||||||
|
resolved (bool, optional): Whether the case is resolved or not. Defaults to False.
|
||||||
|
"""
|
||||||
|
if resolved:
|
||||||
|
if case_dict["target_type"] == "USER":
|
||||||
|
target_user = await fetch_user_dict(interaction.client, case_dict["target_id"])
|
||||||
|
target_name = (
|
||||||
|
f"`{target_user['name']}`"
|
||||||
|
if target_user["discriminator"] == "0"
|
||||||
|
else f"`{target_user['name']}#{target_user['discriminator']}`"
|
||||||
|
)
|
||||||
|
elif case_dict["target_type"] == "CHANNEL":
|
||||||
|
target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"])
|
||||||
|
if target_user["mention"]:
|
||||||
|
target_name = f"{target_user['mention']}"
|
||||||
|
else:
|
||||||
|
target_name = f"`{target_user['name']}`"
|
||||||
|
|
||||||
|
moderator_user = await fetch_user_dict(interaction.client, case_dict["moderator_id"])
|
||||||
|
moderator_name = (
|
||||||
|
f"`{moderator_user['name']}`"
|
||||||
|
if moderator_user["discriminator"] == "0"
|
||||||
|
else f"`{moderator_user['name']}#{moderator_user['discriminator']}`"
|
||||||
|
)
|
||||||
|
|
||||||
|
embed = Embed(
|
||||||
|
title=f"📕 Case #{case_dict['moderation_id']:,} Resolved",
|
||||||
|
color=await interaction.client.get_embed_color(interaction.channel),
|
||||||
|
)
|
||||||
|
|
||||||
|
embed.description = f"**Type:** {str.title(case_dict['moderation_type'])}\n**Target:** {target_name} ({target_user['id']})\n**Moderator:** {moderator_name} ({moderator_user['id']})\n**Timestamp:** <t:{case_dict['timestamp']}> | <t:{case_dict['timestamp']}:R>"
|
||||||
|
|
||||||
|
if case_dict["duration"] != "NULL":
|
||||||
|
td = timedelta(
|
||||||
|
**{
|
||||||
|
unit: int(val)
|
||||||
|
for unit, val in zip(
|
||||||
|
["hours", "minutes", "seconds"],
|
||||||
|
case_dict["duration"].split(":"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
duration_embed = (
|
||||||
|
f"{humanize_timedelta(timedelta=td)} | <t:{case_dict['end_timestamp']}:R>"
|
||||||
|
if case_dict["expired"] == "0"
|
||||||
|
else str(humanize_timedelta(timedelta=td))
|
||||||
|
)
|
||||||
|
embed.description = (
|
||||||
|
embed.description
|
||||||
|
+ f"\n**Duration:** {duration_embed}\n**Expired:** {bool(case_dict['expired'])}"
|
||||||
|
)
|
||||||
|
|
||||||
|
embed.add_field(name="Reason", value=box(case_dict["reason"]), inline=False)
|
||||||
|
|
||||||
|
resolved_user = await fetch_user_dict(interaction.client, case_dict["resolved_by"])
|
||||||
|
resolved_name = (
|
||||||
|
resolved_user["name"]
|
||||||
|
if resolved_user["discriminator"] == "0"
|
||||||
|
else f"{resolved_user['name']}#{resolved_user['discriminator']}"
|
||||||
|
)
|
||||||
|
embed.add_field(
|
||||||
|
name="Resolve Reason",
|
||||||
|
value=f"Resolved by `{resolved_name}` ({resolved_user['id']}) for:\n"
|
||||||
|
+ box(case_dict["resolve_reason"]),
|
||||||
|
inline=False,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
if case_dict["target_type"] == "USER":
|
||||||
|
target_user = await fetch_user_dict(interaction.client, case_dict["target_id"])
|
||||||
|
target_name = (
|
||||||
|
f"`{target_user['name']}`"
|
||||||
|
if target_user["discriminator"] == "0"
|
||||||
|
else f"`{target_user['name']}#{target_user['discriminator']}`"
|
||||||
|
)
|
||||||
|
elif case_dict["target_type"] == "CHANNEL":
|
||||||
|
target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"])
|
||||||
|
if target_user["mention"]:
|
||||||
|
target_name = target_user["mention"]
|
||||||
|
else:
|
||||||
|
target_name = f"`{target_user['name']}`"
|
||||||
|
|
||||||
|
moderator_user = await fetch_user_dict(interaction.client, case_dict["moderator_id"])
|
||||||
|
moderator_name = (
|
||||||
|
f"`{moderator_user['name']}`"
|
||||||
|
if moderator_user["discriminator"] == "0"
|
||||||
|
else f"`{moderator_user['name']}#{moderator_user['discriminator']}`"
|
||||||
|
)
|
||||||
|
|
||||||
|
embed = Embed(
|
||||||
|
title=f"📕 Case #{case_dict['moderation_id']:,}",
|
||||||
|
color=await interaction.client.get_embed_color(interaction.channel),
|
||||||
|
)
|
||||||
|
embed.description = f"**Type:** {str.title(case_dict['moderation_type'])}\n**Target:** {target_name} ({target_user['id']})\n**Moderator:** {moderator_name} ({moderator_user['id']})\n**Timestamp:** <t:{case_dict['timestamp']}> | <t:{case_dict['timestamp']}:R>"
|
||||||
|
|
||||||
|
if case_dict["duration"] != "NULL":
|
||||||
|
td = timedelta(
|
||||||
|
**{
|
||||||
|
unit: int(val)
|
||||||
|
for unit, val in zip(
|
||||||
|
["hours", "minutes", "seconds"],
|
||||||
|
case_dict["duration"].split(":"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
embed.description = (
|
||||||
|
embed.description
|
||||||
|
+ f"\n**Duration:** {humanize_timedelta(timedelta=td)} | <t:{case_dict['end_timestamp']}:R>"
|
||||||
|
)
|
||||||
|
|
||||||
|
embed.add_field(name="Reason", value=box(case_dict["reason"]), inline=False)
|
||||||
|
return embed
|
||||||
|
|
||||||
|
|
||||||
|
async def case_factory(interaction: Interaction, case_dict: dict) -> Embed:
|
||||||
|
"""This function creates a case embed from set parameters.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
interaction (Interaction): The interaction object.
|
||||||
|
case_dict (dict): The case dictionary.
|
||||||
|
"""
|
||||||
|
if case_dict["target_type"] == "USER":
|
||||||
|
target_user = await fetch_user_dict(interaction.client, case_dict["target_id"])
|
||||||
|
target_name = (
|
||||||
|
f"`{target_user['name']}`"
|
||||||
|
if target_user["discriminator"] == "0"
|
||||||
|
else f"`{target_user['name']}#{target_user['discriminator']}`"
|
||||||
|
)
|
||||||
|
elif case_dict["target_type"] == "CHANNEL":
|
||||||
|
target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"])
|
||||||
|
if target_user["mention"]:
|
||||||
|
target_name = f"{target_user['mention']}"
|
||||||
|
else:
|
||||||
|
target_name = f"`{target_user['name']}`"
|
||||||
|
|
||||||
|
moderator_user = await fetch_user_dict(interaction.client, case_dict["moderator_id"])
|
||||||
|
moderator_name = (
|
||||||
|
f"`{moderator_user['name']}`"
|
||||||
|
if moderator_user["discriminator"] == "0"
|
||||||
|
else f"`{moderator_user['name']}#{moderator_user['discriminator']}`"
|
||||||
|
)
|
||||||
|
|
||||||
|
embed = Embed(
|
||||||
|
title=f"📕 Case #{case_dict['moderation_id']:,}",
|
||||||
|
color=await interaction.client.get_embed_color(interaction.channel),
|
||||||
|
)
|
||||||
|
embed.description = f"**Type:** {str.title(case_dict['moderation_type'])}\n**Target:** {target_name} ({target_user['id']})\n**Moderator:** {moderator_name} ({moderator_user['id']})\n**Resolved:** {bool(case_dict['resolved'])}\n**Timestamp:** <t:{case_dict['timestamp']}> | <t:{case_dict['timestamp']}:R>"
|
||||||
|
|
||||||
|
if case_dict["duration"] != "NULL":
|
||||||
|
td = timedelta(
|
||||||
|
**{
|
||||||
|
unit: int(val)
|
||||||
|
for unit, val in zip(
|
||||||
|
["hours", "minutes", "seconds"], case_dict["duration"].split(":")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
duration_embed = (
|
||||||
|
f"{humanize_timedelta(timedelta=td)} | <t:{case_dict['end_timestamp']}:R>"
|
||||||
|
if bool(case_dict["expired"]) is False
|
||||||
|
else str(humanize_timedelta(timedelta=td))
|
||||||
|
)
|
||||||
|
embed.description += f"\n**Duration:** {duration_embed}\n**Expired:** {bool(case_dict['expired'])}"
|
||||||
|
|
||||||
|
embed.description += (
|
||||||
|
f"\n**Changes:** {len(case_dict['changes']) - 1}"
|
||||||
|
if case_dict["changes"]
|
||||||
|
else "\n**Changes:** 0"
|
||||||
|
)
|
||||||
|
|
||||||
|
if case_dict["metadata"]:
|
||||||
|
if case_dict["metadata"]["imported_from"]:
|
||||||
|
embed.description += (
|
||||||
|
f"\n**Imported From:** {case_dict['metadata']['imported_from']}"
|
||||||
|
)
|
||||||
|
|
||||||
|
embed.add_field(name="Reason", value=box(case_dict["reason"]), inline=False)
|
||||||
|
|
||||||
|
if case_dict["resolved"] == 1:
|
||||||
|
resolved_user = await fetch_user_dict(interaction.client, case_dict["resolved_by"])
|
||||||
|
resolved_name = (
|
||||||
|
f"`{resolved_user['name']}`"
|
||||||
|
if resolved_user["discriminator"] == "0"
|
||||||
|
else f"`{resolved_user['name']}#{resolved_user['discriminator']}`"
|
||||||
|
)
|
||||||
|
embed.add_field(
|
||||||
|
name="Resolve Reason",
|
||||||
|
value=f"Resolved by {resolved_name} ({resolved_user['id']}) for:\n{box(case_dict['resolve_reason'])}",
|
||||||
|
inline=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
return embed
|
||||||
|
|
||||||
|
|
||||||
|
async def changes_factory(interaction: Interaction, case_dict: dict) -> Embed:
|
||||||
|
"""This function creates a changes embed from set parameters.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
interaction (Interaction): The interaction object.
|
||||||
|
case_dict (dict): The case dictionary.
|
||||||
|
"""
|
||||||
|
embed = Embed(
|
||||||
|
title=f"📕 Case #{case_dict['moderation_id']:,} Changes",
|
||||||
|
color=await interaction.client.get_embed_color(interaction.channel),
|
||||||
|
)
|
||||||
|
|
||||||
|
memory_dict = {}
|
||||||
|
|
||||||
|
if case_dict["changes"]:
|
||||||
|
for change in case_dict["changes"]:
|
||||||
|
if change["user_id"] not in memory_dict:
|
||||||
|
memory_dict[str(change["user_id"])] = await fetch_user_dict(
|
||||||
|
interaction.client, change["user_id"]
|
||||||
|
)
|
||||||
|
|
||||||
|
user = memory_dict[str(change["user_id"])]
|
||||||
|
name = (
|
||||||
|
user["name"]
|
||||||
|
if user["discriminator"] == "0"
|
||||||
|
else f"{user['name']}#{user['discriminator']}"
|
||||||
|
)
|
||||||
|
|
||||||
|
timestamp = f"<t:{change['timestamp']}> | <t:{change['timestamp']}:R>"
|
||||||
|
|
||||||
|
if change["type"] == "ORIGINAL":
|
||||||
|
embed.add_field(
|
||||||
|
name="Original",
|
||||||
|
value=f"**User:** `{name}` ({user['id']})\n**Reason:** {change['reason']}\n**Timestamp:** {timestamp}",
|
||||||
|
inline=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
elif change["type"] == "EDIT":
|
||||||
|
embed.add_field(
|
||||||
|
name="Edit",
|
||||||
|
value=f"**User:** `{name}` ({user['id']})\n**Reason:** {change['reason']}\n**Timestamp:** {timestamp}",
|
||||||
|
inline=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
elif change["type"] == "RESOLVE":
|
||||||
|
embed.add_field(
|
||||||
|
name="Resolve",
|
||||||
|
value=f"**User:** `{name}` ({user['id']})\n**Reason:** {change['reason']}\n**Timestamp:** {timestamp}",
|
||||||
|
inline=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
else:
|
||||||
|
embed.description = "*No changes have been made to this case.* 🙁"
|
||||||
|
|
||||||
|
return embed
|
||||||
|
|
||||||
|
|
||||||
|
async def evidenceformat_factory(interaction: Interaction, case_dict: dict) -> str:
|
||||||
|
"""This function creates a codeblock in evidence format from set parameters.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
interaction (Interaction): The interaction object.
|
||||||
|
case_dict (dict): The case dictionary.
|
||||||
|
"""
|
||||||
|
if case_dict["target_type"] == "USER":
|
||||||
|
target_user = await fetch_user_dict(interaction.client, case_dict["target_id"])
|
||||||
|
target_name = (
|
||||||
|
target_user["name"]
|
||||||
|
if target_user["discriminator"] == "0"
|
||||||
|
else f"{target_user['name']}#{target_user['discriminator']}"
|
||||||
|
)
|
||||||
|
|
||||||
|
elif case_dict["target_type"] == "CHANNEL":
|
||||||
|
target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"])
|
||||||
|
target_name = target_user["name"]
|
||||||
|
|
||||||
|
moderator_user = await fetch_user_dict(interaction.client, case_dict["moderator_id"])
|
||||||
|
moderator_name = (
|
||||||
|
moderator_user["name"]
|
||||||
|
if moderator_user["discriminator"] == "0"
|
||||||
|
else f"{moderator_user['name']}#{moderator_user['discriminator']}"
|
||||||
|
)
|
||||||
|
|
||||||
|
content = f"Case: {case_dict['moderation_id']:,} ({str.title(case_dict['moderation_type'])})\nTarget: {target_name} ({target_user['id']})\nModerator: {moderator_name} ({moderator_user['id']})"
|
||||||
|
|
||||||
|
if case_dict["duration"] != "NULL":
|
||||||
|
hours, minutes, seconds = map(int, case_dict["duration"].split(":"))
|
||||||
|
td = timedelta(hours=hours, minutes=minutes, seconds=seconds)
|
||||||
|
content += f"\nDuration: {humanize_timedelta(timedelta=td)}"
|
||||||
|
|
||||||
|
content += f"\nReason: {case_dict['reason']}"
|
||||||
|
|
||||||
|
return box(content, "prolog")
|
||||||
|
|
||||||
|
|
||||||
|
########################################################################################################################
|
||||||
|
### Configuration Embeds #
|
||||||
|
########################################################################################################################
|
||||||
|
|
||||||
|
|
||||||
|
async def _config(ctx: commands.Context) -> Embed:
|
||||||
|
"""Generates the core embed for configuration menus to use."""
|
||||||
|
e = Embed(title="Aurora Configuration Menu", color=await ctx.embed_color())
|
||||||
|
e.set_thumbnail(url=ctx.bot.user.display_avatar.url)
|
||||||
|
return e
|
||||||
|
|
||||||
|
|
||||||
|
async def overrides_embed(ctx: commands.Context) -> Embed:
|
||||||
|
"""Generates a configuration menu embed for a user's overrides."""
|
||||||
|
|
||||||
|
override_settings = {
|
||||||
|
"ephemeral": await config.user(ctx.author).history_ephemeral(),
|
||||||
|
"inline": await config.user(ctx.author).history_inline(),
|
||||||
|
"inline_pagesize": await config.user(ctx.author).history_inline_pagesize(),
|
||||||
|
"pagesize": await config.user(ctx.author).history_pagesize(),
|
||||||
|
"auto_evidenceformat": await config.user(ctx.author).auto_evidenceformat(),
|
||||||
|
}
|
||||||
|
|
||||||
|
override_str = [
|
||||||
|
"- "
|
||||||
|
+ bold("Auto Evidence Format: ")
|
||||||
|
+ get_bool_emoji(override_settings["auto_evidenceformat"]),
|
||||||
|
"- " + bold("Ephemeral: ") + get_bool_emoji(override_settings["ephemeral"]),
|
||||||
|
"- " + bold("History Inline: ") + get_bool_emoji(override_settings["inline"]),
|
||||||
|
"- "
|
||||||
|
+ bold("History Inline Pagesize: ")
|
||||||
|
+ get_pagesize_str(override_settings["inline_pagesize"]),
|
||||||
|
"- "
|
||||||
|
+ bold("History Pagesize: ")
|
||||||
|
+ get_pagesize_str(override_settings["pagesize"]),
|
||||||
|
]
|
||||||
|
override_str = "\n".join(override_str)
|
||||||
|
|
||||||
|
e = await _config(ctx)
|
||||||
|
e.title += ": User Overrides"
|
||||||
|
e.description = (
|
||||||
|
"""
|
||||||
|
Use the buttons below to manage your user overrides.
|
||||||
|
These settings will override the relevant guild settings.\n
|
||||||
|
"""
|
||||||
|
+ override_str
|
||||||
|
)
|
||||||
|
return e
|
||||||
|
|
||||||
|
|
||||||
|
async def guild_embed(ctx: commands.Context) -> Embed:
|
||||||
|
"""Generates a configuration menu field value for a guild's settings."""
|
||||||
|
|
||||||
|
guild_settings = {
|
||||||
|
"show_moderator": await config.guild(ctx.guild).show_moderator(),
|
||||||
|
"use_discord_permissions": await config.guild(
|
||||||
|
ctx.guild
|
||||||
|
).use_discord_permissions(),
|
||||||
|
"ignore_modlog": await config.guild(ctx.guild).ignore_modlog(),
|
||||||
|
"ignore_other_bots": await config.guild(ctx.guild).ignore_other_bots(),
|
||||||
|
"dm_users": await config.guild(ctx.guild).dm_users(),
|
||||||
|
"log_channel": await config.guild(ctx.guild).log_channel(),
|
||||||
|
"history_ephemeral": await config.guild(ctx.guild).history_ephemeral(),
|
||||||
|
"history_inline": await config.guild(ctx.guild).history_inline(),
|
||||||
|
"history_pagesize": await config.guild(ctx.guild).history_pagesize(),
|
||||||
|
"history_inline_pagesize": await config.guild(
|
||||||
|
ctx.guild
|
||||||
|
).history_inline_pagesize(),
|
||||||
|
"auto_evidenceformat": await config.guild(ctx.guild).auto_evidenceformat(),
|
||||||
|
"respect_hierarchy": await config.guild(ctx.guild).respect_hierarchy(),
|
||||||
|
}
|
||||||
|
|
||||||
|
channel = ctx.guild.get_channel(guild_settings["log_channel"])
|
||||||
|
if channel is None:
|
||||||
|
channel = warning("Not Set")
|
||||||
|
else:
|
||||||
|
channel = channel.mention
|
||||||
|
|
||||||
|
guild_str = [
|
||||||
|
"- "
|
||||||
|
+ bold("Show Moderator: ")
|
||||||
|
+ get_bool_emoji(guild_settings["show_moderator"]),
|
||||||
|
"- "
|
||||||
|
+ bold("Use Discord Permissions: ")
|
||||||
|
+ get_bool_emoji(guild_settings["use_discord_permissions"]),
|
||||||
|
"- "
|
||||||
|
+ bold("Respect Hierarchy: ")
|
||||||
|
+ get_bool_emoji(guild_settings["respect_hierarchy"]),
|
||||||
|
"- "
|
||||||
|
+ bold("Ignore Modlog: ")
|
||||||
|
+ get_bool_emoji(guild_settings["ignore_modlog"]),
|
||||||
|
"- "
|
||||||
|
+ bold("Ignore Other Bots: ")
|
||||||
|
+ get_bool_emoji(guild_settings["ignore_other_bots"]),
|
||||||
|
"- " + bold("DM Users: ") + get_bool_emoji(guild_settings["dm_users"]),
|
||||||
|
"- "
|
||||||
|
+ bold("Auto Evidence Format: ")
|
||||||
|
+ get_bool_emoji(guild_settings["auto_evidenceformat"]),
|
||||||
|
"- "
|
||||||
|
+ bold("Ephemeral: ")
|
||||||
|
+ get_bool_emoji(guild_settings["history_ephemeral"]),
|
||||||
|
"- "
|
||||||
|
+ bold("History Inline: ")
|
||||||
|
+ get_bool_emoji(guild_settings["history_inline"]),
|
||||||
|
"- "
|
||||||
|
+ bold("History Pagesize: ")
|
||||||
|
+ get_pagesize_str(guild_settings["history_pagesize"]),
|
||||||
|
"- "
|
||||||
|
+ bold("History Inline Pagesize: ")
|
||||||
|
+ get_pagesize_str(guild_settings["history_inline_pagesize"]),
|
||||||
|
"- " + bold("Log Channel: ") + channel,
|
||||||
|
]
|
||||||
|
guild_str = "\n".join(guild_str)
|
||||||
|
|
||||||
|
e = await _config(ctx)
|
||||||
|
e.title += ": Server Configuration"
|
||||||
|
e.description = (
|
||||||
|
"""
|
||||||
|
Use the buttons below to manage Aurora's server configuration.\n
|
||||||
|
"""
|
||||||
|
+ guild_str
|
||||||
|
)
|
||||||
|
return e
|
||||||
|
|
||||||
|
|
||||||
|
async def addrole_embed(ctx: commands.Context) -> Embed:
|
||||||
|
"""Generates a configuration menu field value for a guild's addrole whitelist."""
|
||||||
|
|
||||||
|
roles = []
|
||||||
|
async with config.guild(ctx.guild).addrole_whitelist() as whitelist:
|
||||||
|
for role in whitelist:
|
||||||
|
evalulated_role = ctx.guild.get_role(role) or error(f"`{role}` (Not Found)")
|
||||||
|
if isinstance(evalulated_role, Role):
|
||||||
|
roles.append({
|
||||||
|
"id": evalulated_role.id,
|
||||||
|
"mention": evalulated_role.mention,
|
||||||
|
"position": evalulated_role.position
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
roles.append({
|
||||||
|
"id": role,
|
||||||
|
"mention": error(f"`{role}` (Not Found)"),
|
||||||
|
"position": 0
|
||||||
|
})
|
||||||
|
|
||||||
|
if roles:
|
||||||
|
roles = sorted(roles, key=lambda x: x["position"], reverse=True)
|
||||||
|
roles = [role["mention"] for role in roles]
|
||||||
|
whitelist_str = "\n".join(roles)
|
||||||
|
else:
|
||||||
|
whitelist_str = warning("No roles are on the addrole whitelist!")
|
||||||
|
|
||||||
|
e = await _config(ctx)
|
||||||
|
e.title += ": Addrole Whitelist"
|
||||||
|
e.description = (
|
||||||
|
"Use the select menu below to manage this guild's addrole whitelist."
|
||||||
|
)
|
||||||
|
|
||||||
|
if len(whitelist_str) > 4000 and len(whitelist_str) < 5000:
|
||||||
|
lines = whitelist_str.split("\n")
|
||||||
|
chunks = []
|
||||||
|
chunk = ""
|
||||||
|
for line in lines:
|
||||||
|
if len(chunk) + len(line) > 1024:
|
||||||
|
chunks.append(chunk)
|
||||||
|
chunk = line
|
||||||
|
else:
|
||||||
|
chunk += "\n" + line if chunk else line
|
||||||
|
chunks.append(chunk)
|
||||||
|
|
||||||
|
for chunk in chunks:
|
||||||
|
e.add_field(name="", value=chunk)
|
||||||
|
else:
|
||||||
|
e.description += "\n\n" + whitelist_str
|
||||||
|
|
||||||
|
return e
|
||||||
|
|
||||||
|
|
||||||
|
async def immune_embed(ctx: commands.Context) -> Embed:
|
||||||
|
"""Generates a configuration menu embed for a guild's immune roles."""
|
||||||
|
|
||||||
|
roles = []
|
||||||
|
async with config.guild(ctx.guild).immune_roles() as immune_roles:
|
||||||
|
for role in immune_roles:
|
||||||
|
evalulated_role = ctx.guild.get_role(role) or error(f"`{role}` (Not Found)")
|
||||||
|
if isinstance(evalulated_role, Role):
|
||||||
|
roles.append({
|
||||||
|
"id": evalulated_role.id,
|
||||||
|
"mention": evalulated_role.mention,
|
||||||
|
"position": evalulated_role.position
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
roles.append({
|
||||||
|
"id": role,
|
||||||
|
"mention": error(f"`{role}` (Not Found)"),
|
||||||
|
"position": 0
|
||||||
|
})
|
||||||
|
|
||||||
|
if roles:
|
||||||
|
roles = sorted(roles, key=lambda x: x["position"], reverse=True)
|
||||||
|
roles = [role["mention"] for role in roles]
|
||||||
|
immune_str = "\n".join(roles)
|
||||||
|
else:
|
||||||
|
immune_str = warning("No roles are set as immune roles!")
|
||||||
|
|
||||||
|
e = await _config(ctx)
|
||||||
|
e.title += ": Immune Roles"
|
||||||
|
e.description = "Use the select menu below to manage this guild's immune roles."
|
||||||
|
|
||||||
|
if len(immune_str) > 4000 and len(immune_str) < 5000:
|
||||||
|
lines = immune_str.split("\n")
|
||||||
|
chunks = []
|
||||||
|
chunk = ""
|
||||||
|
for line in lines:
|
||||||
|
if len(chunk) + len(line) > 1024:
|
||||||
|
chunks.append(chunk)
|
||||||
|
chunk = line
|
||||||
|
else:
|
||||||
|
chunk += "\n" + line if chunk else line
|
||||||
|
chunks.append(chunk)
|
||||||
|
|
||||||
|
for chunk in chunks:
|
||||||
|
e.add_field(name="", value=chunk)
|
||||||
|
else:
|
||||||
|
e.description += "\n\n" + immune_str
|
||||||
|
|
||||||
|
return e
|
|
@ -1,3 +1,3 @@
|
||||||
import logging
|
from red_commons.logging import getLogger
|
||||||
|
|
||||||
logger = logging.getLogger("red.sea.aurora")
|
logger = getLogger("red.SeaCogs.Aurora")
|
||||||
|
|
|
@ -1,12 +1,14 @@
|
||||||
# pylint: disable=cyclic-import
|
# pylint: disable=cyclic-import
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
from datetime import datetime
|
||||||
from datetime import timedelta as td
|
from datetime import timedelta as td
|
||||||
from typing import Union
|
from typing import Optional, Union
|
||||||
|
|
||||||
from discord import Guild, Interaction, Member, User
|
from dateutil.relativedelta import relativedelta as rd
|
||||||
|
from discord import Guild, Interaction, Member, SelectOption, User
|
||||||
from discord.errors import Forbidden, NotFound
|
from discord.errors import Forbidden, NotFound
|
||||||
from redbot.core import commands
|
from redbot.core import commands
|
||||||
|
from redbot.core.utils.chat_formatting import error
|
||||||
|
|
||||||
from .config import config
|
from .config import config
|
||||||
|
|
||||||
|
@ -16,7 +18,7 @@ def check_permissions(
|
||||||
permissions: list,
|
permissions: list,
|
||||||
ctx: Union[commands.Context, Interaction] = None,
|
ctx: Union[commands.Context, Interaction] = None,
|
||||||
guild: Guild = None,
|
guild: Guild = None,
|
||||||
):
|
) -> Union[bool, str]:
|
||||||
"""Checks if a user has a specific permission (or a list of permissions) in a channel."""
|
"""Checks if a user has a specific permission (or a list of permissions) in a channel."""
|
||||||
if ctx:
|
if ctx:
|
||||||
member = ctx.guild.get_member(user.id)
|
member = ctx.guild.get_member(user.id)
|
||||||
|
@ -32,7 +34,7 @@ def check_permissions(
|
||||||
for permission in permissions:
|
for permission in permissions:
|
||||||
if (
|
if (
|
||||||
not getattr(resolved_permissions, permission, False)
|
not getattr(resolved_permissions, permission, False)
|
||||||
and not resolved_permissions.administrator is True
|
and resolved_permissions.administrator is not True
|
||||||
):
|
):
|
||||||
return permission
|
return permission
|
||||||
|
|
||||||
|
@ -41,11 +43,13 @@ def check_permissions(
|
||||||
|
|
||||||
async def check_moddable(
|
async def check_moddable(
|
||||||
target: Union[User, Member], interaction: Interaction, permissions: list
|
target: Union[User, Member], interaction: Interaction, permissions: list
|
||||||
):
|
) -> bool:
|
||||||
"""Checks if a moderator can moderate a target."""
|
"""Checks if a moderator can moderate a target."""
|
||||||
if check_permissions(interaction.client.user, permissions, guild=interaction.guild):
|
if check_permissions(interaction.client.user, permissions, guild=interaction.guild):
|
||||||
await interaction.response.send_message(
|
await interaction.response.send_message(
|
||||||
f"I do not have the `{permissions}` permission, required for this action.",
|
error(
|
||||||
|
f"I do not have the `{permissions}` permission, required for this action."
|
||||||
|
),
|
||||||
ephemeral=True,
|
ephemeral=True,
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
@ -53,7 +57,9 @@ async def check_moddable(
|
||||||
if await config.guild(interaction.guild).use_discord_permissions() is True:
|
if await config.guild(interaction.guild).use_discord_permissions() is True:
|
||||||
if check_permissions(interaction.user, permissions, guild=interaction.guild):
|
if check_permissions(interaction.user, permissions, guild=interaction.guild):
|
||||||
await interaction.response.send_message(
|
await interaction.response.send_message(
|
||||||
f"You do not have the `{permissions}` permission, required for this action.",
|
error(
|
||||||
|
f"You do not have the `{permissions}` permission, required for this action."
|
||||||
|
),
|
||||||
ephemeral=True,
|
ephemeral=True,
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
@ -71,9 +77,11 @@ async def check_moddable(
|
||||||
return False
|
return False
|
||||||
|
|
||||||
if isinstance(target, Member):
|
if isinstance(target, Member):
|
||||||
if interaction.user.top_role <= target.top_role:
|
if interaction.user.top_role <= target.top_role and await config.guild(interaction.guild).respect_hierarchy() is True:
|
||||||
await interaction.response.send_message(
|
await interaction.response.send_message(
|
||||||
content="You cannot moderate members with a higher role than you!",
|
content=error(
|
||||||
|
"You cannot moderate members with a higher role than you!"
|
||||||
|
),
|
||||||
ephemeral=True,
|
ephemeral=True,
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
@ -83,7 +91,9 @@ async def check_moddable(
|
||||||
<= target.top_role
|
<= target.top_role
|
||||||
):
|
):
|
||||||
await interaction.response.send_message(
|
await interaction.response.send_message(
|
||||||
content="You cannot moderate members with a role higher than the bot!",
|
content=error(
|
||||||
|
"You cannot moderate members with a role higher than the bot!"
|
||||||
|
),
|
||||||
ephemeral=True,
|
ephemeral=True,
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
@ -93,7 +103,7 @@ async def check_moddable(
|
||||||
for role in target.roles:
|
for role in target.roles:
|
||||||
if role.id in immune_roles:
|
if role.id in immune_roles:
|
||||||
await interaction.response.send_message(
|
await interaction.response.send_message(
|
||||||
content="You cannot moderate members with an immune role!",
|
content=error("You cannot moderate members with an immune role!"),
|
||||||
ephemeral=True,
|
ephemeral=True,
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
@ -101,7 +111,7 @@ async def check_moddable(
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
async def get_next_case_number(guild_id: str, cursor=None):
|
async def get_next_case_number(guild_id: str, cursor=None) -> int:
|
||||||
"""This function returns the next case number from the MySQL table for a specific guild."""
|
"""This function returns the next case number from the MySQL table for a specific guild."""
|
||||||
from .database import connect
|
from .database import connect
|
||||||
|
|
||||||
|
@ -111,11 +121,12 @@ async def get_next_case_number(guild_id: str, cursor=None):
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
f"SELECT moderation_id FROM `moderation_{guild_id}` ORDER BY moderation_id DESC LIMIT 1"
|
f"SELECT moderation_id FROM `moderation_{guild_id}` ORDER BY moderation_id DESC LIMIT 1"
|
||||||
)
|
)
|
||||||
return cursor.fetchone()[0] + 1
|
result = cursor.fetchone()
|
||||||
|
return (result[0] + 1) if result else 1
|
||||||
|
|
||||||
|
|
||||||
def generate_dict(result):
|
def generate_dict(result) -> dict:
|
||||||
case: dict = {
|
case = {
|
||||||
"moderation_id": result[0],
|
"moderation_id": result[0],
|
||||||
"timestamp": result[1],
|
"timestamp": result[1],
|
||||||
"moderation_type": result[2],
|
"moderation_type": result[2],
|
||||||
|
@ -131,21 +142,21 @@ def generate_dict(result):
|
||||||
"resolve_reason": result[12],
|
"resolve_reason": result[12],
|
||||||
"expired": result[13],
|
"expired": result[13],
|
||||||
"changes": json.loads(result[14]),
|
"changes": json.loads(result[14]),
|
||||||
"metadata": json.loads(result[15])
|
"metadata": json.loads(result[15]),
|
||||||
}
|
}
|
||||||
return case
|
return case
|
||||||
|
|
||||||
|
|
||||||
async def fetch_user_dict(interaction: Interaction, user_id: str):
|
async def fetch_user_dict(client: commands.Bot, user_id: str) -> dict:
|
||||||
"""This function returns a dictionary containing either user information or a standard deleted user template."""
|
"""This function returns a dictionary containing either user information or a standard deleted user template."""
|
||||||
if user_id == "?":
|
if user_id == "?":
|
||||||
user_dict = {"id": "?", "name": "Unknown User", "discriminator": "0"}
|
user_dict = {"id": "?", "name": "Unknown User", "discriminator": "0"}
|
||||||
|
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
user = interaction.client.get_user(user_id)
|
user = client.get_user(int(user_id))
|
||||||
if user is None:
|
if user is None:
|
||||||
user = await interaction.client.fetch_user(user_id)
|
user = await client.fetch_user(int(user_id))
|
||||||
|
|
||||||
user_dict = {
|
user_dict = {
|
||||||
"id": user.id,
|
"id": user.id,
|
||||||
|
@ -160,17 +171,22 @@ async def fetch_user_dict(interaction: Interaction, user_id: str):
|
||||||
"discriminator": "0",
|
"discriminator": "0",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
return user_dict
|
return user_dict
|
||||||
|
|
||||||
|
|
||||||
async def fetch_channel_dict(interaction: Interaction, channel_id: str):
|
async def fetch_channel_dict(guild: Guild, channel_id: int) -> dict:
|
||||||
"""This function returns a dictionary containing either channel information or a standard deleted channel template."""
|
"""This function returns a dictionary containing either channel information or a standard deleted channel template."""
|
||||||
try:
|
try:
|
||||||
channel = interaction.guild.get_channel(channel_id)
|
channel = guild.get_channel(int(channel_id))
|
||||||
if not channel:
|
if not channel:
|
||||||
channel = await interaction.guild.fetch_channel(channel_id)
|
channel = await guild.fetch_channel(channel_id)
|
||||||
|
|
||||||
channel_dict = {"id": channel.id, "name": channel.name, "mention": channel.mention}
|
channel_dict = {
|
||||||
|
"id": channel.id,
|
||||||
|
"name": channel.name,
|
||||||
|
"mention": channel.mention,
|
||||||
|
}
|
||||||
|
|
||||||
except NotFound:
|
except NotFound:
|
||||||
channel_dict = {"id": channel_id, "name": "Deleted Channel", "mention": None}
|
channel_dict = {"id": channel_id, "name": "Deleted Channel", "mention": None}
|
||||||
|
@ -178,9 +194,9 @@ async def fetch_channel_dict(interaction: Interaction, channel_id: str):
|
||||||
return channel_dict
|
return channel_dict
|
||||||
|
|
||||||
|
|
||||||
async def fetch_role_dict(interaction: Interaction, role_id: str):
|
async def fetch_role_dict(guild: Guild, role_id: int) -> dict:
|
||||||
"""This function returns a dictionary containing either role information or a standard deleted role template."""
|
"""This function returns a dictionary containing either role information or a standard deleted role template."""
|
||||||
role = interaction.guild.get_role(role_id)
|
role = guild.get_role(int(role_id))
|
||||||
if not role:
|
if not role:
|
||||||
role_dict = {"id": role_id, "name": "Deleted Role"}
|
role_dict = {"id": role_id, "name": "Deleted Role"}
|
||||||
|
|
||||||
|
@ -189,10 +205,10 @@ async def fetch_role_dict(interaction: Interaction, role_id: str):
|
||||||
return role_dict
|
return role_dict
|
||||||
|
|
||||||
|
|
||||||
async def log(interaction: Interaction, moderation_id: int, resolved: bool = False):
|
async def log(interaction: Interaction, moderation_id: int, resolved: bool = False) -> None:
|
||||||
"""This function sends a message to the guild's configured logging channel when an infraction takes place."""
|
"""This function sends a message to the guild's configured logging channel when an infraction takes place."""
|
||||||
from .database import fetch_case
|
from .database import fetch_case
|
||||||
from .embed_factory import embed_factory
|
from .factory import log_factory
|
||||||
|
|
||||||
logging_channel_id = await config.guild(interaction.guild).log_channel()
|
logging_channel_id = await config.guild(interaction.guild).log_channel()
|
||||||
if logging_channel_id != " ":
|
if logging_channel_id != " ":
|
||||||
|
@ -200,29 +216,31 @@ async def log(interaction: Interaction, moderation_id: int, resolved: bool = Fal
|
||||||
|
|
||||||
case = await fetch_case(moderation_id, interaction.guild.id)
|
case = await fetch_case(moderation_id, interaction.guild.id)
|
||||||
if case:
|
if case:
|
||||||
embed = await embed_factory(
|
embed = await log_factory(
|
||||||
"log", await interaction.client.get_embed_color(None), interaction=interaction, case_dict=case, resolved=resolved
|
interaction=interaction, case_dict=case, resolved=resolved
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
await logging_channel.send(embed=embed)
|
await logging_channel.send(embed=embed)
|
||||||
except Forbidden:
|
except Forbidden:
|
||||||
return
|
return
|
||||||
|
|
||||||
async def send_evidenceformat(interaction: Interaction, case_dict: dict):
|
|
||||||
"""This function sends an ephemeral message to the moderator who took the moderation action, with a pre-made codeblock for use in the mod-evidence channel."""
|
|
||||||
from .embed_factory import embed_factory
|
|
||||||
|
|
||||||
send_evidence_bool = (await config.user(interaction.user).auto_evidenceformat()
|
async def send_evidenceformat(interaction: Interaction, case_dict: dict) -> None:
|
||||||
|
"""This function sends an ephemeral message to the moderator who took the moderation action, with a pre-made codeblock for use in the mod-evidence channel."""
|
||||||
|
from .factory import evidenceformat_factory
|
||||||
|
|
||||||
|
send_evidence_bool = (
|
||||||
|
await config.user(interaction.user).auto_evidenceformat()
|
||||||
or await config.guild(interaction.guild).auto_evidenceformat()
|
or await config.guild(interaction.guild).auto_evidenceformat()
|
||||||
or False)
|
or False
|
||||||
|
)
|
||||||
if send_evidence_bool is False:
|
if send_evidence_bool is False:
|
||||||
return
|
return
|
||||||
|
|
||||||
content = await embed_factory(
|
content = await evidenceformat_factory(interaction=interaction, case_dict=case_dict)
|
||||||
"evidenceformat", await interaction.client.get_embed_color(None), interaction=interaction, case_dict=case_dict
|
|
||||||
)
|
|
||||||
await interaction.followup.send(content=content, ephemeral=True)
|
await interaction.followup.send(content=content, ephemeral=True)
|
||||||
|
|
||||||
|
|
||||||
def convert_timedelta_to_str(timedelta: td) -> str:
|
def convert_timedelta_to_str(timedelta: td) -> str:
|
||||||
"""This function converts a timedelta object to a string."""
|
"""This function converts a timedelta object to a string."""
|
||||||
total_seconds = int(timedelta.total_seconds())
|
total_seconds = int(timedelta.total_seconds())
|
||||||
|
@ -230,3 +248,46 @@ def convert_timedelta_to_str(timedelta: td) -> str:
|
||||||
minutes = (total_seconds % 3600) // 60
|
minutes = (total_seconds % 3600) // 60
|
||||||
seconds = total_seconds % 60
|
seconds = total_seconds % 60
|
||||||
return f"{hours}:{minutes}:{seconds}"
|
return f"{hours}:{minutes}:{seconds}"
|
||||||
|
|
||||||
|
|
||||||
|
def get_bool_emoji(value: Optional[bool]) -> str:
|
||||||
|
"""Returns a unicode emoji based on a boolean value."""
|
||||||
|
if value is True:
|
||||||
|
return "\N{WHITE HEAVY CHECK MARK}"
|
||||||
|
if value is False:
|
||||||
|
return "\N{NO ENTRY SIGN}"
|
||||||
|
return "\N{BLACK QUESTION MARK ORNAMENT}\N{VARIATION SELECTOR-16}"
|
||||||
|
|
||||||
|
|
||||||
|
def get_pagesize_str(value: Union[int, None]) -> str:
|
||||||
|
"""Returns a string based on a pagesize value."""
|
||||||
|
if value is None:
|
||||||
|
return "\N{BLACK QUESTION MARK ORNAMENT}\N{VARIATION SELECTOR-16}"
|
||||||
|
return str(value) + " cases per page"
|
||||||
|
|
||||||
|
|
||||||
|
def create_pagesize_options() -> list[SelectOption]:
|
||||||
|
"""Returns a list of SelectOptions for pagesize configuration."""
|
||||||
|
options = []
|
||||||
|
options.append(
|
||||||
|
SelectOption(
|
||||||
|
label="Default",
|
||||||
|
value="default",
|
||||||
|
description="Reset the pagesize to the default value.",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
for i in range(1, 21):
|
||||||
|
options.append(
|
||||||
|
SelectOption(
|
||||||
|
label=str(i),
|
||||||
|
value=str(i),
|
||||||
|
description=f"Set the pagesize to {i}.",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return options
|
||||||
|
|
||||||
|
def timedelta_from_relativedelta(relativedelta: rd) -> td:
|
||||||
|
"""Converts a relativedelta object to a timedelta object."""
|
||||||
|
now = datetime.now()
|
||||||
|
then = now - relativedelta
|
||||||
|
return now - then
|
||||||
|
|
5
backup/__init__.py
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
from .backup import Backup
|
||||||
|
|
||||||
|
|
||||||
|
async def setup(bot):
|
||||||
|
await bot.add_cog(Backup(bot))
|
320
backup/backup.py
Normal file
|
@ -0,0 +1,320 @@
|
||||||
|
# _____ _
|
||||||
|
# / ____| (_)
|
||||||
|
# | (___ ___ __ _ _____ ___ _ __ ___ _ __ ___ ___ _ __
|
||||||
|
# \___ \ / _ \/ _` / __\ \ /\ / / | '_ ` _ \| '_ ` _ \ / _ \ '__|
|
||||||
|
# ____) | __/ (_| \__ \\ V V /| | | | | | | | | | | | __/ |
|
||||||
|
# |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_|
|
||||||
|
|
||||||
|
import contextlib
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
|
||||||
|
from red_commons.logging import getLogger
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
# 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"
|
||||||
|
__documentation__ = "https://seacogs.coastalcommits.com/backup/"
|
||||||
|
|
||||||
|
def __init__(self, bot: Red):
|
||||||
|
super().__init__()
|
||||||
|
self.bot = bot
|
||||||
|
self.logger = getLogger("red.SeaCogs.Backup")
|
||||||
|
|
||||||
|
def format_help_for_context(self, ctx: commands.Context) -> str:
|
||||||
|
pre_processed = super().format_help_for_context(ctx) or ""
|
||||||
|
n = "\n" if "\n\n" not in pre_processed else ""
|
||||||
|
text = [
|
||||||
|
f"{pre_processed}{n}",
|
||||||
|
f"Cog Version: **{self.__version__}**",
|
||||||
|
f"Author: {humanize_list(self.__author__)}",
|
||||||
|
f"Documentation: {self.__documentation__}",
|
||||||
|
]
|
||||||
|
return "\n".join(text)
|
||||||
|
|
||||||
|
@commands.group(autohelp=True)
|
||||||
|
@commands.is_owner()
|
||||||
|
async def backup(self, ctx: commands.Context):
|
||||||
|
"""Backup your installed cogs."""
|
||||||
|
|
||||||
|
@backup.command(name="export")
|
||||||
|
@commands.is_owner()
|
||||||
|
async def backup_export(self, ctx: commands.Context):
|
||||||
|
"""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."
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
all_repos = list(downloader._repo_manager.repos)
|
||||||
|
|
||||||
|
export_data = []
|
||||||
|
|
||||||
|
for repo in all_repos:
|
||||||
|
repo_dict = {
|
||||||
|
"name": repo.name,
|
||||||
|
"url": repo.url,
|
||||||
|
"branch": repo.branch,
|
||||||
|
"cogs": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
cogs = await downloader.installed_cogs()
|
||||||
|
|
||||||
|
for cog in cogs:
|
||||||
|
if cog.repo_name == repo.name:
|
||||||
|
cog_dict = {
|
||||||
|
"name": cog.name,
|
||||||
|
# "loaded": cog.name in ctx.bot.extensions.keys(),
|
||||||
|
# this functionality was planned but never implemented due to Red limitations
|
||||||
|
# and the possibility of restoration functionality being added to Core
|
||||||
|
"pinned": cog.pinned,
|
||||||
|
"commit": cog.commit,
|
||||||
|
}
|
||||||
|
repo_dict["cogs"].append(cog_dict)
|
||||||
|
|
||||||
|
export_data.append(repo_dict)
|
||||||
|
|
||||||
|
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):
|
||||||
|
"""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())
|
||||||
|
except (json.JSONDecodeError, IndexError):
|
||||||
|
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."
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
repo_s = []
|
||||||
|
uninstall_s = []
|
||||||
|
install_s = []
|
||||||
|
repo_e = []
|
||||||
|
uninstall_e = []
|
||||||
|
install_e = []
|
||||||
|
|
||||||
|
async with ctx.typing():
|
||||||
|
for repo in export:
|
||||||
|
# Most of this code is from the Downloader cog.
|
||||||
|
name = repo["name"]
|
||||||
|
branch = repo["branch"]
|
||||||
|
url = repo["url"]
|
||||||
|
cogs = repo["cogs"]
|
||||||
|
|
||||||
|
if "PyLav/Red-Cogs" in url:
|
||||||
|
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."
|
||||||
|
)
|
||||||
|
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."
|
||||||
|
)
|
||||||
|
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
|
||||||
|
)
|
||||||
|
|
||||||
|
except errors.ExistingGitRepo:
|
||||||
|
repo_e.append(f"Repository {name} already exists.")
|
||||||
|
repository = downloader._repo_manager.get_repo(
|
||||||
|
name
|
||||||
|
)
|
||||||
|
self.logger.debug("Repository %s already exists", name)
|
||||||
|
|
||||||
|
except errors.AuthenticationError as err:
|
||||||
|
repo_e.append(f"Authentication error while adding repository {name}. See logs for more information.")
|
||||||
|
self.logger.exception(
|
||||||
|
"Something went wrong whilst cloning %s (to revision %s)",
|
||||||
|
url,
|
||||||
|
branch,
|
||||||
|
exc_info=err,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
except errors.CloningError as err:
|
||||||
|
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,
|
||||||
|
branch,
|
||||||
|
exc_info=err,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
except OSError:
|
||||||
|
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,
|
||||||
|
name,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
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:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
cog_module = await InstalledCog.convert(ctx, cog["name"])
|
||||||
|
except commands.BadArgument:
|
||||||
|
uninstall_e.append(f"Failed to uninstall {cog['name']}")
|
||||||
|
continue
|
||||||
|
cog_modules.append(cog_module)
|
||||||
|
|
||||||
|
for cog in set(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
|
||||||
|
)
|
||||||
|
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
|
||||||
|
)
|
||||||
|
|
||||||
|
for cog in cogs:
|
||||||
|
cog_name = cog["name"]
|
||||||
|
cog_pinned = cog["pinned"]
|
||||||
|
if cog_pinned:
|
||||||
|
commit = cog["commit"]
|
||||||
|
else:
|
||||||
|
commit = None
|
||||||
|
|
||||||
|
# If you're forking this cog, make sure to change these strings!
|
||||||
|
if cog_name == "backup" and "SeaswimmerTheFsh/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]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if not cogs_c:
|
||||||
|
install_e.append(message)
|
||||||
|
self.logger.error(message)
|
||||||
|
continue
|
||||||
|
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}"
|
||||||
|
)
|
||||||
|
self.logger.error(
|
||||||
|
"Failed to install %s due to missing requirements: %s",
|
||||||
|
cog_name,
|
||||||
|
failed_reqs,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
installed_libs = None
|
||||||
|
failed_libs = None
|
||||||
|
|
||||||
|
if cog_pinned:
|
||||||
|
for cog in installed_cogs:
|
||||||
|
cog.pinned = True
|
||||||
|
|
||||||
|
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
|
||||||
|
)
|
||||||
|
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}"
|
||||||
|
)
|
||||||
|
self.logger.error(
|
||||||
|
"Failed to install %s required for %s",
|
||||||
|
lib.name,
|
||||||
|
cog_name,
|
||||||
|
)
|
||||||
|
await ctx.send(
|
||||||
|
"Import complete!",
|
||||||
|
file=text_to_file(
|
||||||
|
f"Repositories:\n{repo_s}\n\nRepository Errors:\n{repo_e}\n\nUninstalled Cogs:\n{uninstall_s}\n\nUninstalled Cogs Errors:\n{uninstall_e}\n\nInstalled Cogs:\n{install_s}\n\nInstalled Cogs Errors:\n{install_e}",
|
||||||
|
"backup.log",
|
||||||
|
),
|
||||||
|
)
|
19
backup/info.json
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
{
|
||||||
|
"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.",
|
||||||
|
"hidden": false,
|
||||||
|
"disabled": false,
|
||||||
|
"min_bot_version": "3.5.6",
|
||||||
|
"max_bot_version": "3.5.9",
|
||||||
|
"min_python_version": [3, 9, 0],
|
||||||
|
"tags": [
|
||||||
|
"utility",
|
||||||
|
"backup",
|
||||||
|
"restore",
|
||||||
|
"migration"
|
||||||
|
]
|
||||||
|
}
|
5
bible/__init__.py
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
from .bible import Bible
|
||||||
|
|
||||||
|
|
||||||
|
async def setup(bot):
|
||||||
|
await bot.add_cog(Bible(bot))
|
324
bible/bible.py
Normal file
|
@ -0,0 +1,324 @@
|
||||||
|
# _____ _
|
||||||
|
# / ____| (_)
|
||||||
|
# | (___ ___ __ _ _____ ___ _ __ ___ _ __ ___ ___ _ __
|
||||||
|
# \___ \ / _ \/ _` / __\ \ /\ / / | '_ ` _ \| '_ ` _ \ / _ \ '__|
|
||||||
|
# ____) | __/ (_| \__ \\ V V /| | | | | | | | | | | | __/ |
|
||||||
|
# |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_|
|
||||||
|
|
||||||
|
import random
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
import aiohttp
|
||||||
|
import numpy as np
|
||||||
|
from discord import Colour, Embed, File
|
||||||
|
from PIL import Image
|
||||||
|
from red_commons.logging import getLogger
|
||||||
|
from redbot.core import Config, commands, data_manager
|
||||||
|
from redbot.core.bot import Red
|
||||||
|
from redbot.core.utils.chat_formatting import error, humanize_list
|
||||||
|
|
||||||
|
import bible.errors
|
||||||
|
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/"
|
||||||
|
|
||||||
|
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.logger = getLogger("red.SeaCogs.Bible")
|
||||||
|
self.config.register_global(bible="de4e12af7f28f599-02")
|
||||||
|
self.config.register_user(bible=None)
|
||||||
|
|
||||||
|
def format_help_for_context(self, ctx: commands.Context) -> str:
|
||||||
|
pre_processed = super().format_help_for_context(ctx) or ""
|
||||||
|
n = "\n" if "\n\n" not in pre_processed else ""
|
||||||
|
text = [
|
||||||
|
f"{pre_processed}{n}",
|
||||||
|
f"Cog Version: **{self.__version__}**",
|
||||||
|
f"Author: {humanize_list(self.__author__)}",
|
||||||
|
f"Documentation: {self.__documentation__}",
|
||||||
|
]
|
||||||
|
return "\n".join(text)
|
||||||
|
|
||||||
|
def get_icon(self, color: Colour) -> File:
|
||||||
|
"""Get the docs.api.bible favicon with a given color."""
|
||||||
|
image_path = data_manager.bundled_data_path(self) / "api.bible-logo.png"
|
||||||
|
image = Image.open(image_path)
|
||||||
|
image = image.convert("RGBA")
|
||||||
|
data = np.array(image)
|
||||||
|
red, green, blue, alpha = data.T # pylint: disable=unused-variable
|
||||||
|
white_areas = (red == 255) & (blue == 255) & (green == 255)
|
||||||
|
data[..., :-1][white_areas.T] = color.to_rgb()
|
||||||
|
image = Image.fromarray(data)
|
||||||
|
|
||||||
|
with BytesIO() as image_binary:
|
||||||
|
image.save(image_binary, "PNG")
|
||||||
|
image_binary.seek(0)
|
||||||
|
return File(image_binary, filename="icon.png", description="API.Bible Icon")
|
||||||
|
|
||||||
|
async def translate_book_name(self, bible_id: str, book_name: str) -> str:
|
||||||
|
"""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 = " ".join(book_name_list)
|
||||||
|
books = await self._get_books(bible_id)
|
||||||
|
for book in books:
|
||||||
|
if book_name in (book["abbreviation"], book["name"]):
|
||||||
|
return book["id"]
|
||||||
|
raise ValueError(error(f"Book {book_name} not found."))
|
||||||
|
|
||||||
|
async def get_version(self, bible_id: str) -> Version:
|
||||||
|
"""Retrieve the version of the Bible being used."""
|
||||||
|
url = f"https://api.scripture.api.bible/v1/bibles/{bible_id}"
|
||||||
|
headers = await self.bot.get_shared_api_tokens("api.bible")
|
||||||
|
|
||||||
|
async with self.session.get(url, headers=headers) as response:
|
||||||
|
data = await response.json()
|
||||||
|
self.logger.debug(
|
||||||
|
"get_version executed with a response code of: %s",
|
||||||
|
response.status,
|
||||||
|
)
|
||||||
|
if response.status == 401:
|
||||||
|
raise bible.errors.Unauthorized()
|
||||||
|
if response.status == 403:
|
||||||
|
raise bible.errors.BibleAccessError()
|
||||||
|
if response.status == 503:
|
||||||
|
raise bible.errors.ServiceUnavailable()
|
||||||
|
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"],
|
||||||
|
)
|
||||||
|
|
||||||
|
async def _get_passage(
|
||||||
|
self,
|
||||||
|
ctx: commands.Context,
|
||||||
|
bible_id: str,
|
||||||
|
passage_id: str,
|
||||||
|
include_verse_numbers: bool,
|
||||||
|
) -> dict:
|
||||||
|
"""Get a Bible passage from the API.bible API."""
|
||||||
|
url = f"https://api.scripture.api.bible/v1/bibles/{bible_id}/passages/{passage_id}"
|
||||||
|
headers = await self.bot.get_shared_api_tokens("api.bible")
|
||||||
|
params = {
|
||||||
|
"fums-version": "3",
|
||||||
|
"content-type": "text",
|
||||||
|
"include-notes": "false",
|
||||||
|
"include-titles": "false",
|
||||||
|
"include-chapter-numbers": "false",
|
||||||
|
"include-verse-numbers": str(include_verse_numbers).lower(),
|
||||||
|
"include-verse-spans": "false",
|
||||||
|
"use-org-id": "false",
|
||||||
|
}
|
||||||
|
|
||||||
|
async with self.session.get(url, headers=headers, params=params) as response:
|
||||||
|
data = await response.json()
|
||||||
|
self.logger.debug(
|
||||||
|
"_get_passage executed with a response code of: %s",
|
||||||
|
response.status,
|
||||||
|
)
|
||||||
|
if response.status == 400:
|
||||||
|
raise bible.errors.InexplicableError()
|
||||||
|
if response.status == 401:
|
||||||
|
raise bible.errors.Unauthorized()
|
||||||
|
if response.status == 403:
|
||||||
|
raise bible.errors.BibleAccessError()
|
||||||
|
if response.status == 404:
|
||||||
|
raise bible.errors.NotFound()
|
||||||
|
if response.status == 503:
|
||||||
|
raise bible.errors.ServiceUnavailable()
|
||||||
|
|
||||||
|
fums_url = "https://fums.api.bible/f3"
|
||||||
|
fums_params = {
|
||||||
|
"t": data["meta"]["fumsToken"],
|
||||||
|
"dId": self.bot.user.id,
|
||||||
|
"sId": ctx.message.created_at.timestamp(),
|
||||||
|
"uId": hash(str(ctx.author.id)),
|
||||||
|
}
|
||||||
|
|
||||||
|
async with self.session.get(fums_url, params=fums_params) as response:
|
||||||
|
self.logger.debug(
|
||||||
|
"_get_passage FUMS executed with a response code of: %s\nDevice ID: %s\nSession ID: %s\nUser ID: %s (%s)",
|
||||||
|
response.status,
|
||||||
|
self.bot.user.id,
|
||||||
|
ctx.message.created_at.timestamp(),
|
||||||
|
hash(str(ctx.author.id)),
|
||||||
|
ctx.author.id,
|
||||||
|
)
|
||||||
|
return data["data"]
|
||||||
|
|
||||||
|
async def _get_books(self, bible_id: str) -> dict:
|
||||||
|
"""Get the books of the Bible from the API.bible API."""
|
||||||
|
url = f"https://api.scripture.api.bible/v1/bibles/{bible_id}/books"
|
||||||
|
headers = await self.bot.get_shared_api_tokens("api.bible")
|
||||||
|
|
||||||
|
async with self.session.get(url, headers=headers) as response:
|
||||||
|
data = await response.json()
|
||||||
|
self.logger.debug(
|
||||||
|
"_get_books executed with a response code of: %s",
|
||||||
|
response.status,
|
||||||
|
)
|
||||||
|
if response.status == 401:
|
||||||
|
raise bible.errors.Unauthorized()
|
||||||
|
if response.status == 403:
|
||||||
|
raise bible.errors.BibleAccessError()
|
||||||
|
if response.status == 503:
|
||||||
|
raise bible.errors.ServiceUnavailable()
|
||||||
|
return data["data"]
|
||||||
|
|
||||||
|
async def _get_chapters(self, bible_id: str, book_id: str) -> dict:
|
||||||
|
"""Get the chapters of a book from the API.bible API."""
|
||||||
|
url = f"https://api.scripture.api.bible/v1/bibles/{bible_id}/books/{book_id}/chapters"
|
||||||
|
headers = await self.bot.get_shared_api_tokens("api.bible")
|
||||||
|
|
||||||
|
async with self.session.get(url, headers=headers) as response:
|
||||||
|
data = await response.json()
|
||||||
|
self.logger.debug(
|
||||||
|
"_get_chapters executed with a response code of: %s",
|
||||||
|
response.status,
|
||||||
|
)
|
||||||
|
if response.status == 401:
|
||||||
|
raise bible.errors.Unauthorized()
|
||||||
|
if response.status == 403:
|
||||||
|
raise bible.errors.BibleAccessError()
|
||||||
|
if response.status == 503:
|
||||||
|
raise bible.errors.ServiceUnavailable()
|
||||||
|
return data["data"]
|
||||||
|
|
||||||
|
async def _get_verses(self, bible_id: str, book_id: str, chapter: int) -> dict:
|
||||||
|
"""Get the verses of a chapter from the API.bible API."""
|
||||||
|
url = f"https://api.scripture.api.bible/v1/bibles/{bible_id}/chapters/{book_id}.{chapter}/verses"
|
||||||
|
headers = await self.bot.get_shared_api_tokens("api.bible")
|
||||||
|
|
||||||
|
async with self.session.get(url, headers=headers) as response:
|
||||||
|
data = await response.json()
|
||||||
|
self.logger.debug(
|
||||||
|
"_get_verses executed with a response code of: %s",
|
||||||
|
response.status,
|
||||||
|
)
|
||||||
|
if response.status == 401:
|
||||||
|
raise bible.errors.Unauthorized()
|
||||||
|
if response.status == 403:
|
||||||
|
raise bible.errors.BibleAccessError()
|
||||||
|
if response.status == 503:
|
||||||
|
raise bible.errors.ServiceUnavailable()
|
||||||
|
return data["data"]
|
||||||
|
|
||||||
|
@commands.group(autohelp=True)
|
||||||
|
async def bible(self, ctx: commands.Context):
|
||||||
|
"""Retrieve Bible verses from the API.bible API."""
|
||||||
|
|
||||||
|
@bible.command(name="passage", aliases=["verse"])
|
||||||
|
async def bible_passage(self, ctx: commands.Context, book: str, passage: str):
|
||||||
|
"""Get a Bible passage.
|
||||||
|
|
||||||
|
Example usage:
|
||||||
|
`[p]bible passage Genesis 1:1`
|
||||||
|
`[p]bible passage John 3:16-3:17`"""
|
||||||
|
bible_id = await self.config.bible()
|
||||||
|
|
||||||
|
try:
|
||||||
|
book_id = await self.translate_book_name(bible_id, book)
|
||||||
|
except ValueError as e:
|
||||||
|
await ctx.send(str(e))
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
version = await self.get_version(bible_id)
|
||||||
|
if len(passage.split("-")) == 2:
|
||||||
|
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
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
passage = await self._get_passage(
|
||||||
|
ctx, bible_id, f"{book_id}.{passage.replace(':', '.')}", False
|
||||||
|
)
|
||||||
|
except (
|
||||||
|
bible.errors.BibleAccessError,
|
||||||
|
bible.errors.NotFound,
|
||||||
|
bible.errors.InexplicableError,
|
||||||
|
bible.errors.ServiceUnavailable,
|
||||||
|
bible.errors.Unauthorized,
|
||||||
|
) as e:
|
||||||
|
await ctx.send(e.message)
|
||||||
|
return
|
||||||
|
|
||||||
|
if len(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("¶ ", ""),
|
||||||
|
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"
|
||||||
|
)
|
||||||
|
await ctx.send(embed=embed, file=icon)
|
||||||
|
else:
|
||||||
|
await ctx.send(f"## {passage['reference']}\n{passage['content']}")
|
||||||
|
|
||||||
|
@bible.command(name="random")
|
||||||
|
async def bible_random(self, ctx: commands.Context):
|
||||||
|
"""Get a random Bible verse."""
|
||||||
|
bible_id = await self.config.bible()
|
||||||
|
|
||||||
|
try:
|
||||||
|
version = await self.get_version(bible_id)
|
||||||
|
books = await self._get_books(bible_id)
|
||||||
|
book = random.choice(books)
|
||||||
|
|
||||||
|
chapters = await self._get_chapters(bible_id, book["id"])
|
||||||
|
chapter = random.choice(chapters)
|
||||||
|
|
||||||
|
verses = await self._get_verses(bible_id, book["id"], chapter["number"])
|
||||||
|
verse = random.choice(verses)["id"]
|
||||||
|
|
||||||
|
passage = await self._get_passage(ctx, bible_id, verse, False)
|
||||||
|
except (
|
||||||
|
bible.errors.BibleAccessError,
|
||||||
|
bible.errors.NotFound,
|
||||||
|
bible.errors.InexplicableError,
|
||||||
|
bible.errors.ServiceUnavailable,
|
||||||
|
bible.errors.Unauthorized,
|
||||||
|
) as e:
|
||||||
|
await ctx.send(e.message)
|
||||||
|
return
|
||||||
|
|
||||||
|
if await ctx.embed_requested():
|
||||||
|
icon = self.get_icon(await ctx.embed_color())
|
||||||
|
embed = Embed(
|
||||||
|
title=f"{passage['reference']}",
|
||||||
|
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"
|
||||||
|
)
|
||||||
|
await ctx.send(embed=embed, file=icon)
|
||||||
|
else:
|
||||||
|
await ctx.send(f"## {passage['reference']}\n{passage['content']}")
|
BIN
bible/data/api.bible-logo.png
Normal file
After Width: | Height: | Size: 20 KiB |
52
bible/errors.py
Normal file
|
@ -0,0 +1,52 @@
|
||||||
|
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."
|
||||||
|
),
|
||||||
|
):
|
||||||
|
super().__init__(message)
|
||||||
|
self.message = message
|
||||||
|
|
||||||
|
|
||||||
|
class Unauthorized(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>)."
|
||||||
|
),
|
||||||
|
):
|
||||||
|
super().__init__(message)
|
||||||
|
self.message = message
|
||||||
|
|
||||||
|
|
||||||
|
class NotFound(Exception):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
message: str = error("The requested passage was not found."),
|
||||||
|
):
|
||||||
|
super().__init__(message)
|
||||||
|
self.message = message
|
||||||
|
|
||||||
|
|
||||||
|
class ServiceUnavailable(Exception):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
message: str = error("The API.Bible service is currently unavailable."),
|
||||||
|
):
|
||||||
|
super().__init__(message)
|
||||||
|
self.message = message
|
||||||
|
|
||||||
|
|
||||||
|
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."
|
||||||
|
),
|
||||||
|
):
|
||||||
|
super().__init__(message)
|
||||||
|
self.message = message
|
18
bible/info.json
Normal file
|
@ -0,0 +1,18 @@
|
||||||
|
{
|
||||||
|
"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",
|
||||||
|
"hidden": false,
|
||||||
|
"disabled": false,
|
||||||
|
"min_bot_version": "3.5.0",
|
||||||
|
"min_python_version": [3, 10, 0],
|
||||||
|
"requirements": ["numpy", "pillow"],
|
||||||
|
"tags": [
|
||||||
|
"fun",
|
||||||
|
"utility",
|
||||||
|
"api"
|
||||||
|
]
|
||||||
|
}
|
26
bible/models.py
Normal file
|
@ -0,0 +1,26 @@
|
||||||
|
class Version:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
bible_id,
|
||||||
|
abbreviation,
|
||||||
|
language,
|
||||||
|
abbreviationLocal,
|
||||||
|
languageLocal,
|
||||||
|
description,
|
||||||
|
descriptionLocal,
|
||||||
|
version_copyright,
|
||||||
|
):
|
||||||
|
self.bible_id = bible_id
|
||||||
|
self.abbreviation = abbreviation
|
||||||
|
self.language = language
|
||||||
|
self.abbreviationLocal = abbreviationLocal
|
||||||
|
self.languageLocal = languageLocal
|
||||||
|
self.description = description
|
||||||
|
self.descriptionLocal = descriptionLocal
|
||||||
|
self.copyright = version_copyright
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return self.abbreviationLocal
|
||||||
|
|
||||||
|
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}")'
|
114
mkdocs.yml
Normal file
|
@ -0,0 +1,114 @@
|
||||||
|
site_name: SeaCogs Documentation
|
||||||
|
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 © 2023-2024, SeaswimmerTheFsh
|
||||||
|
docs_dir: .docs
|
||||||
|
|
||||||
|
site_author: SeaswimmerTheFsh
|
||||||
|
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
|
||||||
|
- Bible: bible.md
|
||||||
|
- Backup: backup.md
|
||||||
|
- Nerdify: nerdify.md
|
||||||
|
- Pterodactyl:
|
||||||
|
- pterodactyl/index.md
|
||||||
|
- Installing Red: pterodactyl/installing-red.md
|
||||||
|
- Getting Started: pterodactyl/getting-started.md
|
||||||
|
- Configuration: pterodactyl/configuration.md
|
||||||
|
- Regex Examples: pterodactyl/regex.md
|
||||||
|
|
||||||
|
plugins:
|
||||||
|
- git-authors
|
||||||
|
- search
|
||||||
|
#- social
|
||||||
|
- git-revision-date-localized:
|
||||||
|
enable_creation_date: true
|
||||||
|
type: timeago
|
||||||
|
- mkdocstrings:
|
||||||
|
default_handler: python
|
||||||
|
handlers:
|
||||||
|
python:
|
||||||
|
paths: [aurora, nerdify]
|
||||||
|
options:
|
||||||
|
docstring_options:
|
||||||
|
ignore_imit_summary: true
|
||||||
|
summary: true
|
||||||
|
show_root_toc_entry: true
|
||||||
|
show_root_heading: true
|
||||||
|
filters:
|
||||||
|
- "!^___"
|
||||||
|
|
||||||
|
markdown_extensions:
|
||||||
|
- abbr
|
||||||
|
- attr_list
|
||||||
|
- md_in_html
|
||||||
|
- tables
|
||||||
|
- pymdownx.blocks.details
|
||||||
|
- pymdownx.blocks.admonition
|
||||||
|
- pymdownx.saneheaders
|
||||||
|
- pymdownx.magiclink
|
||||||
|
- pymdownx.mark
|
||||||
|
- pymdownx.inlinehilite
|
||||||
|
- pymdownx.snippets
|
||||||
|
- pymdownx.superfences
|
||||||
|
- pymdownx.highlight:
|
||||||
|
anchor_linenums: true
|
||||||
|
line_spans: __span
|
||||||
|
pygments_lang_class: true
|
||||||
|
- pymdownx.emoji:
|
||||||
|
emoji_index: !!python/name:material.extensions.emoji.twemoji
|
||||||
|
emoji_generator: !!python/name:material.extensions.emoji.to_svg
|
||||||
|
|
||||||
|
theme:
|
||||||
|
name: material
|
||||||
|
palette:
|
||||||
|
- media: '(prefers-color-scheme: light)'
|
||||||
|
scheme: default
|
||||||
|
primary: white
|
||||||
|
accent: light blue
|
||||||
|
toggle:
|
||||||
|
icon: material/toggle-switch
|
||||||
|
name: Switch to dark mode
|
||||||
|
|
||||||
|
- media: '(prefers-color-scheme: dark)'
|
||||||
|
scheme: slate
|
||||||
|
primary: black
|
||||||
|
accent: light blue
|
||||||
|
toggle:
|
||||||
|
icon: material/toggle-switch-off-outline
|
||||||
|
name: Switch to light mode
|
||||||
|
features:
|
||||||
|
- announce.dismiss
|
||||||
|
- content.code.annotate
|
||||||
|
- content.code.copy
|
||||||
|
- navigation.instant
|
||||||
|
- navigation.instant.progress
|
||||||
|
- navigation.tabs
|
||||||
|
- navigation.tracking
|
||||||
|
- navigation.top
|
||||||
|
- navigation.sections
|
||||||
|
- navigation.indexes
|
||||||
|
- search.suggest
|
||||||
|
- search.highlight
|
||||||
|
- search.share
|
||||||
|
- toc.follow
|
||||||
|
logo: img/logo.png
|
||||||
|
favicon: img/logo.png
|
||||||
|
icon:
|
||||||
|
repo: simple/forgejo
|
||||||
|
|
||||||
|
watch:
|
||||||
|
- ./aurora
|
||||||
|
- ./backup
|
||||||
|
- ./bible
|
||||||
|
- ./nerdify
|
||||||
|
- ./pterodactyl
|
|
@ -1,10 +1,17 @@
|
||||||
{
|
{
|
||||||
"author" : ["SeaswimmerTheFsh"],
|
"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.",
|
"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",
|
"name" : "Nerdify",
|
||||||
"short" : "Nerdify your text!",
|
"short" : "Nerdify your text!",
|
||||||
"description" : "Nerdify your text!",
|
"description" : "Nerdify your text!",
|
||||||
"end_user_data_statement" : "This cog does not store end user data.",
|
"end_user_data_statement" : "This cog does not store end user data.",
|
||||||
"hidden": false,
|
"hidden": false,
|
||||||
"disabled": false
|
"disabled": false,
|
||||||
}
|
"min_bot_version": "3.5.0",
|
||||||
|
"min_python_version": [3, 8, 0],
|
||||||
|
"tags": [
|
||||||
|
"fun",
|
||||||
|
"text",
|
||||||
|
"meme"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
|
@ -7,20 +7,38 @@
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
from contextlib import suppress
|
from contextlib import suppress
|
||||||
from typing import Any, Optional
|
from typing import Any, Optional, Union
|
||||||
|
|
||||||
import discord
|
import discord
|
||||||
from redbot.core import commands
|
from redbot.core import commands
|
||||||
from redbot.core.utils import common_filters
|
from redbot.core.utils import chat_formatting, common_filters
|
||||||
|
|
||||||
|
|
||||||
class Nerdify(commands.Cog):
|
class Nerdify(commands.Cog):
|
||||||
"""Nerdify your text."""
|
"""Nerdify your text."""
|
||||||
|
|
||||||
|
__author__ = ["SeaswimmerTheFsh"]
|
||||||
|
__version__ = "1.3.4"
|
||||||
|
__documentation__ = "https://seacogs.coastalcommits.com/nerdify/"
|
||||||
|
|
||||||
def __init__(self, bot):
|
def __init__(self, bot):
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
|
|
||||||
|
def format_help_for_context(self, ctx: commands.Context) -> str:
|
||||||
|
pre_processed = super().format_help_for_context(ctx) or ""
|
||||||
|
n = "\n" if "\n\n" not in pre_processed else ""
|
||||||
|
text = [
|
||||||
|
f"{pre_processed}{n}",
|
||||||
|
f"Cog Version: **{self.__version__}**",
|
||||||
|
f"Author: {chat_formatting.humanize_list(self.__author__)}",
|
||||||
|
f"Documentation: {self.__documentation__}"
|
||||||
|
]
|
||||||
|
return "\n".join(text)
|
||||||
|
|
||||||
@commands.command(aliases=["nerd"])
|
@commands.command(aliases=["nerd"])
|
||||||
async def nerdify(self, ctx: commands.Context, *, text: Optional[str] = None) -> None:
|
async def nerdify(
|
||||||
|
self, ctx: commands.Context, *, text: Optional[str] = None
|
||||||
|
) -> None:
|
||||||
"""Nerdify the replied to message, previous message, or your own text."""
|
"""Nerdify the replied to message, previous message, or your own text."""
|
||||||
if not text:
|
if not text:
|
||||||
if hasattr(ctx.message, "reference") and ctx.message.reference:
|
if hasattr(ctx.message, "reference") and ctx.message.reference:
|
||||||
|
@ -33,7 +51,10 @@ class Nerdify(commands.Cog):
|
||||||
if not text:
|
if not text:
|
||||||
messages = [message async for message in ctx.channel.history(limit=2)]
|
messages = [message async for message in ctx.channel.history(limit=2)]
|
||||||
# [0] is the command, [1] is the message before the command
|
# [0] is the command, [1] is the message before the command
|
||||||
text = messages[1].content or "I can't translate that!"
|
text = messages[1].content
|
||||||
|
if text == "":
|
||||||
|
await ctx.send(chat_formatting.error("I can't translate that!"))
|
||||||
|
return
|
||||||
await self.type_message(
|
await self.type_message(
|
||||||
ctx.channel,
|
ctx.channel,
|
||||||
self.nerdify_text(text),
|
self.nerdify_text(text),
|
||||||
|
@ -43,16 +64,30 @@ class Nerdify(commands.Cog):
|
||||||
)
|
)
|
||||||
|
|
||||||
def nerdify_text(self, text: str) -> str:
|
def nerdify_text(self, text: str) -> str:
|
||||||
"""Convert text to nerd speak."""
|
"""Convert text to nerd speak.
|
||||||
return f"\"{text}\" 🤓"
|
|
||||||
|
Args:
|
||||||
|
text: The text to convert.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The converted text."""
|
||||||
|
return f'"{text}" 🤓'
|
||||||
|
|
||||||
async def type_message(
|
async def type_message(
|
||||||
self, destination: discord.abc.Messageable, content: str, **kwargs: Any
|
self, destination: discord.abc.Messageable, content: str, **kwargs: Any
|
||||||
) -> discord.Message | None:
|
) -> Union[discord.Message, None]:
|
||||||
"""Simulate typing and sending a message to a destination.
|
"""Simulate typing and sending a message to a destination.
|
||||||
|
|
||||||
Will send a typing indicator, wait a variable amount of time based on the length
|
Will send a typing indicator, wait a variable amount of time based on the length
|
||||||
of the text (to simulate typing speed), then send the message.
|
of the text (to simulate typing speed), then send the message.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
destination: The [destination](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Messageable) to send the message to.
|
||||||
|
content: The content of the message to send.
|
||||||
|
**kwargs: Any keyword arguments to pass to the [destination.send](https://discordpy.readthedocs.io/en/stable/api.html#discord.TextChannel.send) function.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The message sent, or None if an error occurred.
|
||||||
"""
|
"""
|
||||||
content = common_filters.filter_urls(content)
|
content = common_filters.filter_urls(content)
|
||||||
with suppress(discord.HTTPException):
|
with suppress(discord.HTTPException):
|
||||||
|
|
2873
poetry.lock
generated
5
pterodactyl/__init__.py
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
from .pterodactyl import Pterodactyl
|
||||||
|
|
||||||
|
|
||||||
|
async def setup(bot):
|
||||||
|
await bot.add_cog(Pterodactyl(bot))
|
30
pterodactyl/config.py
Normal file
|
@ -0,0 +1,30 @@
|
||||||
|
from redbot.core import Config
|
||||||
|
|
||||||
|
config: Config = Config.get_conf(None, identifier=457581387213637448123567, cog_name="Pterodactyl", force_registration=True)
|
||||||
|
|
||||||
|
def register_config(config_obj: Config) -> None:
|
||||||
|
config_obj.register_global(
|
||||||
|
base_url=None,
|
||||||
|
server_id=None,
|
||||||
|
console_channel=None,
|
||||||
|
console_commands_enabled=False,
|
||||||
|
current_status='',
|
||||||
|
chat_regex=r"^\[\d{2}:\d{2}:\d{2}\sINFO\]: (?!\[(?:Server|Rcon)\])(?:<|\[)(\w+)(?:>|\]) (.*)",
|
||||||
|
server_regex=r"^\[\d{2}:\d{2}:\d{2} INFO\]:(?: \[Not Secure\])? \[(?:Server|Rcon)\] (.*)",
|
||||||
|
join_regex=r"^\[\d{2}:\d{2}:\d{2} INFO\]: ([^<\n]+) joined the game$",
|
||||||
|
leave_regex=r"^\[\d{2}:\d{2}:\d{2} INFO\]: ([^<\n]+) left the game$",
|
||||||
|
achievement_regex=r"^\[\d{2}:\d{2}:\d{2} INFO\]: (.*) has (made the advancement|completed the challenge) \[(.*)\]$",
|
||||||
|
chat_command='tellraw @a ["",{"text":".$N ","color":".$C","insertion":"<@.$I>","hoverEvent":{"action":"show_text","contents":"Shift click to mention this user inside Discord"}},{"text":"(DISCORD):","color":"blue","clickEvent":{"action":"open_url","value":".$V"},"hoverEvent":{"action":"show_text","contents":"Click to join the Discord Server"}},{"text":" .$M","color":"white"}]', # noqa: E501
|
||||||
|
topic='Server IP: .$H\nServer Players: .$P/.$M',
|
||||||
|
topic_hostname=None,
|
||||||
|
topic_port=25565,
|
||||||
|
api_endpoint="minecraft",
|
||||||
|
chat_channel=None,
|
||||||
|
startup_msg='Server started!',
|
||||||
|
shutdown_msg='Server stopped!',
|
||||||
|
join_msg='Welcome to the server! 👋',
|
||||||
|
leave_msg='Goodbye! 👋',
|
||||||
|
mask_ip=True,
|
||||||
|
invite=None,
|
||||||
|
regex_blacklist={},
|
||||||
|
)
|
19
pterodactyl/info.json
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
{
|
||||||
|
"author" : ["SeaswimmerTheFsh (seasw.)"],
|
||||||
|
"install_msg" : "Thank you for installing Pterodactyl!\nYou can find the source code of this cog [here](https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs).\nDocumentation can be found [here](https://seacogs.coastalcommits.com/pterodactyl ).",
|
||||||
|
"name" : "Pterodactyl",
|
||||||
|
"short" : "Interface with Pterodactyl through websockets.",
|
||||||
|
"description" : "Interface with Pterodactyl through websockets.",
|
||||||
|
"end_user_data_statement" : "This cog does not store end user data.",
|
||||||
|
"hidden": false,
|
||||||
|
"disabled": false,
|
||||||
|
"min_bot_version": "3.5.0",
|
||||||
|
"min_python_version": [3, 8, 0],
|
||||||
|
"requirements": ["git+https://github.com/SeaswimmerTheFsh/pydactyl", "websockets"],
|
||||||
|
"tags": [
|
||||||
|
"pterodactyl",
|
||||||
|
"minecraft",
|
||||||
|
"server",
|
||||||
|
"management"
|
||||||
|
]
|
||||||
|
}
|
9
pterodactyl/logger.py
Normal file
|
@ -0,0 +1,9 @@
|
||||||
|
from red_commons import logging
|
||||||
|
from red_commons.logging import getLogger
|
||||||
|
|
||||||
|
logger = getLogger('red.SeaCogs.Pterodactyl')
|
||||||
|
websocket_logger = getLogger('red.SeaCogs.Pterodactyl.websocket')
|
||||||
|
if logger.level >= logging.VERBOSE:
|
||||||
|
websocket_logger.setLevel(logging.logging.INFO)
|
||||||
|
elif logger.level < logging.VERBOSE:
|
||||||
|
websocket_logger.setLevel(logging.logging.DEBUG)
|
10
pterodactyl/mcsrvstatus.py
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
import aiohttp
|
||||||
|
|
||||||
|
|
||||||
|
async def get_status(host, port = 25565) -> tuple[bool, dict]:
|
||||||
|
async with aiohttp.ClientSession() as session:
|
||||||
|
async with session.get(f'https://api.mcsrvstat.us/2/{host}:{port}') as response:
|
||||||
|
response = await response.json()
|
||||||
|
if response['online']:
|
||||||
|
return (True, response)
|
||||||
|
return (False, response)
|
627
pterodactyl/pterodactyl.py
Normal file
|
@ -0,0 +1,627 @@
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
from typing import Mapping, Optional, Tuple, Union
|
||||||
|
|
||||||
|
import discord
|
||||||
|
import websockets
|
||||||
|
from discord.ext import tasks
|
||||||
|
from pydactyl import PterodactylClient
|
||||||
|
from redbot.core import app_commands, commands
|
||||||
|
from redbot.core.app_commands import Choice
|
||||||
|
from redbot.core.bot import Red
|
||||||
|
from redbot.core.utils.chat_formatting import box, error, humanize_list
|
||||||
|
from redbot.core.utils.views import ConfirmView
|
||||||
|
|
||||||
|
from pterodactyl import mcsrvstatus
|
||||||
|
from pterodactyl.config import config, register_config
|
||||||
|
from pterodactyl.logger import logger
|
||||||
|
|
||||||
|
|
||||||
|
class Pterodactyl(commands.Cog):
|
||||||
|
"""Pterodactyl allows you to manage your Pterodactyl Panel from Discord."""
|
||||||
|
|
||||||
|
__author__ = ["SeaswimmerTheFsh"]
|
||||||
|
__version__ = "2.0.0"
|
||||||
|
__documentation__ = "https://seacogs.coastalcommits.com/pterodactyl/"
|
||||||
|
|
||||||
|
def __init__(self, bot: Red):
|
||||||
|
self.bot = bot
|
||||||
|
self.client: Optional[PterodactylClient] = None
|
||||||
|
self.task: Optional[asyncio.Task] = None
|
||||||
|
self.websocket: Optional[websockets.WebSocketClientProtocol] = None
|
||||||
|
self.retry_counter: int = 0
|
||||||
|
register_config(config)
|
||||||
|
self.task = self.get_task()
|
||||||
|
self.update_topic.start()
|
||||||
|
|
||||||
|
def format_help_for_context(self, ctx: commands.Context) -> str:
|
||||||
|
pre_processed = super().format_help_for_context(ctx) or ""
|
||||||
|
n = "\n" if "\n\n" not in pre_processed else ""
|
||||||
|
text = [
|
||||||
|
f"{pre_processed}{n}",
|
||||||
|
f"Cog Version: **{self.__version__}**",
|
||||||
|
f"Author: {humanize_list(self.__author__)}",
|
||||||
|
f"Documentation: {self.__documentation__}",
|
||||||
|
]
|
||||||
|
return "\n".join(text)
|
||||||
|
|
||||||
|
async def cog_unload(self) -> None:
|
||||||
|
self.update_topic.cancel()
|
||||||
|
self.task.cancel()
|
||||||
|
self.retry_counter = 0
|
||||||
|
await self.client._session.close() # pylint: disable=protected-access
|
||||||
|
|
||||||
|
def get_task(self) -> asyncio.Task:
|
||||||
|
from pterodactyl.websocket import establish_websocket_connection
|
||||||
|
task = self.bot.loop.create_task(establish_websocket_connection(self), name="Pterodactyl Websocket Connection")
|
||||||
|
task.add_done_callback(self.error_callback)
|
||||||
|
return task
|
||||||
|
|
||||||
|
def error_callback(self, fut) -> None: #NOTE - Thanks flame442 and zephyrkul for helping me figure this out
|
||||||
|
try:
|
||||||
|
fut.result()
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
logger.info("WebSocket task has been cancelled.")
|
||||||
|
except Exception as e: # pylint: disable=broad-exception-caught
|
||||||
|
logger.error("WebSocket task has failed: %s", e, exc_info=e)
|
||||||
|
self.task.cancel()
|
||||||
|
if self.retry_counter < 5:
|
||||||
|
self.retry_counter += 1
|
||||||
|
logger.info("Retrying in %s seconds...", 5 * self.retry_counter)
|
||||||
|
self.task = self.bot.loop.call_later(5 * self.retry_counter, self.get_task)
|
||||||
|
else:
|
||||||
|
logger.info("Retry limit reached. Stopping task.")
|
||||||
|
|
||||||
|
@tasks.loop(minutes=6)
|
||||||
|
async def update_topic(self):
|
||||||
|
await self.bot.wait_until_red_ready()
|
||||||
|
topic = await self.get_topic()
|
||||||
|
console = self.bot.get_channel(await config.console_channel())
|
||||||
|
chat = self.bot.get_channel(await config.chat_channel())
|
||||||
|
if console:
|
||||||
|
await console.edit(topic=topic)
|
||||||
|
if chat:
|
||||||
|
await chat.edit(topic=topic)
|
||||||
|
|
||||||
|
@commands.Cog.listener()
|
||||||
|
async def on_message_without_command(self, message: discord.Message) -> None:
|
||||||
|
if message.channel.id == await config.console_channel() and message.author.bot is False:
|
||||||
|
if await config.console_commands_enabled() is False:
|
||||||
|
await message.channel.send("Console commands are disabled.")
|
||||||
|
logger.debug("Received console command from %s, but console commands are disabled: %s", message.author.id, message.content)
|
||||||
|
return
|
||||||
|
logger.debug("Received console command from %s: %s", message.author.id, message.content)
|
||||||
|
await message.channel.send(f"Received console command from {message.author.id}: {message.content[:1900]}", allowed_mentions=discord.AllowedMentions.none())
|
||||||
|
try:
|
||||||
|
await self.websocket.send(json.dumps({"event": "send command", "args": [message.content]}))
|
||||||
|
except websockets.exceptions.ConnectionClosed as e:
|
||||||
|
logger.error("WebSocket connection closed: %s", e)
|
||||||
|
self.task.cancel()
|
||||||
|
self.retry_counter = 0
|
||||||
|
self.task = self.get_task()
|
||||||
|
if message.channel.id == await config.chat_channel() and message.author.bot is False:
|
||||||
|
logger.debug("Received chat message from %s: %s", message.author.id, message.content)
|
||||||
|
channel = self.bot.get_channel(await config.console_channel())
|
||||||
|
if channel:
|
||||||
|
await channel.send(f"Received chat message from {message.author.id}: {message.content[:1900]}", allowed_mentions=discord.AllowedMentions.none())
|
||||||
|
msg = json.dumps({"event": "send command", "args": [await self.get_chat_command(message)]})
|
||||||
|
logger.debug("Sending chat message to server:\n%s", msg)
|
||||||
|
try:
|
||||||
|
await self.websocket.send(msg)
|
||||||
|
except websockets.exceptions.ConnectionClosed as e:
|
||||||
|
logger.error("WebSocket connection closed: %s", e)
|
||||||
|
self.task.cancel()
|
||||||
|
self.retry_counter = 0
|
||||||
|
self.task = self.get_task()
|
||||||
|
|
||||||
|
async def get_topic(self) -> str:
|
||||||
|
topic: str = await config.topic()
|
||||||
|
placeholders = {
|
||||||
|
"H": await config.topic_hostname() or "unset",
|
||||||
|
"O": str(await config.topic_port()),
|
||||||
|
}
|
||||||
|
if await config.api_endpoint() == "minecraft":
|
||||||
|
status, response = await mcsrvstatus.get_status(await config.topic_hostname(), await config.topic_port())
|
||||||
|
if status:
|
||||||
|
placeholders.update({
|
||||||
|
"I": response['ip'],
|
||||||
|
"M": str(response['players']['max']),
|
||||||
|
"P": str(response['players']['online']),
|
||||||
|
"V": response['version'],
|
||||||
|
"D": response['motd']['clean'][0] if response['motd']['clean'] else "unset",
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
placeholders.update({
|
||||||
|
"I": response['ip'],
|
||||||
|
"M": "0",
|
||||||
|
"P": "0",
|
||||||
|
"V": "Server Offline",
|
||||||
|
"D": "Server Offline",
|
||||||
|
})
|
||||||
|
for key, value in placeholders.items():
|
||||||
|
topic = topic.replace('.$' + key, value)
|
||||||
|
return topic
|
||||||
|
|
||||||
|
async def get_chat_command(self, message: discord.Message) -> str:
|
||||||
|
command: str = await config.chat_command()
|
||||||
|
placeholders = {
|
||||||
|
"C": str(message.author.color),
|
||||||
|
"D": message.author.discriminator,
|
||||||
|
"I": str(message.author.id),
|
||||||
|
"M": message.content.replace('"','').replace("\n", " "),
|
||||||
|
"N": message.author.display_name,
|
||||||
|
"U": message.author.name,
|
||||||
|
"V": await config.invite() or "use [p]pterodactyl config invite to change me",
|
||||||
|
}
|
||||||
|
for key, value in placeholders.items():
|
||||||
|
command = command.replace('.$' + key, value)
|
||||||
|
return command
|
||||||
|
|
||||||
|
async def get_player_list(self) -> Optional[Tuple[str, list]]:
|
||||||
|
if await config.api_endpoint() == "minecraft":
|
||||||
|
status, response = await mcsrvstatus.get_status(await config.topic_hostname(), await config.topic_port())
|
||||||
|
if status and 'list' in response['players']:
|
||||||
|
output_str = '\n'.join(response['players']['list'])
|
||||||
|
return output_str, response['players']['list']
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def get_player_list_embed(self, ctx: Union[commands.Context, discord.Interaction]) -> Optional[discord.Embed]:
|
||||||
|
player_list = await self.get_player_list()
|
||||||
|
if player_list:
|
||||||
|
embed = discord.Embed(color=await self.bot.get_embed_color(ctx.channel), title="Players Online")
|
||||||
|
embed.description = player_list[0]
|
||||||
|
return embed
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def power(self, ctx: Union[discord.Interaction, commands.Context], action: str, action_ing: str, warning: str = '') -> None:
|
||||||
|
if isinstance(ctx, discord.Interaction):
|
||||||
|
author = ctx.user
|
||||||
|
else:
|
||||||
|
author = ctx.author
|
||||||
|
|
||||||
|
current_status = await config.current_status()
|
||||||
|
|
||||||
|
if current_status == action_ing:
|
||||||
|
if isinstance(ctx, discord.Interaction):
|
||||||
|
return await ctx.response.send_message(f"Server is already {action_ing}.", ephemeral=True)
|
||||||
|
return await ctx.send(f"Server is already {action_ing}.")
|
||||||
|
|
||||||
|
if current_status in ["starting", "stopping"] and action != "kill":
|
||||||
|
if isinstance(ctx, discord.Interaction):
|
||||||
|
return await ctx.response.send_message("Another power action is already in progress.", ephemeral=True)
|
||||||
|
return await ctx.send("Another power action is already in progress.")
|
||||||
|
|
||||||
|
view = ConfirmView(author, disable_buttons=True)
|
||||||
|
|
||||||
|
if isinstance(ctx, discord.Interaction):
|
||||||
|
await ctx.response.send_message(f"{warning}Are you sure you want to {action} the server?", view=view)
|
||||||
|
else:
|
||||||
|
message = await ctx.send(f"{warning}Are you sure you want to {action} the server?", view=view)
|
||||||
|
|
||||||
|
await view.wait()
|
||||||
|
|
||||||
|
if view.result is True:
|
||||||
|
if isinstance(ctx, discord.Interaction):
|
||||||
|
await ctx.edit_original_response(content=f"Sending websocket command to {action} server...", view=None)
|
||||||
|
else:
|
||||||
|
await message.edit(content=f"Sending websocket command to {action} server...", view=None)
|
||||||
|
|
||||||
|
await self.websocket.send(json.dumps({"event": "set state", "args": [action]}))
|
||||||
|
|
||||||
|
if isinstance(ctx, discord.Interaction):
|
||||||
|
await ctx.edit_original_response(content=f"Server {action_ing}", view=None)
|
||||||
|
else:
|
||||||
|
await message.edit(content=f"Server {action_ing}", view=None)
|
||||||
|
|
||||||
|
else:
|
||||||
|
if isinstance(ctx, discord.Interaction):
|
||||||
|
await ctx.edit_original_response(content="Cancelled.", view=None)
|
||||||
|
else:
|
||||||
|
await message.edit(content="Cancelled.", view=None)
|
||||||
|
|
||||||
|
async def send_command(self, ctx: Union[discord.Interaction, commands.Context], command: str):
|
||||||
|
channel = self.bot.get_channel(await config.console_channel())
|
||||||
|
if isinstance(ctx, discord.Interaction):
|
||||||
|
if channel:
|
||||||
|
await channel.send(f"Received console command from {ctx.user.id}: {command[:1900]}", allowed_mentions=discord.AllowedMentions.none())
|
||||||
|
try:
|
||||||
|
await self.websocket.send(json.dumps({"event": "send command", "args": [command]}))
|
||||||
|
await ctx.response.send_message(f"Command sent to server. {box(command, 'json')}", ephemeral=True)
|
||||||
|
except websockets.exceptions.ConnectionClosed as e:
|
||||||
|
logger.error("WebSocket connection closed: %s", e)
|
||||||
|
await ctx.response.send_message(error("WebSocket connection closed."))
|
||||||
|
self.task.cancel()
|
||||||
|
self.retry_counter = 0
|
||||||
|
self.task = self.get_task()
|
||||||
|
else:
|
||||||
|
if channel:
|
||||||
|
await channel.send(f"Received console command from {ctx.author.id}: {command[:1900]}", allowed_mentions=discord.AllowedMentions.none())
|
||||||
|
try:
|
||||||
|
await self.websocket.send(json.dumps({"event": "send command", "args": [command]}))
|
||||||
|
await ctx.send(f"Command sent to server. {box(command, 'json')}")
|
||||||
|
except websockets.exceptions.ConnectionClosed as e:
|
||||||
|
logger.error("WebSocket connection closed: %s", e)
|
||||||
|
await ctx.send(error("WebSocket connection closed."))
|
||||||
|
self.task.cancel()
|
||||||
|
self.retry_counter = 0
|
||||||
|
self.task = self.get_task()
|
||||||
|
|
||||||
|
@commands.Cog.listener()
|
||||||
|
async def on_red_api_tokens_update(self, service_name: str, api_tokens: Mapping[str,str]): # pylint: disable=unused-argument
|
||||||
|
if service_name == "pterodactyl":
|
||||||
|
logger.info("Configuration value set: api_key\nRestarting task...")
|
||||||
|
self.task.cancel()
|
||||||
|
self.retry_counter = 0
|
||||||
|
self.task = self.get_task()
|
||||||
|
|
||||||
|
slash_pterodactyl = app_commands.Group(name="pterodactyl", description="Pterodactyl allows you to manage your Pterodactyl Panel from Discord.")
|
||||||
|
|
||||||
|
@slash_pterodactyl.command(name = "command", description = "Send a command to the server console.")
|
||||||
|
async def slash_pterodactyl_command(self, interaction: discord.Interaction, command: str) -> None:
|
||||||
|
"""Send a command to the server console.
|
||||||
|
|
||||||
|
Parameters:
|
||||||
|
-----------
|
||||||
|
command: str
|
||||||
|
The command to send to the server."""
|
||||||
|
return await self.send_command(interaction, command)
|
||||||
|
|
||||||
|
@slash_pterodactyl.command(name = "players", description = "Retrieve a list of players on the server.")
|
||||||
|
async def slash_pterodactyl_players(self, interaction: discord.Interaction) -> None:
|
||||||
|
"""Retrieve a list of players on the server."""
|
||||||
|
e = await self.get_player_list_embed(interaction)
|
||||||
|
if e:
|
||||||
|
await interaction.response.send_message(embed=e, ephemeral=True)
|
||||||
|
else:
|
||||||
|
await interaction.response.send_message("No players online.", ephemeral=True)
|
||||||
|
|
||||||
|
@slash_pterodactyl.command(name = "power", description = "Send power actions to the server.")
|
||||||
|
@app_commands.choices(action=[
|
||||||
|
Choice(name="Start", value="start"),
|
||||||
|
Choice(name="Stop", value="stop"),
|
||||||
|
Choice(name="Restart", value="restart"),
|
||||||
|
Choice(name="⚠️ Kill ⚠️", value="kill")
|
||||||
|
])
|
||||||
|
async def slash_pterodactyl_power(self, interaction: discord.Interaction, action: app_commands.Choice[str]) -> None:
|
||||||
|
"""Send power actions to the server.
|
||||||
|
|
||||||
|
Parameters:
|
||||||
|
-----------
|
||||||
|
action: app_commands.Choice[str]
|
||||||
|
The action to perform on the server."""
|
||||||
|
if action.value == "kill":
|
||||||
|
return await self.power(interaction, action.value, "stopping... (forcefully killed)", warning="**⚠️ Forcefully killing the server process can corrupt data in some cases. ⚠️**\n")
|
||||||
|
if action.value == "stop":
|
||||||
|
return await self.power(interaction, action.value, "stopping...")
|
||||||
|
return await self.power(interaction, action.value, f"{action.value}ing...")
|
||||||
|
|
||||||
|
@commands.group(autohelp = True, name = "pterodactyl", aliases = ["ptero"])
|
||||||
|
async def pterodactyl(self, ctx: commands.Context) -> None:
|
||||||
|
"""Pterodactyl allows you to manage your Pterodactyl Panel from Discord."""
|
||||||
|
|
||||||
|
@pterodactyl.command(name = "players", aliases=["list", "online", "playerlist", "who"])
|
||||||
|
async def pterodactyl_players(self, ctx: commands.Context) -> None:
|
||||||
|
"""Retrieve a list of players on the server."""
|
||||||
|
e = await self.get_player_list_embed(ctx)
|
||||||
|
if e:
|
||||||
|
await ctx.send(embed=e)
|
||||||
|
else:
|
||||||
|
await ctx.send("No players online.")
|
||||||
|
|
||||||
|
@pterodactyl.command(name = "command", aliases = ["cmd", "execute", "exec"])
|
||||||
|
@commands.admin()
|
||||||
|
async def pterodactyl_command(self, ctx: commands.Context, *, command: str) -> None:
|
||||||
|
"""Send a command to the server console."""
|
||||||
|
return await self.send_command(ctx, command)
|
||||||
|
|
||||||
|
@pterodactyl.group(autohelp = True, name = "power")
|
||||||
|
@commands.admin()
|
||||||
|
async def pterodactyl_power(self, ctx: commands.Context) -> None:
|
||||||
|
"""Send power actions to the server."""
|
||||||
|
|
||||||
|
@pterodactyl_power.command(name = "start")
|
||||||
|
async def pterodactyl_power_start(self, ctx: commands.Context) -> Optional[discord.Message]:
|
||||||
|
"""Start the server."""
|
||||||
|
return await self.power(ctx, "start", "starting...")
|
||||||
|
|
||||||
|
@pterodactyl_power.command(name = "stop")
|
||||||
|
async def pterodactyl_power_stop(self, ctx: commands.Context) -> Optional[discord.Message]:
|
||||||
|
"""Stop the server."""
|
||||||
|
return await self.power(ctx, "stop", "stopping...")
|
||||||
|
|
||||||
|
@pterodactyl_power.command(name = "restart")
|
||||||
|
async def pterodactyl_power_restart(self, ctx: commands.Context) -> Optional[discord.Message]:
|
||||||
|
"""Restart the server."""
|
||||||
|
return await self.power(ctx, "restart", "restarting...")
|
||||||
|
|
||||||
|
@pterodactyl_power.command(name = "kill")
|
||||||
|
async def pterodactyl_power_kill(self, ctx: commands.Context) -> Optional[discord.Message]:
|
||||||
|
"""Kill the server."""
|
||||||
|
return await self.power(ctx, "kill", "stopping... (forcefully killed)", warning="**⚠️ Forcefully killing the server process can corrupt data in some cases. ⚠️**\n")
|
||||||
|
|
||||||
|
@pterodactyl.group(autohelp = True, name = "config", aliases = ["settings", "set"])
|
||||||
|
@commands.is_owner()
|
||||||
|
async def pterodactyl_config(self, ctx: commands.Context) -> None:
|
||||||
|
"""Configure Pterodactyl settings."""
|
||||||
|
|
||||||
|
@pterodactyl_config.command(name = "url")
|
||||||
|
async def pterodactyl_config_base_url(self, ctx: commands.Context, *, base_url: str) -> None:
|
||||||
|
"""Set the base URL of your Pterodactyl Panel.
|
||||||
|
|
||||||
|
Please include the protocol (http/https).
|
||||||
|
Example: `https://panel.example.com`"""
|
||||||
|
await config.base_url.set(base_url)
|
||||||
|
await ctx.send(f"Base URL set to {base_url}")
|
||||||
|
logger.info("Configuration value set: base_url = %s\nRestarting task...", base_url)
|
||||||
|
self.task.cancel()
|
||||||
|
self.retry_counter = 0
|
||||||
|
self.task = self.get_task()
|
||||||
|
|
||||||
|
@pterodactyl_config.command(name = "serverid")
|
||||||
|
async def pterodactyl_config_server_id(self, ctx: commands.Context, *, server_id: str) -> None:
|
||||||
|
"""Set the ID of your server."""
|
||||||
|
await config.server_id.set(server_id)
|
||||||
|
await ctx.send(f"Server ID set to {server_id}")
|
||||||
|
logger.info("Configuration value set: server_id = %s\nRestarting task...", server_id)
|
||||||
|
self.task.cancel()
|
||||||
|
self.retry_counter = 0
|
||||||
|
self.task = self.get_task()
|
||||||
|
|
||||||
|
@pterodactyl_config.group(name = "console")
|
||||||
|
async def pterodactyl_config_console(self, ctx: commands.Context):
|
||||||
|
"""Configure console settings."""
|
||||||
|
|
||||||
|
@pterodactyl_config_console.command(name = "channel")
|
||||||
|
async def pterodactyl_config_console_channel(self, ctx: commands.Context, channel: discord.TextChannel) -> None:
|
||||||
|
"""Set the channel to send console output to."""
|
||||||
|
await config.console_channel.set(channel.id)
|
||||||
|
await ctx.send(f"Console channel set to {channel.mention}")
|
||||||
|
|
||||||
|
@pterodactyl_config_console.command(name = "commands")
|
||||||
|
async def pterodactyl_config_console_commands(self, ctx: commands.Context, enabled: bool) -> None:
|
||||||
|
"""Enable or disable console commands."""
|
||||||
|
await config.console_commands_enabled.set(enabled)
|
||||||
|
await ctx.send(f"Console commands set to {enabled}")
|
||||||
|
|
||||||
|
@pterodactyl_config.command(name = "invite")
|
||||||
|
async def pterodactyl_config_invite(self, ctx: commands.Context, invite: str) -> None:
|
||||||
|
"""Set the invite link for your server."""
|
||||||
|
await config.invite.set(invite)
|
||||||
|
await ctx.send(f"Invite link set to {invite}")
|
||||||
|
|
||||||
|
@pterodactyl_config.group(name = "topic")
|
||||||
|
async def pterodactyl_config_topic(self, ctx: commands.Context):
|
||||||
|
"""Set the topic for the console and chat channels."""
|
||||||
|
|
||||||
|
@pterodactyl_config_topic.command(name = "host", aliases = ["hostname", "ip"])
|
||||||
|
async def pterodactyl_config_topic_host(self, ctx: commands.Context, host: str) -> None:
|
||||||
|
"""Set the hostname or IP address of your server."""
|
||||||
|
await config.topic_hostname.set(host)
|
||||||
|
await ctx.send(f"Hostname/IP set to `{host}`")
|
||||||
|
|
||||||
|
@pterodactyl_config_topic.command(name = "port")
|
||||||
|
async def pterodactyl_config_topic_port(self, ctx: commands.Context, port: int) -> None:
|
||||||
|
"""Set the port of your server."""
|
||||||
|
await config.topic_port.set(port)
|
||||||
|
await ctx.send(f"Port set to `{port}`")
|
||||||
|
|
||||||
|
@pterodactyl_config_topic.command(name = "text")
|
||||||
|
async def pterodactyl_config_topic_text(self, ctx: commands.Context, *, text: str) -> None:
|
||||||
|
"""Set the text for the console and chat channels.
|
||||||
|
|
||||||
|
Available placeholders:
|
||||||
|
- `.$H` (hostname)
|
||||||
|
- `.$O` (port)
|
||||||
|
Available for Minecraft servers:
|
||||||
|
- `.$I` (ip)
|
||||||
|
- `.$M` (max players)
|
||||||
|
- `.$P` (players online)
|
||||||
|
- `.$V` (version)
|
||||||
|
- `.$D` (description / Message of the Day)"""
|
||||||
|
await config.topic.set(text)
|
||||||
|
await ctx.send(f"Topic set to:\n{box(text, 'yaml')}")
|
||||||
|
|
||||||
|
@pterodactyl_config.group(name = "chat")
|
||||||
|
async def pterodactyl_config_chat(self, ctx: commands.Context):
|
||||||
|
"""Configure chat settings."""
|
||||||
|
|
||||||
|
@pterodactyl_config_chat.command(name = "channel")
|
||||||
|
async def pterodactyl_config_chat_channel(self, ctx: commands.Context, channel: discord.TextChannel) -> None:
|
||||||
|
"""Set the channel to send chat output to."""
|
||||||
|
await config.chat_channel.set(channel.id)
|
||||||
|
await ctx.send(f"Chat channel set to {channel.mention}")
|
||||||
|
|
||||||
|
@pterodactyl_config_chat.command(name = "command")
|
||||||
|
async def pterodactyl_config_chat_command(self, ctx: commands.Context, *, command: str) -> None:
|
||||||
|
"""Set the command that will be used to send messages from Discord.
|
||||||
|
|
||||||
|
Required placeholders: `.$U` (username), `.$M` (message), `.$C` (color)
|
||||||
|
See [documentation](https://seacogs.coastalcommits.com/pterodactyl/setup/#changing-the-tellraw-command) for more information."""
|
||||||
|
await config.chat_command.set(command)
|
||||||
|
await ctx.send(f"Chat command set to:\n{box(command, 'json')}")
|
||||||
|
|
||||||
|
@pterodactyl_config.group(name = "regex")
|
||||||
|
async def pterodactyl_config_regex(self, ctx: commands.Context) -> None:
|
||||||
|
"""Set regex patterns."""
|
||||||
|
|
||||||
|
@pterodactyl_config_regex.command(name = "chat")
|
||||||
|
async def pterodactyl_config_regex_chat(self, ctx: commands.Context, *, regex: str) -> None:
|
||||||
|
"""Set the regex pattern to match chat messages on the server.
|
||||||
|
|
||||||
|
See [documentation](https://seacogs.coastalcommits.com/pterodactyl/setup/#my-chat-messages-arent-detected) for more information."""
|
||||||
|
await config.chat_regex.set(regex)
|
||||||
|
await ctx.send(f"Chat regex set to:\n{box(regex, 'regex')}")
|
||||||
|
|
||||||
|
@pterodactyl_config_regex.command(name = "server")
|
||||||
|
async def pterodactyl_config_regex_server(self, ctx: commands.Context, *, regex: str) -> None:
|
||||||
|
"""Set the regex pattern to match server messages on the server.
|
||||||
|
|
||||||
|
See [documentation](https://seacogs.coastalcommits.com/pterodactyl/setup/#my-chat-messages-arent-detected) for more information."""
|
||||||
|
await config.server_regex.set(regex)
|
||||||
|
await ctx.send(f"Server regex set to:\n{box(regex, 'regex')}")
|
||||||
|
|
||||||
|
@pterodactyl_config_regex.command(name = "join")
|
||||||
|
async def pterodactyl_config_regex_join(self, ctx: commands.Context, *, regex: str) -> None:
|
||||||
|
"""Set the regex pattern to match join messages on the server.
|
||||||
|
|
||||||
|
See [documentation](https://seacogs.coastalcommits.com/pterodactyl/setup/#my-chat-messages-arent-detected) for more information."""
|
||||||
|
await config.join_regex.set(regex)
|
||||||
|
await ctx.send(f"Join regex set to:\n{box(regex, 'regex')}")
|
||||||
|
|
||||||
|
@pterodactyl_config_regex.command(name = "leave")
|
||||||
|
async def pterodactyl_config_regex_leave(self, ctx: commands.Context, *, regex: str) -> None:
|
||||||
|
"""Set the regex pattern to match leave messages on the server.
|
||||||
|
|
||||||
|
See [documentation](https://seacogs.coastalcommits.com/pterodactyl/setup/#my-chat-messages-arent-detected) for more information."""
|
||||||
|
await config.leave_regex.set(regex)
|
||||||
|
await ctx.send(f"Leave regex set to:\n{box(regex, 'regex')}")
|
||||||
|
|
||||||
|
@pterodactyl_config_regex.command(name = "achievement")
|
||||||
|
async def pterodactyl_config_regex_achievement(self, ctx: commands.Context, *, regex: str) -> None:
|
||||||
|
"""Set the regex pattern to match achievement messages on the server.
|
||||||
|
|
||||||
|
See [documentation](https://seacogs.coastalcommits.com/pterodactyl/setup/#my-chat-messages-arent-detected) for more information."""
|
||||||
|
await config.achievement_regex.set(regex)
|
||||||
|
await ctx.send(f"Achievement regex set to:\n{box(regex, 'regex')}")
|
||||||
|
|
||||||
|
@pterodactyl_config.group(name = "messages", aliases = ['msg', 'msgs', 'message'])
|
||||||
|
async def pterodactyl_config_messages(self, ctx: commands.Context):
|
||||||
|
"""Configure message settings."""
|
||||||
|
|
||||||
|
@pterodactyl_config_messages.command(name = "startup")
|
||||||
|
async def pterodactyl_config_messages_startup(self, ctx: commands.Context, *, message: str) -> None:
|
||||||
|
"""Set the message that will be sent when the server starts."""
|
||||||
|
await config.startup_msg.set(message)
|
||||||
|
await ctx.send(f"Startup message set to: {message}")
|
||||||
|
|
||||||
|
@pterodactyl_config_messages.command(name = "shutdown")
|
||||||
|
async def pterodactyl_config_messages_shutdown(self, ctx: commands.Context, *, message: str) -> None:
|
||||||
|
"""Set the message that will be sent when the server stops."""
|
||||||
|
await config.shutdown_msg.set(message)
|
||||||
|
await ctx.send(f"Shutdown message set to: {message}")
|
||||||
|
|
||||||
|
@pterodactyl_config_messages.command(name = "join")
|
||||||
|
async def pterodactyl_config_messages_join(self, ctx: commands.Context, *, message: str) -> None:
|
||||||
|
"""Set the message that will be sent when a user joins the server. This is only shown in embeds."""
|
||||||
|
await config.join_msg.set(message)
|
||||||
|
await ctx.send(f"Join message set to: {message}")
|
||||||
|
|
||||||
|
@pterodactyl_config_messages.command(name = "leave")
|
||||||
|
async def pterodactyl_config_messages_leave(self, ctx: commands.Context, *, message: str) -> None:
|
||||||
|
"""Set the message that will be sent when a user leaves the server. This is only shown in embeds."""
|
||||||
|
await config.leave_msg.set(message)
|
||||||
|
await ctx.send(f"Leave message set to: {message}")
|
||||||
|
|
||||||
|
@pterodactyl_config.command(name = "ip")
|
||||||
|
async def pterodactyl_config_mask_ip(self, ctx: commands.Context, mask: bool) -> None:
|
||||||
|
"""Mask the IP addresses of users in console messages."""
|
||||||
|
await config.mask_ip.set(mask)
|
||||||
|
await ctx.send(f"IP masking set to {mask}")
|
||||||
|
|
||||||
|
@pterodactyl_config.command(name = "api")
|
||||||
|
async def pterodactyl_config_api(self, ctx: commands.Context, endpoint: str) -> None:
|
||||||
|
"""Set the API endpoint for retrieving user avatars.
|
||||||
|
|
||||||
|
This is only used for retrieving user avatars for webhook messages.
|
||||||
|
See [PlayerDB](https://playerdb.co/) for valid endpoints. Usually, you should leave this as default."""
|
||||||
|
await config.api_endpoint.set(endpoint)
|
||||||
|
await ctx.send(f"API endpoint set to {endpoint}")
|
||||||
|
|
||||||
|
@pterodactyl_config_regex.group(name = "blacklist", aliases = ['block', 'blocklist'],)
|
||||||
|
async def pterodactyl_config_regex_blacklist(self, ctx: commands.Context):
|
||||||
|
"""Blacklist regex patterns."""
|
||||||
|
|
||||||
|
@pterodactyl_config_regex_blacklist.command(name = "add")
|
||||||
|
async def pterodactyl_config_regex_blacklist_add(self, ctx: commands.Context, name: str, *, regex: str) -> None:
|
||||||
|
"""Add a regex pattern to the blacklist."""
|
||||||
|
async with config.regex_blacklist() as blacklist:
|
||||||
|
blacklist: dict
|
||||||
|
if name not in blacklist:
|
||||||
|
blacklist.update({name: regex})
|
||||||
|
await ctx.send(f"Added `{name}` to the regex blacklist.\n{box(regex, 're')}")
|
||||||
|
else:
|
||||||
|
view = ConfirmView(ctx.author, disable_buttons=True)
|
||||||
|
msg = await ctx.send(f"Name `{name}` already exists in the blacklist. Would you like to update it? Current value:\n{box(blacklist[name], 're')}", view=view)
|
||||||
|
await view.wait()
|
||||||
|
if view.result is True:
|
||||||
|
blacklist.update({name: regex})
|
||||||
|
await msg.edit(content=f"Updated `{name}` in the regex blacklist.\n{box(regex, 're')}")
|
||||||
|
else:
|
||||||
|
await msg.edit(content="Cancelled.")
|
||||||
|
|
||||||
|
@pterodactyl_config_regex_blacklist.command(name = "remove")
|
||||||
|
async def pterodactyl_config_regex_blacklist_remove(self, ctx: commands.Context, name: str) -> None:
|
||||||
|
"""Remove a regex pattern from the blacklist."""
|
||||||
|
async with config.regex_blacklist() as blacklist:
|
||||||
|
blacklist: dict
|
||||||
|
if name in blacklist:
|
||||||
|
view = ConfirmView(ctx.author, disable_buttons=True)
|
||||||
|
msg = await ctx.send(f"Are you sure you want to remove `{name}` from the regex blacklist?\n{box(blacklist[name], 're')}", view=view)
|
||||||
|
await view.wait()
|
||||||
|
if view.result is True:
|
||||||
|
del blacklist[name]
|
||||||
|
await msg.edit(content=f"Removed `{name}` from the regex blacklist.")
|
||||||
|
else:
|
||||||
|
await msg.edit(content="Cancelled.")
|
||||||
|
else:
|
||||||
|
await ctx.send(f"Name `{name}` does not exist in the blacklist.")
|
||||||
|
|
||||||
|
@pterodactyl_config.command(name = 'view', aliases = ['show'])
|
||||||
|
async def pterodactyl_config_view(self, ctx: commands.Context) -> None:
|
||||||
|
"""View the current configuration."""
|
||||||
|
base_url = await config.base_url()
|
||||||
|
server_id = await config.server_id()
|
||||||
|
console_channel = await config.console_channel()
|
||||||
|
console_commands_enabled = await config.console_commands_enabled()
|
||||||
|
chat_channel = await config.chat_channel()
|
||||||
|
chat_command = await config.chat_command()
|
||||||
|
chat_regex = await config.chat_regex()
|
||||||
|
server_regex = await config.server_regex()
|
||||||
|
join_regex = await config.join_regex()
|
||||||
|
leave_regex = await config.leave_regex()
|
||||||
|
achievement_regex = await config.achievement_regex()
|
||||||
|
startup_msg = await config.startup_msg()
|
||||||
|
shutdown_msg = await config.shutdown_msg()
|
||||||
|
join_msg = await config.join_msg()
|
||||||
|
leave_msg = await config.leave_msg()
|
||||||
|
mask_ip = await config.mask_ip()
|
||||||
|
api_endpoint = await config.api_endpoint()
|
||||||
|
invite = await config.invite()
|
||||||
|
regex_blacklist: dict = await config.regex_blacklist()
|
||||||
|
topic_text = await config.topic()
|
||||||
|
topic_hostname = await config.topic_hostname()
|
||||||
|
topic_port = await config.topic_port()
|
||||||
|
embed = discord.Embed(color = await ctx.embed_color(), title="Pterodactyl Configuration")
|
||||||
|
embed.description = f"""**Base URL:** {base_url}
|
||||||
|
**Server ID:** `{server_id}`
|
||||||
|
**Console Channel:** <#{console_channel}>
|
||||||
|
**Console Commands:** {self.get_bool_str(console_commands_enabled)}
|
||||||
|
**Chat Channel:** <#{chat_channel}>
|
||||||
|
**Startup Message:** {startup_msg}
|
||||||
|
**Shutdown Message:** {shutdown_msg}
|
||||||
|
**Join Message:** {join_msg}
|
||||||
|
**Leave Message:** {leave_msg}
|
||||||
|
**Mask IP:** {self.get_bool_str(mask_ip)}
|
||||||
|
**API Endpoint:** `{api_endpoint}`
|
||||||
|
**Invite:** {invite}
|
||||||
|
|
||||||
|
**Topic Hostname:** `{topic_hostname}`
|
||||||
|
**Topic Port:** `{topic_port}`
|
||||||
|
**Topic Text:** {box(topic_text, 'yaml')}
|
||||||
|
|
||||||
|
**Chat Command:** {box(chat_command, 'json')}
|
||||||
|
**Chat Regex:** {box(chat_regex, 're')}
|
||||||
|
**Server Regex:** {box(server_regex, 're')}
|
||||||
|
**Join Regex:** {box(join_regex, 're')}
|
||||||
|
**Leave Regex:** {box(leave_regex, 're')}
|
||||||
|
**Achievement Regex:** {box(achievement_regex, 're')}"""
|
||||||
|
await ctx.send(embed=embed)
|
||||||
|
if not len(regex_blacklist) == 0:
|
||||||
|
regex_blacklist_embed = discord.Embed(color = await ctx.embed_color(), title="Regex Blacklist")
|
||||||
|
for name, regex in regex_blacklist.items():
|
||||||
|
regex_blacklist_embed.add_field(name=name, value=box(regex, 're'), inline=False)
|
||||||
|
await ctx.send(embed=regex_blacklist_embed)
|
||||||
|
|
||||||
|
def get_bool_str(self, inp: bool) -> str:
|
||||||
|
"""Return a string representation of a boolean."""
|
||||||
|
return "Enabled" if inp else "Disabled"
|
251
pterodactyl/websocket.py
Normal file
|
@ -0,0 +1,251 @@
|
||||||
|
# pylint: disable=cyclic-import
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from typing import Optional, Union
|
||||||
|
|
||||||
|
import aiohttp
|
||||||
|
import discord
|
||||||
|
import websockets
|
||||||
|
from pydactyl import PterodactylClient
|
||||||
|
from redbot.core.utils.chat_formatting import bold, pagify
|
||||||
|
|
||||||
|
from pterodactyl.config import config
|
||||||
|
from pterodactyl.logger import logger, websocket_logger
|
||||||
|
from pterodactyl.pterodactyl import Pterodactyl
|
||||||
|
|
||||||
|
|
||||||
|
async def establish_websocket_connection(coginstance: Pterodactyl) -> None:
|
||||||
|
await coginstance.bot.wait_until_red_ready()
|
||||||
|
base_url = await config.base_url()
|
||||||
|
base_url = base_url[:-1] if base_url.endswith('/') else base_url
|
||||||
|
|
||||||
|
logger.info("Establishing WebSocket connection")
|
||||||
|
|
||||||
|
websocket_credentials = await retrieve_websocket_credentials(coginstance)
|
||||||
|
|
||||||
|
async with websockets.connect(websocket_credentials['data']['socket'], origin=base_url, ping_timeout=60, logger=websocket_logger) as websocket:
|
||||||
|
logger.info("WebSocket connection established")
|
||||||
|
|
||||||
|
auth_message = json.dumps({"event": "auth", "args": [websocket_credentials['data']['token']]})
|
||||||
|
await websocket.send(auth_message)
|
||||||
|
logger.info("Authentication message sent")
|
||||||
|
|
||||||
|
coginstance.websocket = websocket
|
||||||
|
|
||||||
|
while True: # pylint: disable=too-many-nested-blocks
|
||||||
|
message = json.loads(await websocket.recv())
|
||||||
|
if message['event'] in ('token expiring', 'token expired'):
|
||||||
|
logger.info("Received token expiring/expired event. Refreshing token.")
|
||||||
|
websocket_credentials = await retrieve_websocket_credentials(coginstance)
|
||||||
|
auth_message = json.dumps({"event": "auth", "args": [websocket_credentials['data']['token']]})
|
||||||
|
await websocket.send(auth_message)
|
||||||
|
logger.info("Authentication message sent")
|
||||||
|
|
||||||
|
if message['event'] == 'auth success':
|
||||||
|
logger.info("WebSocket authentication successful")
|
||||||
|
|
||||||
|
if message['event'] == 'console output' and await config.console_channel() is not None:
|
||||||
|
regex_blacklist: dict = await config.regex_blacklist()
|
||||||
|
matches = [re.search(regex, message['args'][0]) for regex in regex_blacklist.values()]
|
||||||
|
|
||||||
|
if await config.current_status() in ('running', '') and not any(matches):
|
||||||
|
content = remove_ansi_escape_codes(message['args'][0])
|
||||||
|
if await config.mask_ip() is True:
|
||||||
|
content = mask_ip(content)
|
||||||
|
|
||||||
|
console_channel = coginstance.bot.get_channel(await config.console_channel())
|
||||||
|
chat_channel = coginstance.bot.get_channel(await config.chat_channel())
|
||||||
|
if console_channel is not None:
|
||||||
|
if content.startswith('['):
|
||||||
|
pagified_content = pagify(content, delims=[" ", "\n"])
|
||||||
|
for page in pagified_content:
|
||||||
|
await console_channel.send(content=page, allowed_mentions=discord.AllowedMentions.none())
|
||||||
|
|
||||||
|
server_message = await check_if_server_message(content)
|
||||||
|
if server_message:
|
||||||
|
if chat_channel is not None:
|
||||||
|
await chat_channel.send(server_message if len(server_message) < 2000 else server_message[:1997] + '...', allowed_mentions=discord.AllowedMentions.none())
|
||||||
|
|
||||||
|
chat_message = await check_if_chat_message(content)
|
||||||
|
if chat_message:
|
||||||
|
info = await get_info(chat_message['username'])
|
||||||
|
if info is not None:
|
||||||
|
await send_chat_discord(coginstance, chat_message['username'], chat_message['message'], info['data']['player']['avatar'])
|
||||||
|
else:
|
||||||
|
await send_chat_discord(coginstance, chat_message['username'], chat_message['message'], 'https://seafsh.cc/u/j3AzqQ.png')
|
||||||
|
|
||||||
|
join_message = await check_if_join_message(content)
|
||||||
|
if join_message:
|
||||||
|
if chat_channel is not None:
|
||||||
|
if coginstance.bot.embed_requested(chat_channel):
|
||||||
|
await chat_channel.send(embed=await generate_join_leave_embed(join_message, True))
|
||||||
|
else:
|
||||||
|
await chat_channel.send(f"{join_message} joined the game", allowed_mentions=discord.AllowedMentions.none())
|
||||||
|
|
||||||
|
leave_message = await check_if_leave_message(content)
|
||||||
|
if leave_message:
|
||||||
|
if chat_channel is not None:
|
||||||
|
if coginstance.bot.embed_requested(chat_channel):
|
||||||
|
await chat_channel.send(embed=await generate_join_leave_embed(leave_message, False))
|
||||||
|
else:
|
||||||
|
await chat_channel.send(f"{leave_message} left the game", allowed_mentions=discord.AllowedMentions.none())
|
||||||
|
|
||||||
|
achievement_message = await check_if_achievement_message(content)
|
||||||
|
if achievement_message:
|
||||||
|
if chat_channel is not None:
|
||||||
|
if coginstance.bot.embed_requested(chat_channel):
|
||||||
|
await chat_channel.send(embed=await generate_achievement_embed(achievement_message['username'], achievement_message['achievement'], achievement_message['challenge']))
|
||||||
|
else:
|
||||||
|
await chat_channel.send(f"{achievement_message['username']} has {'completed the challenge' if achievement_message['challenge'] else 'made the advancement'} {achievement_message['achievement']}")
|
||||||
|
|
||||||
|
if message['event'] == 'status':
|
||||||
|
old_status = await config.current_status()
|
||||||
|
current_status = message['args'][0]
|
||||||
|
if old_status != current_status:
|
||||||
|
await config.current_status.set(current_status)
|
||||||
|
if await config.console_channel() is not None:
|
||||||
|
console = coginstance.bot.get_channel(await config.console_channel())
|
||||||
|
if console is not None:
|
||||||
|
await console.send(f"Server status changed! `{current_status}`")
|
||||||
|
if await config.chat_channel() is not None:
|
||||||
|
if current_status == 'running' and await config.startup_msg() is not None:
|
||||||
|
chat = coginstance.bot.get_channel(await config.chat_channel())
|
||||||
|
if chat is not None:
|
||||||
|
await chat.send(await config.startup_msg())
|
||||||
|
if current_status == 'stopping' and await config.shutdown_msg() is not None:
|
||||||
|
chat = coginstance.bot.get_channel(await config.chat_channel())
|
||||||
|
if chat is not None:
|
||||||
|
await chat.send(await config.shutdown_msg())
|
||||||
|
|
||||||
|
async def retrieve_websocket_credentials(coginstance: Pterodactyl) -> Optional[dict]:
|
||||||
|
pterodactyl_keys = await coginstance.bot.get_shared_api_tokens("pterodactyl")
|
||||||
|
api_key = pterodactyl_keys.get("api_key")
|
||||||
|
if api_key is None:
|
||||||
|
coginstance.task.cancel()
|
||||||
|
raise ValueError("Pterodactyl API key not set. Please set it using `[p]set api`.")
|
||||||
|
base_url = await config.base_url()
|
||||||
|
if base_url is None:
|
||||||
|
coginstance.task.cancel()
|
||||||
|
raise ValueError("Pterodactyl base URL not set. Please set it using `[p]pterodactyl config url`.")
|
||||||
|
server_id = await config.server_id()
|
||||||
|
if server_id is None:
|
||||||
|
coginstance.task.cancel()
|
||||||
|
raise ValueError("Pterodactyl server ID not set. Please set it using `[p]pterodactyl config serverid`.")
|
||||||
|
|
||||||
|
client = PterodactylClient(base_url, api_key).client
|
||||||
|
coginstance.client = client
|
||||||
|
websocket_credentials = client.servers.get_websocket(server_id)
|
||||||
|
logger.debug("""Websocket connection details retrieved:
|
||||||
|
Socket: %s
|
||||||
|
Token: %s...""",
|
||||||
|
websocket_credentials['data']['socket'],
|
||||||
|
websocket_credentials['data']['token'][:20]
|
||||||
|
)
|
||||||
|
return websocket_credentials
|
||||||
|
#NOTE - The token is truncated to prevent it from being logged in its entirety, for security reasons
|
||||||
|
|
||||||
|
def remove_ansi_escape_codes(text: str) -> str:
|
||||||
|
ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
|
||||||
|
#NOTE - https://chat.openai.com/share/d92f9acf-d776-4fd6-a53f-b14ac15dd540
|
||||||
|
return ansi_escape.sub('', text)
|
||||||
|
|
||||||
|
async def check_if_server_message(text: str) -> Union[bool, str]:
|
||||||
|
regex = await config.server_regex()
|
||||||
|
match: Optional[re.Match[str]] = re.match(regex, text)
|
||||||
|
if match:
|
||||||
|
logger.debug("Message is a server message")
|
||||||
|
return match.group(1)
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def check_if_chat_message(text: str) -> Union[bool, dict]:
|
||||||
|
regex = await config.chat_regex()
|
||||||
|
match: Optional[re.Match[str]] = re.match(regex, text)
|
||||||
|
if match:
|
||||||
|
groups = {"username": match.group(1), "message": match.group(2)}
|
||||||
|
logger.debug("Message is a chat message\n%s", json.dumps(groups))
|
||||||
|
return groups
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def check_if_join_message(text: str) -> Union[bool, str]:
|
||||||
|
regex = await config.join_regex()
|
||||||
|
match: Optional[re.Match[str]] = re.match(regex, text)
|
||||||
|
if match:
|
||||||
|
logger.debug("Message is a join message")
|
||||||
|
return match.group(1)
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def check_if_leave_message(text: str) -> Union[bool, str]:
|
||||||
|
regex = await config.leave_regex()
|
||||||
|
match: Optional[re.Match[str]] = re.match(regex, text)
|
||||||
|
if match:
|
||||||
|
logger.debug("Message is a leave message")
|
||||||
|
return match.group(1)
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def check_if_achievement_message(text: str) -> Union[bool, dict]:
|
||||||
|
regex = await config.achievement_regex()
|
||||||
|
match: Optional[re.Match[str]] = re.match(regex, text)
|
||||||
|
if match:
|
||||||
|
groups = {"username": match.group(1), "achievement": match.group(3)}
|
||||||
|
if match.group(2) == "completed the challenge":
|
||||||
|
groups["challenge"] = True
|
||||||
|
else:
|
||||||
|
groups["challenge"] = False
|
||||||
|
logger.debug("Message is an achievement message")
|
||||||
|
return groups
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def get_info(username: str) -> Optional[dict]:
|
||||||
|
logger.debug("Retrieving player info for %s", username)
|
||||||
|
endpoint = await config.api_endpoint()
|
||||||
|
async with aiohttp.ClientSession() as session:
|
||||||
|
async with session.get(f"https://playerdb.co/api/player/{endpoint}/{username}") as response:
|
||||||
|
if response.status == 200:
|
||||||
|
logger.debug("Player info retrieved for %s", username)
|
||||||
|
return await response.json()
|
||||||
|
logger.error("Failed to retrieve player info for %s: %s", username, response.status)
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def send_chat_discord(coginstance: Pterodactyl, username: str, message: str, avatar_url: str) -> None:
|
||||||
|
logger.debug("Sending chat message to Discord")
|
||||||
|
channel = coginstance.bot.get_channel(await config.chat_channel())
|
||||||
|
if channel is not None:
|
||||||
|
webhooks = await channel.webhooks()
|
||||||
|
webhook = discord.utils.get(webhooks, name="Pterodactyl Chat")
|
||||||
|
if webhook is None:
|
||||||
|
webhook = await channel.create_webhook(name="Pterodactyl Chat")
|
||||||
|
await webhook.send(content=message, username=username, avatar_url=avatar_url, allowed_mentions=discord.AllowedMentions(everyone=False, roles=False, users=True))
|
||||||
|
logger.debug("Chat message sent to Discord")
|
||||||
|
else:
|
||||||
|
logger.warning("Chat channel not set. Skipping sending chat message to Discord")
|
||||||
|
|
||||||
|
async def generate_join_leave_embed(username: str, join: bool) -> discord.Embed:
|
||||||
|
embed = discord.Embed()
|
||||||
|
embed.color = discord.Color.green() if join else discord.Color.red()
|
||||||
|
embed.description = await config.join_msg() if join else await config.leave_msg()
|
||||||
|
info = await get_info(username)
|
||||||
|
if info:
|
||||||
|
embed.set_author(name=username, icon_url=info['data']['player']['avatar'])
|
||||||
|
else:
|
||||||
|
embed.set_author(name=username, icon_url='https://seafsh.cc/u/j3AzqQ.png')
|
||||||
|
embed.timestamp = discord.utils.utcnow()
|
||||||
|
return embed
|
||||||
|
|
||||||
|
async def generate_achievement_embed(username: str, achievement: str, challenge: bool) -> discord.Embed:
|
||||||
|
embed = discord.Embed()
|
||||||
|
embed.color = discord.Color.from_str('#a800a7') if challenge else discord.Color.from_str('#54fb54')
|
||||||
|
embed.description = f"{bold(username)} has {'completed the challenge' if challenge else 'made the advancement'} {bold(achievement)}"
|
||||||
|
info = await get_info(username)
|
||||||
|
if info:
|
||||||
|
embed.set_author(name=username, icon_url=info['data']['player']['avatar'])
|
||||||
|
else:
|
||||||
|
embed.set_author(name=username, icon_url='https://seafsh.cc/u/j3AzqQ.png')
|
||||||
|
embed.timestamp = discord.utils.utcnow()
|
||||||
|
return embed
|
||||||
|
|
||||||
|
def mask_ip(string: str) -> str:
|
||||||
|
def check(match: re.Match[str]):
|
||||||
|
ip = match.group(0)
|
||||||
|
masked_ip = '.'.join(r'\*' * len(octet) for octet in ip.split('.'))
|
||||||
|
return masked_ip
|
||||||
|
return re.sub(r'\b(?:\d{1,3}\.){3}\d{1,3}\b', check, string)
|
102
pyproject.toml
|
@ -5,19 +5,113 @@ description = "My assorted cogs for Red-DiscordBot."
|
||||||
authors = ["SeaswimmerTheFsh"]
|
authors = ["SeaswimmerTheFsh"]
|
||||||
license = "MPL 2"
|
license = "MPL 2"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
|
package-mode = false
|
||||||
|
|
||||||
[tool.poetry.dependencies]
|
[tool.poetry.dependencies]
|
||||||
python = ">=3.9,<3.12"
|
python = ">=3.11,<3.12"
|
||||||
Red-DiscordBot = "^3.5.5"
|
Red-DiscordBot = "^3.5.5"
|
||||||
pytimeparse2 = "^1.7.1"
|
py-dactyl = "^2.0.4"
|
||||||
humanize = "^4.8.0"
|
websockets = "^12.0"
|
||||||
|
pillow = "^10.3.0"
|
||||||
|
numpy = "^1.26.4"
|
||||||
|
|
||||||
[tool.poetry.group.dev]
|
[tool.poetry.group.dev]
|
||||||
optional = true
|
optional = true
|
||||||
|
|
||||||
[tool.poetry.group.dev.dependencies]
|
[tool.poetry.group.dev.dependencies]
|
||||||
pylint = "^2.17.5"
|
ruff = "^0.3.1"
|
||||||
|
pylint = "^3.1.0"
|
||||||
|
|
||||||
|
[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]
|
[build-system]
|
||||||
requires = ["poetry-core"]
|
requires = ["poetry-core"]
|
||||||
build-backend = "poetry.core.masonry.api"
|
build-backend = "poetry.core.masonry.api"
|
||||||
|
|
||||||
|
[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",
|
||||||
|
]
|
||||||
|
|
||||||
|
# Same as Black.
|
||||||
|
line-length = 320
|
||||||
|
indent-width = 4
|
||||||
|
|
||||||
|
# Assume Python 3.11
|
||||||
|
target-version = "py311"
|
||||||
|
|
||||||
|
[tool.ruff.lint]
|
||||||
|
# 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"]
|
||||||
|
|
||||||
|
# Allow fix for all enabled rules (when `--fix`) is provided.
|
||||||
|
fixable = ["ALL"]
|
||||||
|
unfixable = []
|
||||||
|
|
||||||
|
# Allow unused variables when underscore-prefixed.
|
||||||
|
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
|
||||||
|
|
||||||
|
[tool.ruff.format]
|
||||||
|
# Like Black, use double quotes for strings.
|
||||||
|
quote-style = "double"
|
||||||
|
|
||||||
|
# Like Black, indent with spaces, rather than tabs.
|
||||||
|
indent-style = "space"
|
||||||
|
|
||||||
|
# Like Black, respect magic trailing commas.
|
||||||
|
skip-magic-trailing-comma = false
|
||||||
|
|
||||||
|
# Like Black, automatically detect the appropriate line ending.
|
||||||
|
line-ending = "auto"
|
||||||
|
|
||||||
|
# Enable auto-formatting of code examples in docstrings. Markdown,
|
||||||
|
# reStructuredText code/literal blocks and doctests are all supported.
|
||||||
|
#
|
||||||
|
# This is currently disabled by default, but it is planned for this
|
||||||
|
# to be opt-out in the future.
|
||||||
|
docstring-code-format = false
|
||||||
|
|
||||||
|
# Set the line length limit used when formatting code snippets in
|
||||||
|
# docstrings.
|
||||||
|
#
|
||||||
|
# This only has an effect when the `docstring-code-format` setting is
|
||||||
|
# enabled.
|
||||||
|
docstring-code-line-length = "dynamic"
|
||||||
|
|