Compare commits
1 commit
Author | SHA1 | Date | |
---|---|---|---|
a62b6d5593 |
52 changed files with 1300 additions and 7680 deletions
|
@ -80,23 +80,9 @@ Manage the immunity whitelist.
|
||||||
- Usage: `[p]aurora timedelta <duration>`
|
- Usage: `[p]aurora timedelta <duration>`
|
||||||
- Aliases: `tdc, td, and timedeltaconvert`
|
- Aliases: `tdc, td, and timedeltaconvert`
|
||||||
|
|
||||||
This command converts a duration to a [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) Python object.You cannot convert years or months as they are not fixed units. Use `[p]aurora relativedelta` for that.
|
This command converts a duration to a [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) Python object.
|
||||||
|
|
||||||
**Example usage**
|
**Example usage**
|
||||||
`[p]aurora timedelta 1 day 15hr 82 minutes 52s`
|
`[p]timedelta 1 day 15hr 82 minutes 52s`
|
||||||
|
|
||||||
**Output**
|
**Output**
|
||||||
`1 day, 16:22:52`
|
`1 day, 16:22:52`
|
||||||
|
|
||||||
### aurora relativedelta
|
|
||||||
|
|
||||||
- Usage: `[p]aurora relativedelta <duration>`
|
|
||||||
- Aliases: `rdc, rd, and relativedeltaconvert`
|
|
||||||
|
|
||||||
This command converts a duration to a [`relativedelta`](https://dateutil.readthedocs.io/en/stable/relativedelta.html) Python object.
|
|
||||||
|
|
||||||
**Example usage**
|
|
||||||
`[p]aurora relativedelta 3 years 1 day 15hr 82 minutes 52s`
|
|
||||||
|
|
||||||
**Output**
|
|
||||||
`relativedelta(years=+3, days=+1, hours=+15, minutes=+82, seconds=+52)`
|
|
||||||
|
|
|
@ -23,27 +23,19 @@ Add a note to a user.
|
||||||
|
|
||||||
Warn a user.
|
Warn a user.
|
||||||
|
|
||||||
## addrole
|
## blacklist
|
||||||
|
|
||||||
- Usage: `/addrole <target> <role> <reason> [duration] [silent]`
|
/// admonition | This command is unfinished, and doesn't currently work.
|
||||||
- `target:` (Required) Who are you adding a role to?
|
type: warning
|
||||||
- `role:` (Required) What role are you adding to the target?
|
///
|
||||||
- `reason:` (Required) Why are you adding a role to this user?
|
|
||||||
- `duration:` (Optional) How long are you adding this role for?
|
- 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?
|
- `silent:` (Optional) Should the user be messaged?
|
||||||
|
|
||||||
Add a role to a user.
|
Add a blacklist role to a user.
|
||||||
|
|
||||||
## removerole
|
|
||||||
|
|
||||||
- Usage: `/removerole <target> <role> <reason> [duration] [silent]`
|
|
||||||
- `target:` (Required) Who are you removing a role from?
|
|
||||||
- `role:` (Required) What role are you removing from the target?
|
|
||||||
- `reason:` (Required) Why are you removing a role from this user?
|
|
||||||
- `duration:` (Optional) How long are you removing this role for?
|
|
||||||
- `silent:` (Optional) Should the user be messaged?
|
|
||||||
|
|
||||||
Remove a role from a user.
|
|
||||||
|
|
||||||
## mute
|
## mute
|
||||||
|
|
||||||
|
|
|
@ -10,14 +10,6 @@ Backup allows you to export a JSON list of all of your installed repositories an
|
||||||
[p]cog load backup
|
[p]cog load backup
|
||||||
```
|
```
|
||||||
|
|
||||||
## Version Compatibility
|
|
||||||
|
|
||||||
As of commit [1edb08a](https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs/commit/1edb08a1271f12098ca0bed11a735f7162cedd14), the Backup cog no longer supports Red versions older than 3.5.6. If you want to use the cog on an earlier version (3.5.0 - 3.5.5), install the cog pinned to this commit: `43464db6a7c51bc69282b1ae3dc507a4aae851de`.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
[p]cog installversion sea-cogs 43464db6a7c51bc69282b1ae3dc507a4aae851de backup
|
|
||||||
```
|
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
### backup export
|
### backup export
|
||||||
|
|
|
@ -1,19 +0,0 @@
|
||||||
# EmojiInfo
|
|
||||||
|
|
||||||
EmojiInfo allows you to retrieve information about an emoji.
|
|
||||||
|
|
||||||
## Installation
|
|
||||||
|
|
||||||
```bash
|
|
||||||
[p]repo add seacogs https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs
|
|
||||||
[p]cog install seacogs emojiinfo
|
|
||||||
[p]cog load emojiinfo
|
|
||||||
```
|
|
||||||
|
|
||||||
## Commands
|
|
||||||
|
|
||||||
### emoji
|
|
||||||
|
|
||||||
- Usage: `[p]emoji <emoji> [ephemeral]`
|
|
||||||
|
|
||||||
Retrieve information about the provided emoji. If `ephemeral` is provided and the command is used as a slash command, the response will be sent as an ephemeral message.
|
|
23
.forgejo/ISSUE_TEMPLATE/bug-report.md
Normal file
23
.forgejo/ISSUE_TEMPLATE/bug-report.md
Normal file
|
@ -0,0 +1,23 @@
|
||||||
|
---
|
||||||
|
name: Bug Report
|
||||||
|
about: Got an issue with a cog from SeaCogs? Use this.
|
||||||
|
title: "[BUG]"
|
||||||
|
labels: bug
|
||||||
|
assignees: ''
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Describe the bug**
|
||||||
|
A clear and concise description of what the bug is.
|
||||||
|
|
||||||
|
**To Reproduce**
|
||||||
|
What caused the error?
|
||||||
|
|
||||||
|
**Expected behavior**
|
||||||
|
A clear and concise description of what you expected to happen.
|
||||||
|
|
||||||
|
**Screenshots**
|
||||||
|
If applicable, add screenshots to help explain your problem.
|
||||||
|
|
||||||
|
**Additional context**
|
||||||
|
Add any other context about the problem here.
|
|
@ -1,55 +0,0 @@
|
||||||
name: Bug Report
|
|
||||||
about: File a bug report
|
|
||||||
title: "[Cog Name] "
|
|
||||||
labels: [bug]
|
|
||||||
ref: master
|
|
||||||
body:
|
|
||||||
- type: markdown
|
|
||||||
attributes:
|
|
||||||
value: |
|
|
||||||
Thank you for taking the time to fill out this bug report!
|
|
||||||
- type: checkboxes
|
|
||||||
id: confirmation
|
|
||||||
attributes:
|
|
||||||
label: Please confirm that;
|
|
||||||
options:
|
|
||||||
- label: I have checked that this bug does not already have an opened/closed [issue](https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs/issues) or [pull request](https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs/pulls) associated with it.
|
|
||||||
required: true
|
|
||||||
- label: I have checked that I am on the latest version of [Red-DiscordBot](https://github.com/CogCreators/Red-DiscordBot), and SeaCogs.
|
|
||||||
required: true
|
|
||||||
- type: input
|
|
||||||
id: hosting
|
|
||||||
attributes:
|
|
||||||
label: Hosting
|
|
||||||
description: How is your bot hosted?
|
|
||||||
placeholder: Local, Docker, etc.
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
id: what-happened
|
|
||||||
attributes:
|
|
||||||
label: What happened?
|
|
||||||
description: Also, what did you expect to happen?
|
|
||||||
placeholder: A bug happened!
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
id: reproduction
|
|
||||||
attributes:
|
|
||||||
label: Reproduction steps
|
|
||||||
description: Please provide detailed steps to reproduce the bug.
|
|
||||||
placeholder: |
|
|
||||||
1. Do this
|
|
||||||
2. Do that
|
|
||||||
3. Do this other thing
|
|
||||||
4. Bug happens!
|
|
||||||
validations:
|
|
||||||
required: false
|
|
||||||
- type: textarea
|
|
||||||
id: logs
|
|
||||||
attributes:
|
|
||||||
label: Relevant traceback or logs
|
|
||||||
description: Please copy and paste any relevant tracebacks or log output. This will be automatically formatted into code, so no need for backticks.
|
|
||||||
render: py
|
|
||||||
validations:
|
|
||||||
required: false
|
|
|
@ -1,5 +0,0 @@
|
||||||
blank_issues_enabled: true
|
|
||||||
contact_links:
|
|
||||||
- name: Other Concerns?
|
|
||||||
url: https://discord.gg/eMUMe77Yb8
|
|
||||||
about: Ask in our Discord server!
|
|
26
.forgejo/ISSUE_TEMPLATE/suggestion.md
Normal file
26
.forgejo/ISSUE_TEMPLATE/suggestion.md
Normal file
|
@ -0,0 +1,26 @@
|
||||||
|
---
|
||||||
|
name: Suggestion
|
||||||
|
about: Trying to suggest something for SeaCogs? Use this.
|
||||||
|
title: "[SUGGESTION]"
|
||||||
|
labels: enhancement
|
||||||
|
assignees: ''
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**What cog is your feature request for?**
|
||||||
|
A cog in this repository.
|
||||||
|
|
||||||
|
**Is your feature request related to a problem? Please describe.**
|
||||||
|
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||||
|
|
||||||
|
**Describe the solution you'd like**
|
||||||
|
A clear and concise description of what you want to happen.
|
||||||
|
|
||||||
|
**Describe alternatives you've considered**
|
||||||
|
A clear and concise description of any alternative solutions or features you've considered.
|
||||||
|
|
||||||
|
**Screenshots**
|
||||||
|
If applicable, add screenshots to help explain your problem.
|
||||||
|
|
||||||
|
**Additional context**
|
||||||
|
Add any other context about the problem here.
|
|
@ -1,55 +0,0 @@
|
||||||
name: Suggestion
|
|
||||||
about: Trying to suggest something for SeaCogs? Use this.
|
|
||||||
title: "[Cog Name] "
|
|
||||||
labels: enhancement
|
|
||||||
ref: master
|
|
||||||
body:
|
|
||||||
- type: markdown
|
|
||||||
attributes:
|
|
||||||
value: |
|
|
||||||
Thank you for taking the time to suggest an enhancement!
|
|
||||||
- type: input
|
|
||||||
id: cog
|
|
||||||
attributes:
|
|
||||||
label: What cog is your feature request for?
|
|
||||||
description: Specify the cog within the repository.
|
|
||||||
placeholder: E.g., ModerationCog
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
id: problem-description
|
|
||||||
attributes:
|
|
||||||
label: Is your feature request related to a problem? Please describe.
|
|
||||||
placeholder: A clear and concise description of what the problem is.
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
id: solution-description
|
|
||||||
attributes:
|
|
||||||
label: Describe the solution you'd like
|
|
||||||
placeholder: A clear and concise description of what you want to happen.
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
id: alternatives
|
|
||||||
attributes:
|
|
||||||
label: Describe alternatives you've considered
|
|
||||||
placeholder: A clear and concise description of any alternative solutions or features you've considered.
|
|
||||||
validations:
|
|
||||||
required: false
|
|
||||||
- type: textarea
|
|
||||||
id: screenshots
|
|
||||||
attributes:
|
|
||||||
label: Screenshots
|
|
||||||
description: If applicable, add screenshots to help explain your problem.
|
|
||||||
placeholder: Paste image links here.
|
|
||||||
validations:
|
|
||||||
required: false
|
|
||||||
- type: textarea
|
|
||||||
id: additional-context
|
|
||||||
attributes:
|
|
||||||
label: Additional context
|
|
||||||
description: Add any other context about the problem here.
|
|
||||||
placeholder: Any extra information you think might be useful.
|
|
||||||
validations:
|
|
||||||
required: false
|
|
|
@ -1,6 +0,0 @@
|
||||||
# Describe what your pull request does and which issue you're targeting
|
|
||||||
|
|
||||||
<!-- Create a new issue, if it doesn't exist yet -->
|
|
||||||
|
|
||||||
- [ ] By submitting this pull request, I permit SeaswimmerTheFsh to license my work under
|
|
||||||
the [Mozilla Public License Version 2.0](https://www.coastalcommits.com/SeaswimmerTheFsh/SeaCogs/src/branch/main/LICENSE).
|
|
|
@ -18,5 +18,4 @@
|
||||||
import-self,
|
import-self,
|
||||||
relative-beyond-top-level,
|
relative-beyond-top-level,
|
||||||
too-many-instance-attributes,
|
too-many-instance-attributes,
|
||||||
duplicate-code,
|
duplicate-code
|
||||||
too-many-nested-blocks
|
|
||||||
|
|
|
@ -58,7 +58,7 @@ jobs:
|
||||||
npx -p "@getmeli/cli" meli upload ./site \
|
npx -p "@getmeli/cli" meli upload ./site \
|
||||||
--url "https://pages.coastalcommits.com" \
|
--url "https://pages.coastalcommits.com" \
|
||||||
--site "${{ vars.MELI_SITE_ID }}" \
|
--site "${{ vars.MELI_SITE_ID }}" \
|
||||||
--token "${{ secrets.MELI_SECRET }}" \
|
--token "${{ secrets.MELI_SITE_SECRET }}" \
|
||||||
--release "$CI_ACTION_REF_NAME_SLUG/${{ env.GITHUB_SHA }}" \
|
--release "$CI_ACTION_REF_NAME_SLUG/${{ env.GITHUB_SHA }}" \
|
||||||
--branch "$CI_ACTION_REF_NAME_SLUG"
|
--branch "$CI_ACTION_REF_NAME_SLUG"
|
||||||
|
|
||||||
|
|
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -1,4 +1,3 @@
|
||||||
.cache
|
.cache
|
||||||
.vscode
|
.vscode
|
||||||
site
|
site
|
||||||
.venv
|
|
||||||
|
|
|
@ -1,5 +0,0 @@
|
||||||
from .antipolls import AntiPolls
|
|
||||||
|
|
||||||
|
|
||||||
async def setup(bot):
|
|
||||||
await bot.add_cog(AntiPolls(bot))
|
|
|
@ -1,180 +0,0 @@
|
||||||
# _____ _
|
|
||||||
# / ____| (_)
|
|
||||||
# | (___ ___ __ _ _____ ___ _ __ ___ _ __ ___ ___ _ __
|
|
||||||
# \___ \ / _ \/ _` / __\ \ /\ / / | '_ ` _ \| '_ ` _ \ / _ \ '__|
|
|
||||||
# ____) | __/ (_| \__ \\ 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()
|
|
|
@ -1,17 +0,0 @@
|
||||||
{
|
|
||||||
"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"
|
|
||||||
]
|
|
||||||
}
|
|
285
aurora/aurora.py
285
aurora/aurora.py
|
@ -13,7 +13,6 @@ from datetime import datetime, timedelta, timezone
|
||||||
from math import ceil
|
from math import ceil
|
||||||
|
|
||||||
import discord
|
import discord
|
||||||
from discord import Object
|
|
||||||
from discord.ext import tasks
|
from discord.ext import tasks
|
||||||
from redbot.core import app_commands, commands, data_manager
|
from redbot.core import app_commands, commands, data_manager
|
||||||
from redbot.core.app_commands import Choice
|
from redbot.core.app_commands import Choice
|
||||||
|
@ -31,7 +30,7 @@ from aurora.utilities.config import config, register_config
|
||||||
from aurora.utilities.database import connect, create_guild_table, fetch_case, mysql_log
|
from aurora.utilities.database import connect, create_guild_table, fetch_case, mysql_log
|
||||||
from aurora.utilities.factory import addrole_embed, case_factory, changes_factory, evidenceformat_factory, guild_embed, immune_embed, message_factory, overrides_embed
|
from aurora.utilities.factory import addrole_embed, case_factory, changes_factory, evidenceformat_factory, guild_embed, immune_embed, message_factory, overrides_embed
|
||||||
from aurora.utilities.logger import logger
|
from aurora.utilities.logger import logger
|
||||||
from aurora.utilities.utils import check_moddable, check_permissions, convert_timedelta_to_str, fetch_channel_dict, fetch_user_dict, generate_dict, get_footer_image, log, send_evidenceformat, timedelta_from_relativedelta
|
from aurora.utilities.utils import check_moddable, check_permissions, convert_timedelta_to_str, fetch_channel_dict, fetch_user_dict, generate_dict, log, send_evidenceformat, timedelta_from_relativedelta
|
||||||
|
|
||||||
|
|
||||||
class Aurora(commands.Cog):
|
class Aurora(commands.Cog):
|
||||||
|
@ -40,8 +39,7 @@ class Aurora(commands.Cog):
|
||||||
This cog stores all of its data in an SQLite database."""
|
This cog stores all of its data in an SQLite database."""
|
||||||
|
|
||||||
__author__ = ["SeaswimmerTheFsh"]
|
__author__ = ["SeaswimmerTheFsh"]
|
||||||
__version__ = "2.1.3"
|
__version__ = "2.1.0"
|
||||||
__documentation__ = "https://seacogs.coastalcommits.com/aurora/"
|
|
||||||
|
|
||||||
async def red_delete_data_for_user(self, *, requester, user_id: int):
|
async def red_delete_data_for_user(self, *, requester, user_id: int):
|
||||||
if requester == "discord_deleted_user":
|
if requester == "discord_deleted_user":
|
||||||
|
@ -86,7 +84,6 @@ class Aurora(commands.Cog):
|
||||||
f"{pre_processed}{n}",
|
f"{pre_processed}{n}",
|
||||||
f"Cog Version: **{self.__version__}**",
|
f"Cog Version: **{self.__version__}**",
|
||||||
f"Author: {humanize_list(self.__author__)}",
|
f"Author: {humanize_list(self.__author__)}",
|
||||||
f"Documentation: {self.__documentation__}",
|
|
||||||
]
|
]
|
||||||
return "\n".join(text)
|
return "\n".join(text)
|
||||||
|
|
||||||
|
@ -114,20 +111,6 @@ class Aurora(commands.Cog):
|
||||||
except ConnectionRefusedError:
|
except ConnectionRefusedError:
|
||||||
return
|
return
|
||||||
|
|
||||||
@commands.Cog.listener("on_member_join")
|
|
||||||
async def addrole_on_member_join(self, member: discord.Member):
|
|
||||||
"""This method automatically adds roles to users when they join the server."""
|
|
||||||
if not await self.bot.cog_disabled_in_guild(self, member.guild):
|
|
||||||
query = f"""SELECT moderation_id, role_id, reason FROM moderation_{member.guild.id} WHERE target_id = ? AND moderation_type = 'ADDROLE' AND expired = 0 AND resolved = 0;"""
|
|
||||||
database = connect()
|
|
||||||
cursor = database.cursor()
|
|
||||||
cursor.execute(query, (member.id,))
|
|
||||||
results = cursor.fetchall()
|
|
||||||
for result in results:
|
|
||||||
role = member.guild.get_role(result[1])
|
|
||||||
reason = result[2]
|
|
||||||
await member.add_roles(role, reason=f"Role automatically added on member rejoin for: {reason} (Case #{result[0]:,})")
|
|
||||||
|
|
||||||
@commands.Cog.listener("on_audit_log_entry_create")
|
@commands.Cog.listener("on_audit_log_entry_create")
|
||||||
async def autologger(self, entry: discord.AuditLogEntry):
|
async def autologger(self, entry: discord.AuditLogEntry):
|
||||||
"""This method automatically logs moderations done by users manually ("right clicks")."""
|
"""This method automatically logs moderations done by users manually ("right clicks")."""
|
||||||
|
@ -224,7 +207,7 @@ class Aurora(commands.Cog):
|
||||||
moderation_type="note",
|
moderation_type="note",
|
||||||
response=await interaction.original_response(),
|
response=await interaction.original_response(),
|
||||||
)
|
)
|
||||||
await target.send(embed=embed, file=get_footer_image(self))
|
await target.send(embed=embed)
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -283,7 +266,7 @@ class Aurora(commands.Cog):
|
||||||
moderation_type="warned",
|
moderation_type="warned",
|
||||||
response=await interaction.original_response(),
|
response=await interaction.original_response(),
|
||||||
)
|
)
|
||||||
await target.send(embed=embed, file=get_footer_image(self))
|
await target.send(embed=embed)
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -381,16 +364,16 @@ class Aurora(commands.Cog):
|
||||||
duration=parsed_time,
|
duration=parsed_time,
|
||||||
role=role,
|
role=role,
|
||||||
)
|
)
|
||||||
await target.send(embed=embed, file=get_footer_image(self))
|
await target.send(embed=embed)
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
await target.add_roles(
|
await target.add_roles(
|
||||||
role,
|
role,
|
||||||
reason=f"Role added by {interaction.user.id}{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''} for: {reason}",
|
reason=f"Role added by {interaction.user.id}{(' for ' + {humanize_timedelta(timedelta=parsed_time)} if parsed_time != 'NULL' else '')} for: {reason}",
|
||||||
)
|
)
|
||||||
response: discord.WebhookMessage = await interaction.followup.send(
|
response: discord.WebhookMessage = await interaction.followup.send(
|
||||||
content=f"{target.mention} has been given the {role.mention} role{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''}!\n**Reason** - `{reason}`"
|
content=f"{target.mention} has been given the {role.mention} role{(' for ' + {humanize_timedelta(timedelta=parsed_time)} if parsed_time != 'NULL' else '')}!\n**Reason** - `{reason}`"
|
||||||
)
|
)
|
||||||
|
|
||||||
moderation_id = await mysql_log(
|
moderation_id = await mysql_log(
|
||||||
|
@ -404,113 +387,7 @@ class Aurora(commands.Cog):
|
||||||
reason,
|
reason,
|
||||||
)
|
)
|
||||||
await response.edit(
|
await response.edit(
|
||||||
content=f"{target.mention} has been given the {role.mention} role{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''}! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`",
|
content=f"{target.mention} has been given the {role.mention} role{(' for ' + {humanize_timedelta(timedelta=parsed_time)} if parsed_time != 'NULL' else '')}! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`",
|
||||||
)
|
|
||||||
await log(interaction, moderation_id)
|
|
||||||
|
|
||||||
case = await fetch_case(moderation_id, interaction.guild.id)
|
|
||||||
await send_evidenceformat(interaction, case)
|
|
||||||
|
|
||||||
@app_commands.command(name="removerole")
|
|
||||||
async def removerole(
|
|
||||||
self,
|
|
||||||
interaction: discord.Interaction,
|
|
||||||
target: discord.Member,
|
|
||||||
role: discord.Role,
|
|
||||||
reason: str,
|
|
||||||
duration: str = None,
|
|
||||||
silent: bool = None,
|
|
||||||
):
|
|
||||||
"""Remove a role from a user.
|
|
||||||
|
|
||||||
Parameters
|
|
||||||
-----------
|
|
||||||
target: discord.Member
|
|
||||||
Who are you removing a role from?
|
|
||||||
role: discord.Role
|
|
||||||
What role are you removing from the target?
|
|
||||||
reason: str
|
|
||||||
Why are you removing a role from this user?
|
|
||||||
duration: str
|
|
||||||
How long are you removing this role for?
|
|
||||||
silent: bool
|
|
||||||
Should the user be messaged?"""
|
|
||||||
addrole_whitelist = await config.guild(interaction.guild).addrole_whitelist()
|
|
||||||
|
|
||||||
if not addrole_whitelist:
|
|
||||||
await interaction.response.send_message(
|
|
||||||
content=error("There are no whitelisted roles set for this server!"),
|
|
||||||
ephemeral=True,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
|
|
||||||
if duration is not None:
|
|
||||||
parsed_time = parse_timedelta(duration)
|
|
||||||
if parsed_time is None:
|
|
||||||
await interaction.response.send_message(
|
|
||||||
content=error("Please provide a valid duration!"), ephemeral=True
|
|
||||||
)
|
|
||||||
return
|
|
||||||
else:
|
|
||||||
parsed_time = "NULL"
|
|
||||||
|
|
||||||
if role.id not in addrole_whitelist:
|
|
||||||
await interaction.response.send_message(
|
|
||||||
content=error("That role isn't whitelisted!"), ephemeral=True
|
|
||||||
)
|
|
||||||
return
|
|
||||||
|
|
||||||
if not await check_moddable(
|
|
||||||
target, interaction, ["moderate_members", "manage_roles"]
|
|
||||||
):
|
|
||||||
return
|
|
||||||
|
|
||||||
if role.id not in [user_role.id for user_role in target.roles]:
|
|
||||||
await interaction.response.send_message(
|
|
||||||
content=error(f"{target.mention} does not have this role!"),
|
|
||||||
ephemeral=True,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
|
|
||||||
await interaction.response.defer()
|
|
||||||
if silent is None:
|
|
||||||
silent = not await config.guild(interaction.guild).dm_users()
|
|
||||||
if silent is False:
|
|
||||||
try:
|
|
||||||
embed = await message_factory(
|
|
||||||
await self.bot.get_embed_color(interaction.channel),
|
|
||||||
guild=interaction.guild,
|
|
||||||
moderator=interaction.user,
|
|
||||||
reason=reason,
|
|
||||||
moderation_type="removerole",
|
|
||||||
response=await interaction.original_response(),
|
|
||||||
duration=parsed_time,
|
|
||||||
role=role,
|
|
||||||
)
|
|
||||||
await target.send(embed=embed, file=get_footer_image(self))
|
|
||||||
except discord.errors.HTTPException:
|
|
||||||
pass
|
|
||||||
|
|
||||||
await target.remove_roles(
|
|
||||||
role,
|
|
||||||
reason=f"Role removed by {interaction.user.id}{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''} for: {reason}",
|
|
||||||
)
|
|
||||||
response: discord.WebhookMessage = await interaction.followup.send(
|
|
||||||
content=f"{target.mention} has had the {role.mention} role removed{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''}!\n**Reason** - `{reason}`"
|
|
||||||
)
|
|
||||||
|
|
||||||
moderation_id = await mysql_log(
|
|
||||||
interaction.guild.id,
|
|
||||||
interaction.user.id,
|
|
||||||
"REMOVEROLE",
|
|
||||||
"USER",
|
|
||||||
target.id,
|
|
||||||
role.id,
|
|
||||||
parsed_time,
|
|
||||||
reason,
|
|
||||||
)
|
|
||||||
await response.edit(
|
|
||||||
content=f"{target.mention} has had the {role.mention} role removed{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''}! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`",
|
|
||||||
)
|
)
|
||||||
await log(interaction, moderation_id)
|
await log(interaction, moderation_id)
|
||||||
|
|
||||||
|
@ -583,7 +460,7 @@ class Aurora(commands.Cog):
|
||||||
response=await interaction.original_response(),
|
response=await interaction.original_response(),
|
||||||
duration=parsed_time,
|
duration=parsed_time,
|
||||||
)
|
)
|
||||||
await target.send(embed=embed, file=get_footer_image(self))
|
await target.send(embed=embed)
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -658,7 +535,7 @@ class Aurora(commands.Cog):
|
||||||
moderation_type="unmuted",
|
moderation_type="unmuted",
|
||||||
response=await interaction.original_response(),
|
response=await interaction.original_response(),
|
||||||
)
|
)
|
||||||
await target.send(embed=embed, file=get_footer_image(self))
|
await target.send(embed=embed)
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -717,7 +594,7 @@ class Aurora(commands.Cog):
|
||||||
moderation_type="kicked",
|
moderation_type="kicked",
|
||||||
response=await interaction.original_response(),
|
response=await interaction.original_response(),
|
||||||
)
|
)
|
||||||
await target.send(embed=embed, file=get_footer_image(self))
|
await target.send(embed=embed)
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -821,7 +698,7 @@ class Aurora(commands.Cog):
|
||||||
response=await interaction.original_response(),
|
response=await interaction.original_response(),
|
||||||
duration=parsed_time,
|
duration=parsed_time,
|
||||||
)
|
)
|
||||||
await target.send(embed=embed, file=get_footer_image(self))
|
await target.send(embed=embed)
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -865,7 +742,7 @@ class Aurora(commands.Cog):
|
||||||
moderation_type="banned",
|
moderation_type="banned",
|
||||||
response=await interaction.original_response(),
|
response=await interaction.original_response(),
|
||||||
)
|
)
|
||||||
await target.send(embed=embed, file=get_footer_image(self))
|
await target.send(embed=embed)
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -948,7 +825,7 @@ class Aurora(commands.Cog):
|
||||||
moderation_type="unbanned",
|
moderation_type="unbanned",
|
||||||
response=await interaction.original_response(),
|
response=await interaction.original_response(),
|
||||||
)
|
)
|
||||||
await target.send(embed=embed, file=get_footer_image(self))
|
await target.send(embed=embed)
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -1427,7 +1304,7 @@ class Aurora(commands.Cog):
|
||||||
os.remove(filename)
|
os.remove(filename)
|
||||||
return
|
return
|
||||||
await interaction.response.send_message(
|
await interaction.response.send_message(
|
||||||
content=box(json.dumps(case_dict, indent=2), 'json'),
|
content=box({json.dumps(case_dict, indent=2)}),
|
||||||
ephemeral=ephemeral,
|
ephemeral=ephemeral,
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
@ -1607,13 +1484,10 @@ class Aurora(commands.Cog):
|
||||||
|
|
||||||
@tasks.loop(minutes=1)
|
@tasks.loop(minutes=1)
|
||||||
async def handle_expiry(self):
|
async def handle_expiry(self):
|
||||||
await self.bot.wait_until_red_ready()
|
|
||||||
current_time = time.time()
|
current_time = time.time()
|
||||||
database = connect()
|
database = connect()
|
||||||
cursor = database.cursor()
|
cursor = database.cursor()
|
||||||
global_unban_num = 0
|
global_num = 0
|
||||||
global_addrole_num = 0
|
|
||||||
global_removerole_num = 0
|
|
||||||
|
|
||||||
guilds: list[discord.Guild] = self.bot.guilds
|
guilds: list[discord.Guild] = self.bot.guilds
|
||||||
for guild in guilds:
|
for guild in guilds:
|
||||||
|
@ -1631,7 +1505,7 @@ class Aurora(commands.Cog):
|
||||||
target_ids = [row[0] for row in result]
|
target_ids = [row[0] for row in result]
|
||||||
moderation_ids = [row[1] for row in result]
|
moderation_ids = [row[1] for row in result]
|
||||||
|
|
||||||
unban_num = 0
|
num = 0
|
||||||
for target_id, moderation_id in zip(target_ids, moderation_ids):
|
for target_id, moderation_id in zip(target_ids, moderation_ids):
|
||||||
user: discord.User = await self.bot.fetch_user(target_id)
|
user: discord.User = await self.bot.fetch_user(target_id)
|
||||||
name = (
|
name = (
|
||||||
|
@ -1652,7 +1526,7 @@ class Aurora(commands.Cog):
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await user.send(embed=embed, file=get_footer_image(self))
|
await user.send(embed=embed)
|
||||||
except discord.errors.HTTPException:
|
except discord.errors.HTTPException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -1663,7 +1537,7 @@ class Aurora(commands.Cog):
|
||||||
guild.name,
|
guild.name,
|
||||||
guild.id,
|
guild.id,
|
||||||
)
|
)
|
||||||
unban_num = unban_num + 1
|
num = num + 1
|
||||||
except (
|
except (
|
||||||
discord.errors.NotFound,
|
discord.errors.NotFound,
|
||||||
discord.errors.Forbidden,
|
discord.errors.Forbidden,
|
||||||
|
@ -1678,87 +1552,44 @@ class Aurora(commands.Cog):
|
||||||
e,
|
e,
|
||||||
)
|
)
|
||||||
|
|
||||||
removerole_num = 0
|
expiry_query = f"UPDATE `moderation_{guild.id}` SET expired = 1 WHERE (end_timestamp != 0 AND end_timestamp <= ? AND expired = 0 AND moderation_type != 'BLACKLIST') OR (expired = 0 AND resolved = 1 AND moderation_type != 'BLACKLIST')"
|
||||||
addrole_query = f"SELECT target_id, moderation_id, role_id FROM moderation_{guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'ADDROLE' AND expired = 0"
|
|
||||||
try:
|
|
||||||
cursor.execute(addrole_query, (time.time(),))
|
|
||||||
result = cursor.fetchall()
|
|
||||||
except sqlite3.OperationalError:
|
|
||||||
continue
|
|
||||||
target_ids = [row[0] for row in result]
|
|
||||||
moderation_ids = [row[1] for row in result]
|
|
||||||
role_ids = [row[2] for row in result]
|
|
||||||
|
|
||||||
for target_id, moderation_id, role_id in zip(
|
|
||||||
target_ids, moderation_ids, role_ids
|
|
||||||
):
|
|
||||||
try:
|
|
||||||
member = await guild.fetch_member(target_id)
|
|
||||||
|
|
||||||
await member.remove_roles(
|
|
||||||
Object(role_id), reason=f"Automatic role removal from case #{moderation_id}"
|
|
||||||
)
|
|
||||||
|
|
||||||
removerole_num = removerole_num + 1
|
|
||||||
except (
|
|
||||||
discord.errors.NotFound,
|
|
||||||
discord.errors.Forbidden,
|
|
||||||
discord.errors.HTTPException,
|
|
||||||
) as e:
|
|
||||||
logger.error(
|
|
||||||
"Removing the role %s from user %s failed due to: \n%s",
|
|
||||||
role_id,
|
|
||||||
target_id,
|
|
||||||
e,
|
|
||||||
)
|
|
||||||
continue
|
|
||||||
|
|
||||||
addrole_num = 0
|
|
||||||
removerole_query = f"SELECT target_id, moderation_id, role_id FROM moderation_{guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'REMOVEROLE' AND expired = 0"
|
|
||||||
try:
|
|
||||||
cursor.execute(removerole_query, (time.time(),))
|
|
||||||
result = cursor.fetchall()
|
|
||||||
except sqlite3.OperationalError:
|
|
||||||
continue
|
|
||||||
target_ids = [row[0] for row in result]
|
|
||||||
moderation_ids = [row[1] for row in result]
|
|
||||||
role_ids = [row[2] for row in result]
|
|
||||||
|
|
||||||
for target_id, moderation_id, role_id in zip(
|
|
||||||
target_ids, moderation_ids, role_ids
|
|
||||||
):
|
|
||||||
try:
|
|
||||||
member = await guild.fetch_member(target_id)
|
|
||||||
|
|
||||||
await member.add_roles(
|
|
||||||
Object(role_id), reason=f"Automatic role addition from case #{moderation_id}"
|
|
||||||
)
|
|
||||||
|
|
||||||
addrole_num = addrole_num + 1
|
|
||||||
except (
|
|
||||||
discord.errors.NotFound,
|
|
||||||
discord.errors.Forbidden,
|
|
||||||
discord.errors.HTTPException,
|
|
||||||
) as e:
|
|
||||||
logger.error("Adding the role %s to user %s failed due to: \n%s", role_id, target_id, e)
|
|
||||||
continue
|
|
||||||
|
|
||||||
expiry_query = f"UPDATE `moderation_{guild.id}` SET expired = 1 WHERE (end_timestamp != 0 AND end_timestamp <= ? AND expired = 0) OR (expired = 0 AND resolved = 1);"
|
|
||||||
cursor.execute(expiry_query, (time.time(),))
|
cursor.execute(expiry_query, (time.time(),))
|
||||||
|
|
||||||
|
blacklist_query = f"SELECT target_id, moderation_id, role_id FROM moderation_{guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'BLACKLIST' AND expired = 0"
|
||||||
|
try:
|
||||||
|
cursor.execute(blacklist_query, (time.time(),))
|
||||||
|
result = cursor.fetchall()
|
||||||
|
except sqlite3.OperationalError:
|
||||||
|
continue
|
||||||
|
target_ids = [row[0] for row in result]
|
||||||
|
moderation_ids = [row[1] for row in result]
|
||||||
|
role_ids = [row[2] for row in result]
|
||||||
|
|
||||||
|
for target_id, moderation_id, role_id in zip(
|
||||||
|
target_ids, moderation_ids, role_ids
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
# member: discord.Member = await guild.fetch_member(target_id)
|
||||||
|
|
||||||
|
role: discord.Role = guild.get_role(role_id)
|
||||||
|
if role is None:
|
||||||
|
raise discord.errors.NotFound
|
||||||
|
except (
|
||||||
|
discord.errors.NotFound,
|
||||||
|
discord.errors.Forbidden,
|
||||||
|
discord.errors.HTTPException,
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
per_guild_completion_time = (time.time() - time_per_guild) * 1000
|
per_guild_completion_time = (time.time() - time_per_guild) * 1000
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"Completed expiry loop for %s (%s) in %sms with %s users unbanned, %s roles added, and %s roles removed",
|
"Completed expiry loop for %s (%s) in %sms with %s users unbanned",
|
||||||
guild.name,
|
guild.name,
|
||||||
guild.id,
|
guild.id,
|
||||||
f"{per_guild_completion_time:.6f}",
|
f"{per_guild_completion_time:.6f}",
|
||||||
unban_num,
|
num,
|
||||||
addrole_num,
|
|
||||||
removerole_num,
|
|
||||||
)
|
)
|
||||||
global_unban_num = global_unban_num + unban_num
|
global_num = global_num + num
|
||||||
global_addrole_num = global_addrole_num + addrole_num
|
|
||||||
global_removerole_num = global_removerole_num + removerole_num
|
|
||||||
|
|
||||||
database.commit()
|
database.commit()
|
||||||
cursor.close()
|
cursor.close()
|
||||||
|
@ -1766,11 +1597,9 @@ class Aurora(commands.Cog):
|
||||||
|
|
||||||
completion_time = (time.time() - current_time) * 1000
|
completion_time = (time.time() - current_time) * 1000
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"Completed expiry loop in %sms with %s users unbanned, %s roles added, and %s roles removed",
|
"Completed expiry loop in %sms with %s users unbanned",
|
||||||
f"{completion_time:.6f}",
|
f"{completion_time:.6f}",
|
||||||
global_unban_num,
|
global_num,
|
||||||
global_addrole_num,
|
|
||||||
global_removerole_num,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
########################################################################################################################
|
########################################################################################################################
|
||||||
|
@ -1788,16 +1617,14 @@ class Aurora(commands.Cog):
|
||||||
@aurora_settings.command(name="overrides", aliases=["override", "user"])
|
@aurora_settings.command(name="overrides", aliases=["override", "user"])
|
||||||
async def aurora_settings_overrides(self, ctx: commands.Context):
|
async def aurora_settings_overrides(self, ctx: commands.Context):
|
||||||
"""Manage Aurora's user overriddable settings."""
|
"""Manage Aurora's user overriddable settings."""
|
||||||
msg = await ctx.send(embed=await overrides_embed(ctx))
|
await ctx.send(embed=await overrides_embed(ctx), view=Overrides(ctx))
|
||||||
await msg.edit(view=Overrides(ctx, msg, 60))
|
|
||||||
|
|
||||||
@aurora_settings.command(name="guild", aliases=["server"])
|
@aurora_settings.command(name="guild", aliases=["server"])
|
||||||
@commands.admin_or_permissions(manage_guild=True)
|
@commands.admin_or_permissions(manage_guild=True)
|
||||||
@commands.guild_only()
|
@commands.guild_only()
|
||||||
async def aurora_settings_guild(self, ctx: commands.Context):
|
async def aurora_settings_guild(self, ctx: commands.Context):
|
||||||
"""Manage Aurora's guild settings."""
|
"""Manage Aurora's guild settings."""
|
||||||
msg = await ctx.send(embed=await guild_embed(ctx))
|
await ctx.send(embed=await guild_embed(ctx), view=Guild(ctx))
|
||||||
await msg.edit(view=Guild(ctx, msg, 60))
|
|
||||||
|
|
||||||
@aurora_settings.command(name="addrole", aliases=["removerole"])
|
@aurora_settings.command(name="addrole", aliases=["removerole"])
|
||||||
@commands.admin_or_permissions(manage_guild=True)
|
@commands.admin_or_permissions(manage_guild=True)
|
||||||
|
@ -1806,16 +1633,14 @@ class Aurora(commands.Cog):
|
||||||
"""Manage the addrole whitelist.
|
"""Manage the addrole whitelist.
|
||||||
|
|
||||||
Roles added to this list are also applied to `/removerole`."""
|
Roles added to this list are also applied to `/removerole`."""
|
||||||
msg = await ctx.send(embed=await addrole_embed(ctx))
|
await ctx.send(embed=await addrole_embed(ctx), view=Addrole(ctx))
|
||||||
await msg.edit(view=Addrole(ctx, msg, 60))
|
|
||||||
|
|
||||||
@aurora_settings.command(name="immunity")
|
@aurora_settings.command(name="immunity")
|
||||||
@commands.admin_or_permissions(manage_guild=True)
|
@commands.admin_or_permissions(manage_guild=True)
|
||||||
@commands.guild_only()
|
@commands.guild_only()
|
||||||
async def aurora_settings_immunity(self, ctx: commands.Context):
|
async def aurora_settings_immunity(self, ctx: commands.Context):
|
||||||
"""Manage the immunity whitelist."""
|
"""Manage the immunity whitelist."""
|
||||||
msg = await ctx.send(embed=await immune_embed(ctx))
|
await ctx.send(embed=await immune_embed(ctx), view=Immune(ctx))
|
||||||
await msg.edit(view=Immune(ctx, msg, 60))
|
|
||||||
|
|
||||||
@aurora.group(autohelp=True, name="import")
|
@aurora.group(autohelp=True, name="import")
|
||||||
@commands.admin()
|
@commands.admin()
|
||||||
|
|
Binary file not shown.
Before Width: | Height: | Size: 6.2 KiB |
|
@ -43,7 +43,7 @@ class ImportAuroraView(ui.View):
|
||||||
file = await self.ctx.message.attachments[0].read()
|
file = await self.ctx.message.attachments[0].read()
|
||||||
data: list[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", "ADDROLE", "REMOVEROLE", "MUTE", "UNMUTE", "KICK", "TEMPBAN", "BAN", "UNBAN"]
|
user_mod_types = ["NOTE", "WARN", "MUTE", "UNMUTE", "KICK", "BAN", "UNBAN"]
|
||||||
|
|
||||||
channel_mod_types = ["SLOWMODE", "LOCKDOWN"]
|
channel_mod_types = ["SLOWMODE", "LOCKDOWN"]
|
||||||
|
|
||||||
|
@ -58,8 +58,6 @@ class ImportAuroraView(ui.View):
|
||||||
case["target_type"] = "USER"
|
case["target_type"] = "USER"
|
||||||
elif case["moderation_type"] in channel_mod_types:
|
elif case["moderation_type"] in channel_mod_types:
|
||||||
case["target_type"] = "CHANNEL"
|
case["target_type"] = "CHANNEL"
|
||||||
else:
|
|
||||||
case["target_type"] = "USER"
|
|
||||||
|
|
||||||
if "role_id" not in case or not case["role_id"]:
|
if "role_id" not in case or not case["role_id"]:
|
||||||
case["role_id"] = 0
|
case["role_id"] = 0
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from discord import ButtonStyle, Interaction, Message, ui
|
from discord import ButtonStyle, Interaction, ui
|
||||||
from redbot.core import commands
|
from redbot.core import commands
|
||||||
from redbot.core.utils.chat_formatting import error
|
from redbot.core.utils.chat_formatting import error
|
||||||
|
|
||||||
|
@ -7,14 +7,9 @@ from aurora.utilities.factory import addrole_embed
|
||||||
|
|
||||||
|
|
||||||
class Addrole(ui.View):
|
class Addrole(ui.View):
|
||||||
def __init__(self, ctx: commands.Context, message: Message, timeout: int = None):
|
def __init__(self, ctx: commands.Context):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.ctx = ctx
|
self.ctx = ctx
|
||||||
self.message = message
|
|
||||||
self.timeout = timeout
|
|
||||||
|
|
||||||
async def on_timeout(self):
|
|
||||||
await self.message.edit(view=None)
|
|
||||||
|
|
||||||
@ui.select(cls=ui.RoleSelect, placeholder="Select a role", min_values=0, max_values=25)
|
@ui.select(cls=ui.RoleSelect, placeholder="Select a role", min_values=0, max_values=25)
|
||||||
async def addrole_select(self, interaction: Interaction, select: ui.RoleSelect):
|
async def addrole_select(self, interaction: Interaction, select: ui.RoleSelect):
|
||||||
|
@ -22,13 +17,12 @@ class Addrole(ui.View):
|
||||||
await interaction.response.send_message(error("You must have the manage guild permission to add roles to the addrole whitelist."), ephemeral=True)
|
await interaction.response.send_message(error("You must have the manage guild permission to add roles to the addrole whitelist."), ephemeral=True)
|
||||||
return
|
return
|
||||||
await interaction.response.defer()
|
await interaction.response.defer()
|
||||||
async with config.guild(self.ctx.guild).addrole_whitelist() as addrole_whitelist:
|
addrole_whitelist: list = await config.guild(self.ctx.guild).addrole_whitelist()
|
||||||
addrole_whitelist: list # type hint
|
if select.values[0].id in addrole_whitelist:
|
||||||
for value in select.values:
|
addrole_whitelist.remove(select.values[0].id)
|
||||||
if value.id in addrole_whitelist:
|
|
||||||
addrole_whitelist.remove(value.id)
|
|
||||||
else:
|
else:
|
||||||
addrole_whitelist.append(value.id)
|
addrole_whitelist.append(select.values[0].id)
|
||||||
|
await config.guild(self.ctx.guild).addrole_whitelist.set(addrole_whitelist)
|
||||||
await interaction.message.edit(embed=await addrole_embed(self.ctx))
|
await interaction.message.edit(embed=await addrole_embed(self.ctx))
|
||||||
|
|
||||||
@ui.button(label="Clear", style=ButtonStyle.red, row=1)
|
@ui.button(label="Clear", style=ButtonStyle.red, row=1)
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from discord import ButtonStyle, Interaction, Message, ui
|
from discord import ButtonStyle, Interaction, ui
|
||||||
from redbot.core import commands
|
from redbot.core import commands
|
||||||
|
|
||||||
from aurora.utilities.config import config
|
from aurora.utilities.config import config
|
||||||
|
@ -7,14 +7,9 @@ from aurora.utilities.utils import create_pagesize_options
|
||||||
|
|
||||||
|
|
||||||
class Guild(ui.View):
|
class Guild(ui.View):
|
||||||
def __init__(self, ctx: commands.Context, message: Message, timeout: int = None):
|
def __init__(self, ctx: commands.Context):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.ctx = ctx
|
self.ctx = ctx
|
||||||
self.message = message
|
|
||||||
self.timeout = timeout
|
|
||||||
|
|
||||||
async def on_timeout(self):
|
|
||||||
await self.message.edit(view=None)
|
|
||||||
|
|
||||||
@ui.button(label="Show Moderator", style=ButtonStyle.green, row=0)
|
@ui.button(label="Show Moderator", style=ButtonStyle.green, row=0)
|
||||||
async def show_moderator(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
async def show_moderator(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
||||||
|
@ -22,7 +17,7 @@ class Guild(ui.View):
|
||||||
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
|
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
|
||||||
return
|
return
|
||||||
await interaction.response.defer()
|
await interaction.response.defer()
|
||||||
current_setting = await config.guild(interaction.guild).show_moderator()
|
current_setting = await config.guild(interaction.guild).show_moderator
|
||||||
await config.guild(interaction.guild).show_moderator.set(not current_setting)
|
await config.guild(interaction.guild).show_moderator.set(not current_setting)
|
||||||
await interaction.message.edit(embed=await guild_embed(self.ctx))
|
await interaction.message.edit(embed=await guild_embed(self.ctx))
|
||||||
|
|
||||||
|
@ -36,16 +31,6 @@ class Guild(ui.View):
|
||||||
await config.guild(interaction.guild).use_discord_permissions.set(not current_setting)
|
await config.guild(interaction.guild).use_discord_permissions.set(not current_setting)
|
||||||
await interaction.message.edit(embed=await guild_embed(self.ctx))
|
await interaction.message.edit(embed=await guild_embed(self.ctx))
|
||||||
|
|
||||||
@ui.button(label="Respect Hierarchy", style=ButtonStyle.green, row=0)
|
|
||||||
async def respect_heirarchy(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
|
||||||
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
|
||||||
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
|
|
||||||
return
|
|
||||||
await interaction.response.defer()
|
|
||||||
current_setting = await config.guild(interaction.guild).respect_hierarchy()
|
|
||||||
await config.guild(interaction.guild).respect_hierarchy.set(not current_setting)
|
|
||||||
await interaction.message.edit(embed=await guild_embed(self.ctx))
|
|
||||||
|
|
||||||
@ui.button(label="Ignore Modlog", style=ButtonStyle.green, row=0)
|
@ui.button(label="Ignore Modlog", style=ButtonStyle.green, row=0)
|
||||||
async def ignore_modlog(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
async def ignore_modlog(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
||||||
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from discord import ButtonStyle, Interaction, Message, ui
|
from discord import ButtonStyle, Interaction, ui
|
||||||
from redbot.core import commands
|
from redbot.core import commands
|
||||||
from redbot.core.utils.chat_formatting import error
|
from redbot.core.utils.chat_formatting import error
|
||||||
|
|
||||||
|
@ -7,14 +7,9 @@ from aurora.utilities.factory import immune_embed
|
||||||
|
|
||||||
|
|
||||||
class Immune(ui.View):
|
class Immune(ui.View):
|
||||||
def __init__(self, ctx: commands.Context, message: Message, timeout: int = None):
|
def __init__(self, ctx: commands.Context):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.ctx = ctx
|
self.ctx = ctx
|
||||||
self.message = message
|
|
||||||
self.timeout = timeout
|
|
||||||
|
|
||||||
async def on_timeout(self):
|
|
||||||
await self.message.edit(view=None)
|
|
||||||
|
|
||||||
@ui.select(cls=ui.RoleSelect, placeholder="Select a role", min_values=0, max_values=25)
|
@ui.select(cls=ui.RoleSelect, placeholder="Select a role", min_values=0, max_values=25)
|
||||||
async def immune_select(self, interaction: Interaction, select: ui.RoleSelect):
|
async def immune_select(self, interaction: Interaction, select: ui.RoleSelect):
|
||||||
|
@ -22,13 +17,13 @@ class Immune(ui.View):
|
||||||
await interaction.response.send_message(error("You must have the manage guild permission to add immune roles."), ephemeral=True)
|
await interaction.response.send_message(error("You must have the manage guild permission to add immune roles."), ephemeral=True)
|
||||||
return
|
return
|
||||||
await interaction.response.defer()
|
await interaction.response.defer()
|
||||||
async with config.guild(self.ctx.guild).immune_roles() as immune_roles:
|
immune_roles: list = await config.guild(self.ctx.guild).immune_roles()
|
||||||
immune_roles: list # type hint
|
for role in select.values:
|
||||||
for value in select.values:
|
if role.id in immune_roles:
|
||||||
if value.id in immune_roles:
|
immune_roles.remove(role.id)
|
||||||
immune_roles.remove(value.id)
|
|
||||||
else:
|
else:
|
||||||
immune_roles.append(value.id)
|
immune_roles.append(role.id)
|
||||||
|
await config.guild(self.ctx.guild).immune_roles.set(immune_roles)
|
||||||
await interaction.message.edit(embed=await immune_embed(self.ctx))
|
await interaction.message.edit(embed=await immune_embed(self.ctx))
|
||||||
|
|
||||||
@ui.button(label="Clear", style=ButtonStyle.red, row=1)
|
@ui.button(label="Clear", style=ButtonStyle.red, row=1)
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from discord import ButtonStyle, Interaction, Message, ui
|
from discord import ButtonStyle, Interaction, ui
|
||||||
from redbot.core import commands
|
from redbot.core import commands
|
||||||
|
|
||||||
from aurora.utilities.config import config
|
from aurora.utilities.config import config
|
||||||
|
@ -7,14 +7,9 @@ from aurora.utilities.utils import create_pagesize_options
|
||||||
|
|
||||||
|
|
||||||
class Overrides(ui.View):
|
class Overrides(ui.View):
|
||||||
def __init__(self, ctx: commands.Context, message: Message, timeout: int = None):
|
def __init__(self, ctx: commands.Context):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.ctx = ctx
|
self.ctx = ctx
|
||||||
self.message = message
|
|
||||||
self.timeout = timeout
|
|
||||||
|
|
||||||
async def on_timeout(self):
|
|
||||||
await self.message.edit(view=None)
|
|
||||||
|
|
||||||
@ui.button(label="Auto Evidence Format", style=ButtonStyle.green, row=0)
|
@ui.button(label="Auto Evidence Format", style=ButtonStyle.green, row=0)
|
||||||
async def auto_evidenceformat(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
async def auto_evidenceformat(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument
|
||||||
|
|
|
@ -7,7 +7,6 @@ def register_config(config_obj: Config):
|
||||||
config_obj.register_guild(
|
config_obj.register_guild(
|
||||||
show_moderator=True,
|
show_moderator=True,
|
||||||
use_discord_permissions=True,
|
use_discord_permissions=True,
|
||||||
respect_hierarchy=True,
|
|
||||||
ignore_modlog=True,
|
ignore_modlog=True,
|
||||||
ignore_other_bots=True,
|
ignore_other_bots=True,
|
||||||
dm_users=True,
|
dm_users=True,
|
||||||
|
|
|
@ -46,8 +46,6 @@ async def message_factory(
|
||||||
else:
|
else:
|
||||||
guild_name = guild.name
|
guild_name = guild.name
|
||||||
|
|
||||||
title = moderation_type
|
|
||||||
|
|
||||||
if moderation_type in ["tempbanned", "muted"] and duration:
|
if moderation_type in ["tempbanned", "muted"] and duration:
|
||||||
embed_duration = f" for {humanize_timedelta(timedelta=duration)}"
|
embed_duration = f" for {humanize_timedelta(timedelta=duration)}"
|
||||||
else:
|
else:
|
||||||
|
@ -57,17 +55,13 @@ async def message_factory(
|
||||||
embed_desc = "received a"
|
embed_desc = "received a"
|
||||||
elif moderation_type == "addrole":
|
elif moderation_type == "addrole":
|
||||||
embed_desc = f"received the {role.name} role"
|
embed_desc = f"received the {role.name} role"
|
||||||
title = "Role Added"
|
|
||||||
moderation_type = ""
|
|
||||||
elif moderation_type == "removerole":
|
elif moderation_type == "removerole":
|
||||||
embed_desc = f"lost the {role.name} role"
|
embed_desc = f"lost the {role.name} role"
|
||||||
title = "Role Removed"
|
|
||||||
moderation_type = ""
|
|
||||||
else:
|
else:
|
||||||
embed_desc = "been"
|
embed_desc = "been"
|
||||||
|
|
||||||
embed = Embed(
|
embed = Embed(
|
||||||
title=str.title(title),
|
title=str.title(moderation_type),
|
||||||
description=f"You have {embed_desc} {moderation_type}{embed_duration} in {guild_name}.",
|
description=f"You have {embed_desc} {moderation_type}{embed_duration} in {guild_name}.",
|
||||||
color=color,
|
color=color,
|
||||||
timestamp=datetime.now(),
|
timestamp=datetime.now(),
|
||||||
|
@ -87,7 +81,7 @@ async def message_factory(
|
||||||
|
|
||||||
embed.set_footer(
|
embed.set_footer(
|
||||||
text=f"Case #{await get_next_case_number(guild.id):,}",
|
text=f"Case #{await get_next_case_number(guild.id):,}",
|
||||||
icon_url="attachment://arrow.png",
|
icon_url="https://cdn.discordapp.com/attachments/1070822161389994054/1159469476773904414/arrow-right-circle-icon-512x512-2p1e2aaw.png?ex=65312319&is=651eae19&hm=3cebdd28e805c13a79ec48ef87c32ca532ffa6b9ede2e48d0cf8e5e81f3a6818&",
|
||||||
)
|
)
|
||||||
|
|
||||||
return embed
|
return embed
|
||||||
|
@ -269,9 +263,6 @@ async def case_factory(interaction: Interaction, case_dict: dict) -> Embed:
|
||||||
else "\n**Changes:** 0"
|
else "\n**Changes:** 0"
|
||||||
)
|
)
|
||||||
|
|
||||||
if case_dict["role_id"]:
|
|
||||||
embed.description += f"\n**Role:** <@&{case_dict['role_id']}>"
|
|
||||||
|
|
||||||
if case_dict["metadata"]:
|
if case_dict["metadata"]:
|
||||||
if case_dict["metadata"]["imported_from"]:
|
if case_dict["metadata"]["imported_from"]:
|
||||||
embed.description += (
|
embed.description += (
|
||||||
|
@ -381,10 +372,6 @@ async def evidenceformat_factory(interaction: Interaction, case_dict: dict) -> s
|
||||||
|
|
||||||
content = f"Case: {case_dict['moderation_id']:,} ({str.title(case_dict['moderation_type'])})\nTarget: {target_name} ({target_user['id']})\nModerator: {moderator_name} ({moderator_user['id']})"
|
content = f"Case: {case_dict['moderation_id']:,} ({str.title(case_dict['moderation_type'])})\nTarget: {target_name} ({target_user['id']})\nModerator: {moderator_name} ({moderator_user['id']})"
|
||||||
|
|
||||||
if case_dict["role_id"] != "0":
|
|
||||||
role = interaction.guild.get_role(int(case_dict["role_id"]))
|
|
||||||
content += "\nRole: " + (role.name if role is not None else case_dict["role_id"])
|
|
||||||
|
|
||||||
if case_dict["duration"] != "NULL":
|
if case_dict["duration"] != "NULL":
|
||||||
hours, minutes, seconds = map(int, case_dict["duration"].split(":"))
|
hours, minutes, seconds = map(int, case_dict["duration"].split(":"))
|
||||||
td = timedelta(hours=hours, minutes=minutes, seconds=seconds)
|
td = timedelta(hours=hours, minutes=minutes, seconds=seconds)
|
||||||
|
@ -464,7 +451,6 @@ async def guild_embed(ctx: commands.Context) -> Embed:
|
||||||
ctx.guild
|
ctx.guild
|
||||||
).history_inline_pagesize(),
|
).history_inline_pagesize(),
|
||||||
"auto_evidenceformat": await config.guild(ctx.guild).auto_evidenceformat(),
|
"auto_evidenceformat": await config.guild(ctx.guild).auto_evidenceformat(),
|
||||||
"respect_hierarchy": await config.guild(ctx.guild).respect_hierarchy(),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
channel = ctx.guild.get_channel(guild_settings["log_channel"])
|
channel = ctx.guild.get_channel(guild_settings["log_channel"])
|
||||||
|
@ -481,9 +467,6 @@ async def guild_embed(ctx: commands.Context) -> Embed:
|
||||||
+ bold("Use Discord Permissions: ")
|
+ bold("Use Discord Permissions: ")
|
||||||
+ get_bool_emoji(guild_settings["use_discord_permissions"]),
|
+ get_bool_emoji(guild_settings["use_discord_permissions"]),
|
||||||
"- "
|
"- "
|
||||||
+ bold("Respect Hierarchy: ")
|
|
||||||
+ get_bool_emoji(guild_settings["respect_hierarchy"]),
|
|
||||||
"- "
|
|
||||||
+ bold("Ignore Modlog: ")
|
+ bold("Ignore Modlog: ")
|
||||||
+ get_bool_emoji(guild_settings["ignore_modlog"]),
|
+ get_bool_emoji(guild_settings["ignore_modlog"]),
|
||||||
"- "
|
"- "
|
||||||
|
@ -523,29 +506,15 @@ async def guild_embed(ctx: commands.Context) -> Embed:
|
||||||
async def addrole_embed(ctx: commands.Context) -> Embed:
|
async def addrole_embed(ctx: commands.Context) -> Embed:
|
||||||
"""Generates a configuration menu field value for a guild's addrole whitelist."""
|
"""Generates a configuration menu field value for a guild's addrole whitelist."""
|
||||||
|
|
||||||
roles = []
|
whitelist = await config.guild(ctx.guild).addrole_whitelist()
|
||||||
async with config.guild(ctx.guild).addrole_whitelist() as whitelist:
|
if whitelist:
|
||||||
for role in whitelist:
|
whitelist = [
|
||||||
evalulated_role = ctx.guild.get_role(role) or error(f"`{role}` (Not Found)")
|
ctx.guild.get_role(role).mention or error(f"`{role}` (Not Found)")
|
||||||
if isinstance(evalulated_role, Role):
|
for role in whitelist
|
||||||
roles.append({
|
]
|
||||||
"id": evalulated_role.id,
|
whitelist = "\n".join(whitelist)
|
||||||
"mention": evalulated_role.mention,
|
|
||||||
"position": evalulated_role.position
|
|
||||||
})
|
|
||||||
else:
|
else:
|
||||||
roles.append({
|
whitelist = warning("No roles are on the addrole whitelist!")
|
||||||
"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 = await _config(ctx)
|
||||||
e.title += ": Addrole Whitelist"
|
e.title += ": Addrole Whitelist"
|
||||||
|
@ -553,8 +522,8 @@ async def addrole_embed(ctx: commands.Context) -> Embed:
|
||||||
"Use the select menu below to manage this guild's addrole whitelist."
|
"Use the select menu below to manage this guild's addrole whitelist."
|
||||||
)
|
)
|
||||||
|
|
||||||
if len(whitelist_str) > 4000 and len(whitelist_str) < 5000:
|
if len(whitelist) > 4000 and len(whitelist) < 5000:
|
||||||
lines = whitelist_str.split("\n")
|
lines = whitelist.split("\n")
|
||||||
chunks = []
|
chunks = []
|
||||||
chunk = ""
|
chunk = ""
|
||||||
for line in lines:
|
for line in lines:
|
||||||
|
@ -568,35 +537,21 @@ async def addrole_embed(ctx: commands.Context) -> Embed:
|
||||||
for chunk in chunks:
|
for chunk in chunks:
|
||||||
e.add_field(name="", value=chunk)
|
e.add_field(name="", value=chunk)
|
||||||
else:
|
else:
|
||||||
e.description += "\n\n" + whitelist_str
|
e.description += "\n\n" + whitelist
|
||||||
|
|
||||||
return e
|
return e
|
||||||
|
|
||||||
|
|
||||||
async def immune_embed(ctx: commands.Context) -> Embed:
|
async def immune_embed(ctx: commands.Context) -> Embed:
|
||||||
"""Generates a configuration menu embed for a guild's immune roles."""
|
"""Generates a configuration menu field value for a guild's immune roles."""
|
||||||
|
|
||||||
roles = []
|
immune_roles = await config.guild(ctx.guild).immune_roles()
|
||||||
async with config.guild(ctx.guild).immune_roles() as immune_roles:
|
if immune_roles:
|
||||||
for role in immune_roles:
|
immune_str = [
|
||||||
evalulated_role = ctx.guild.get_role(role) or error(f"`{role}` (Not Found)")
|
ctx.guild.get_role(role).mention or error(f"`{role}` (Not Found)")
|
||||||
if isinstance(evalulated_role, Role):
|
for role in immune_roles
|
||||||
roles.append({
|
]
|
||||||
"id": evalulated_role.id,
|
immune_str = "\n".join(immune_str)
|
||||||
"mention": evalulated_role.mention,
|
|
||||||
"position": evalulated_role.position
|
|
||||||
})
|
|
||||||
else:
|
|
||||||
roles.append({
|
|
||||||
"id": role,
|
|
||||||
"mention": error(f"`{role}` (Not Found)"),
|
|
||||||
"position": 0
|
|
||||||
})
|
|
||||||
|
|
||||||
if roles:
|
|
||||||
roles = sorted(roles, key=lambda x: x["position"], reverse=True)
|
|
||||||
roles = [role["mention"] for role in roles]
|
|
||||||
immune_str = "\n".join(roles)
|
|
||||||
else:
|
else:
|
||||||
immune_str = warning("No roles are set as immune roles!")
|
immune_str = warning("No roles are set as immune roles!")
|
||||||
|
|
||||||
|
|
|
@ -1,3 +1,3 @@
|
||||||
from red_commons.logging import getLogger
|
from red_commons.logging import getLogger
|
||||||
|
|
||||||
logger = getLogger("red.SeaCogs.Aurora")
|
logger = getLogger("red.seacogs.aurora")
|
||||||
|
|
|
@ -2,12 +2,12 @@
|
||||||
import json
|
import json
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from datetime import timedelta as td
|
from datetime import timedelta as td
|
||||||
from typing import Optional, Union
|
from typing import Union
|
||||||
|
|
||||||
from dateutil.relativedelta import relativedelta as rd
|
from dateutil.relativedelta import relativedelta as rd
|
||||||
from discord import File, Guild, Interaction, Member, SelectOption, User
|
from discord import Guild, Interaction, Member, SelectOption, User
|
||||||
from discord.errors import Forbidden, NotFound
|
from discord.errors import Forbidden, NotFound
|
||||||
from redbot.core import commands, data_manager
|
from redbot.core import commands
|
||||||
from redbot.core.utils.chat_formatting import error
|
from redbot.core.utils.chat_formatting import error
|
||||||
|
|
||||||
from .config import config
|
from .config import config
|
||||||
|
@ -77,7 +77,7 @@ async def check_moddable(
|
||||||
return False
|
return False
|
||||||
|
|
||||||
if isinstance(target, Member):
|
if isinstance(target, Member):
|
||||||
if interaction.user.top_role <= target.top_role and await config.guild(interaction.guild).respect_hierarchy() is True:
|
if interaction.user.top_role <= target.top_role:
|
||||||
await interaction.response.send_message(
|
await interaction.response.send_message(
|
||||||
content=error(
|
content=error(
|
||||||
"You cannot moderate members with a higher role than you!"
|
"You cannot moderate members with a higher role than you!"
|
||||||
|
@ -250,7 +250,7 @@ def convert_timedelta_to_str(timedelta: td) -> str:
|
||||||
return f"{hours}:{minutes}:{seconds}"
|
return f"{hours}:{minutes}:{seconds}"
|
||||||
|
|
||||||
|
|
||||||
def get_bool_emoji(value: Optional[bool]) -> str:
|
def get_bool_emoji(value: bool) -> str:
|
||||||
"""Returns a unicode emoji based on a boolean value."""
|
"""Returns a unicode emoji based on a boolean value."""
|
||||||
if value is True:
|
if value is True:
|
||||||
return "\N{WHITE HEAVY CHECK MARK}"
|
return "\N{WHITE HEAVY CHECK MARK}"
|
||||||
|
@ -291,8 +291,3 @@ def timedelta_from_relativedelta(relativedelta: rd) -> td:
|
||||||
now = datetime.now()
|
now = datetime.now()
|
||||||
then = now - relativedelta
|
then = now - relativedelta
|
||||||
return now - then
|
return now - then
|
||||||
|
|
||||||
def get_footer_image(coginstance: commands.Cog) -> File:
|
|
||||||
"""Returns the footer image for the embeds."""
|
|
||||||
image_path = data_manager.bundled_data_path(coginstance) / "arrow.png"
|
|
||||||
return File(image_path, filename="arrow.png", description="arrow")
|
|
||||||
|
|
|
@ -14,7 +14,8 @@ from redbot.cogs.downloader import errors
|
||||||
from redbot.cogs.downloader.converters import InstalledCog
|
from redbot.cogs.downloader.converters import InstalledCog
|
||||||
from redbot.core import commands
|
from redbot.core import commands
|
||||||
from redbot.core.bot import Red
|
from redbot.core.bot import Red
|
||||||
from redbot.core.utils.chat_formatting import error, humanize_list, text_to_file
|
from redbot.core.utils.chat_formatting import (error, humanize_list,
|
||||||
|
text_to_file)
|
||||||
|
|
||||||
|
|
||||||
# pylint: disable=protected-access
|
# pylint: disable=protected-access
|
||||||
|
@ -22,13 +23,12 @@ class Backup(commands.Cog):
|
||||||
"""A utility to make reinstalling repositories and cogs after migrating the bot far easier."""
|
"""A utility to make reinstalling repositories and cogs after migrating the bot far easier."""
|
||||||
|
|
||||||
__author__ = ["SeaswimmerTheFsh"]
|
__author__ = ["SeaswimmerTheFsh"]
|
||||||
__version__ = "1.1.0"
|
__version__ = "1.0.1"
|
||||||
__documentation__ = "https://seacogs.coastalcommits.com/backup/"
|
|
||||||
|
|
||||||
def __init__(self, bot: Red):
|
def __init__(self, bot: Red):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
self.logger = getLogger("red.SeaCogs.Backup")
|
self.logger = getLogger("red.seacogs.backup")
|
||||||
|
|
||||||
def format_help_for_context(self, ctx: commands.Context) -> str:
|
def format_help_for_context(self, ctx: commands.Context) -> str:
|
||||||
pre_processed = super().format_help_for_context(ctx) or ""
|
pre_processed = super().format_help_for_context(ctx) or ""
|
||||||
|
@ -37,7 +37,6 @@ class Backup(commands.Cog):
|
||||||
f"{pre_processed}{n}",
|
f"{pre_processed}{n}",
|
||||||
f"Cog Version: **{self.__version__}**",
|
f"Cog Version: **{self.__version__}**",
|
||||||
f"Author: {humanize_list(self.__author__)}",
|
f"Author: {humanize_list(self.__author__)}",
|
||||||
f"Documentation: {self.__documentation__}",
|
|
||||||
]
|
]
|
||||||
return "\n".join(text)
|
return "\n".join(text)
|
||||||
|
|
||||||
|
@ -100,7 +99,7 @@ class Backup(commands.Cog):
|
||||||
except (json.JSONDecodeError, IndexError):
|
except (json.JSONDecodeError, IndexError):
|
||||||
try:
|
try:
|
||||||
export = json.loads(await ctx.message.reference.resolved.attachments[0].read())
|
export = json.loads(await ctx.message.reference.resolved.attachments[0].read())
|
||||||
except (json.JSONDecodeError, IndexError, AttributeError):
|
except (json.JSONDecodeError, IndexError):
|
||||||
await ctx.send(error("Please provide a valid JSON export file."))
|
await ctx.send(error("Please provide a valid JSON export file."))
|
||||||
return
|
return
|
||||||
|
|
||||||
|
@ -160,15 +159,17 @@ class Backup(commands.Cog):
|
||||||
)
|
)
|
||||||
self.logger.debug("Repository %s already exists", name)
|
self.logger.debug("Repository %s already exists", name)
|
||||||
|
|
||||||
except errors.AuthenticationError as err:
|
# This is commented out because errors.AuthenticationError is not yet implemented in Red 3.5.5's Downloader cog.
|
||||||
repo_e.append(f"Authentication error while adding repository {name}. See logs for more information.")
|
# Rather, it is only in the development version and will be added in version 3.5.6 (or whatever the next version is).
|
||||||
self.logger.exception(
|
# except errors.AuthenticationError as err:
|
||||||
"Something went wrong whilst cloning %s (to revision %s)",
|
# repo_e.append(f"Authentication error while adding repository {name}. See logs for more information.")
|
||||||
url,
|
# self.logger.exception(
|
||||||
branch,
|
# "Something went wrong whilst cloning %s (to revision %s)",
|
||||||
exc_info=err,
|
# url,
|
||||||
)
|
# branch,
|
||||||
continue
|
# exc_info=err,
|
||||||
|
# )
|
||||||
|
# continue
|
||||||
|
|
||||||
except errors.CloningError as err:
|
except errors.CloningError as err:
|
||||||
repo_e.append(
|
repo_e.append(
|
||||||
|
|
|
@ -7,8 +7,8 @@
|
||||||
"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.6",
|
"min_bot_version": "3.5.0",
|
||||||
"max_bot_version": "3.5.9",
|
"max_bot_version": "3.5.5",
|
||||||
"min_python_version": [3, 9, 0],
|
"min_python_version": [3, 9, 0],
|
||||||
"tags": [
|
"tags": [
|
||||||
"utility",
|
"utility",
|
||||||
|
|
|
@ -6,14 +6,11 @@
|
||||||
# |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_|
|
# |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_|
|
||||||
|
|
||||||
import random
|
import random
|
||||||
from io import BytesIO
|
|
||||||
|
|
||||||
import aiohttp
|
import aiohttp
|
||||||
import numpy as np
|
from discord import Embed
|
||||||
from discord import Colour, Embed, File
|
|
||||||
from PIL import Image
|
|
||||||
from red_commons.logging import getLogger
|
from red_commons.logging import getLogger
|
||||||
from redbot.core import Config, commands, data_manager
|
from redbot.core import Config, commands
|
||||||
from redbot.core.bot import Red
|
from redbot.core.bot import Red
|
||||||
from redbot.core.utils.chat_formatting import error, humanize_list
|
from redbot.core.utils.chat_formatting import error, humanize_list
|
||||||
|
|
||||||
|
@ -25,8 +22,7 @@ class Bible(commands.Cog):
|
||||||
"""Retrieve Bible verses from the API.bible API."""
|
"""Retrieve Bible verses from the API.bible API."""
|
||||||
|
|
||||||
__author__ = ["SeaswimmerTheFsh"]
|
__author__ = ["SeaswimmerTheFsh"]
|
||||||
__version__ = "1.1.0"
|
__version__ = "1.0.1"
|
||||||
__documentation__ = "https://seacogs.coastalcommits.com/bible/"
|
|
||||||
|
|
||||||
def __init__(self, bot: Red):
|
def __init__(self, bot: Red):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
@ -35,7 +31,7 @@ class Bible(commands.Cog):
|
||||||
self.config = Config.get_conf(
|
self.config = Config.get_conf(
|
||||||
self, identifier=481923957134912, force_registration=True
|
self, identifier=481923957134912, force_registration=True
|
||||||
)
|
)
|
||||||
self.logger = getLogger("red.SeaCogs.Bible")
|
self.logger = getLogger("red.seacogs.bible")
|
||||||
self.config.register_global(bible="de4e12af7f28f599-02")
|
self.config.register_global(bible="de4e12af7f28f599-02")
|
||||||
self.config.register_user(bible=None)
|
self.config.register_user(bible=None)
|
||||||
|
|
||||||
|
@ -46,26 +42,9 @@ class Bible(commands.Cog):
|
||||||
f"{pre_processed}{n}",
|
f"{pre_processed}{n}",
|
||||||
f"Cog Version: **{self.__version__}**",
|
f"Cog Version: **{self.__version__}**",
|
||||||
f"Author: {humanize_list(self.__author__)}",
|
f"Author: {humanize_list(self.__author__)}",
|
||||||
f"Documentation: {self.__documentation__}",
|
|
||||||
]
|
]
|
||||||
return "\n".join(text)
|
return "\n".join(text)
|
||||||
|
|
||||||
def get_icon(self, color: Colour) -> File:
|
|
||||||
"""Get the docs.api.bible favicon with a given color."""
|
|
||||||
image_path = data_manager.bundled_data_path(self) / "api.bible-logo.png"
|
|
||||||
image = Image.open(image_path)
|
|
||||||
image = image.convert("RGBA")
|
|
||||||
data = np.array(image)
|
|
||||||
red, green, blue, alpha = data.T # pylint: disable=unused-variable
|
|
||||||
white_areas = (red == 255) & (blue == 255) & (green == 255)
|
|
||||||
data[..., :-1][white_areas.T] = color.to_rgb()
|
|
||||||
image = Image.fromarray(data)
|
|
||||||
|
|
||||||
with BytesIO() as image_binary:
|
|
||||||
image.save(image_binary, "PNG")
|
|
||||||
image_binary.seek(0)
|
|
||||||
return File(image_binary, filename="icon.png", description="API.Bible Icon")
|
|
||||||
|
|
||||||
async def translate_book_name(self, bible_id: str, book_name: str) -> str:
|
async def translate_book_name(self, bible_id: str, book_name: str) -> str:
|
||||||
"""Translate a book name to a book ID."""
|
"""Translate a book name to a book ID."""
|
||||||
book_name_list = [
|
book_name_list = [
|
||||||
|
@ -267,17 +246,15 @@ class Bible(commands.Cog):
|
||||||
return
|
return
|
||||||
|
|
||||||
if await ctx.embed_requested():
|
if await ctx.embed_requested():
|
||||||
icon = self.get_icon(await ctx.embed_color())
|
|
||||||
embed = Embed(
|
embed = Embed(
|
||||||
title=f"{passage['reference']}",
|
title=f"{passage['reference']}",
|
||||||
description=passage["content"].replace("¶ ", ""),
|
description=passage["content"].replace("¶ ", ""),
|
||||||
color=await ctx.embed_color(),
|
color=await self.bot.get_embed_color(ctx.channel),
|
||||||
)
|
)
|
||||||
embed.set_footer(
|
embed.set_footer(
|
||||||
text=f"{ctx.prefix}bible passage - Powered by API.Bible - {version.abbreviationLocal} ({version.languageLocal}, {version.descriptionLocal})",
|
text=f"{ctx.prefix}bible passage - Powered by API.Bible - {version.abbreviationLocal} ({version.languageLocal}, {version.descriptionLocal})"
|
||||||
icon_url="attachment://icon.png"
|
|
||||||
)
|
)
|
||||||
await ctx.send(embed=embed, file=icon)
|
await ctx.send(embed=embed)
|
||||||
else:
|
else:
|
||||||
await ctx.send(f"## {passage['reference']}\n{passage['content']}")
|
await ctx.send(f"## {passage['reference']}\n{passage['content']}")
|
||||||
|
|
||||||
|
@ -309,16 +286,14 @@ class Bible(commands.Cog):
|
||||||
return
|
return
|
||||||
|
|
||||||
if await ctx.embed_requested():
|
if await ctx.embed_requested():
|
||||||
icon = self.get_icon(await ctx.embed_color())
|
|
||||||
embed = Embed(
|
embed = Embed(
|
||||||
title=f"{passage['reference']}",
|
title=f"{passage['reference']}",
|
||||||
description=passage["content"].replace("¶ ", ""),
|
description=passage["content"].replace("¶ ", ""),
|
||||||
color=await ctx.embed_color(),
|
color=await self.bot.get_embed_color(ctx.channel),
|
||||||
)
|
)
|
||||||
embed.set_footer(
|
embed.set_footer(
|
||||||
text=f"{ctx.prefix}bible random - Powered by API.Bible - {version.abbreviationLocal} ({version.languageLocal}, {version.descriptionLocal})",
|
text=f"{ctx.prefix}bible random - Powered by API.Bible - {version.abbreviationLocal} ({version.languageLocal}, {version.descriptionLocal})"
|
||||||
icon_url="attachment://icon.png"
|
|
||||||
)
|
)
|
||||||
await ctx.send(embed=embed, file=icon)
|
await ctx.send(embed=embed)
|
||||||
else:
|
else:
|
||||||
await ctx.send(f"## {passage['reference']}\n{passage['content']}")
|
await ctx.send(f"## {passage['reference']}\n{passage['content']}")
|
||||||
|
|
Binary file not shown.
Before Width: | Height: | Size: 20 KiB |
|
@ -9,7 +9,6 @@
|
||||||
"disabled": false,
|
"disabled": false,
|
||||||
"min_bot_version": "3.5.0",
|
"min_bot_version": "3.5.0",
|
||||||
"min_python_version": [3, 10, 0],
|
"min_python_version": [3, 10, 0],
|
||||||
"requirements": ["numpy", "pillow"],
|
|
||||||
"tags": [
|
"tags": [
|
||||||
"fun",
|
"fun",
|
||||||
"utility",
|
"utility",
|
||||||
|
|
|
@ -1,5 +0,0 @@
|
||||||
from .emojiinfo import EmojiInfo
|
|
||||||
|
|
||||||
|
|
||||||
async def setup(bot):
|
|
||||||
await bot.add_cog(EmojiInfo(bot))
|
|
File diff suppressed because it is too large
Load diff
|
@ -1,129 +0,0 @@
|
||||||
import io
|
|
||||||
from typing import Any, Literal
|
|
||||||
|
|
||||||
import aiohttp
|
|
||||||
import discord
|
|
||||||
from colorthief import ColorThief
|
|
||||||
from red_commons.logging import RedTraceLogger, getLogger
|
|
||||||
from redbot.core import app_commands, commands
|
|
||||||
from redbot.core.bot import Red
|
|
||||||
from redbot.core.utils.chat_formatting import bold, humanize_list
|
|
||||||
|
|
||||||
from .model import PartialEmoji
|
|
||||||
|
|
||||||
|
|
||||||
class EmojiInfo(commands.Cog):
|
|
||||||
"""Retrieve information about emojis."""
|
|
||||||
|
|
||||||
__author__: list[str] = ["SeaswimmerTheFsh"]
|
|
||||||
__version__: str = "1.0.0"
|
|
||||||
__documentation__: str = "https://seacogs.coastalcommits.com/emojiinfo/"
|
|
||||||
|
|
||||||
def __init__(self, bot: Red) -> None:
|
|
||||||
super().__init__()
|
|
||||||
self.bot: Red = bot
|
|
||||||
self.logger: RedTraceLogger = getLogger(name="red.SeaCogs.Emoji")
|
|
||||||
|
|
||||||
def format_help_for_context(self, ctx: commands.Context) -> str:
|
|
||||||
pre_processed: Any | Literal[''] = super().format_help_for_context(ctx) or ""
|
|
||||||
n: Literal['\n'] | Literal[''] = "\n" if "\n\n" not in pre_processed else ""
|
|
||||||
text: list[str] = [
|
|
||||||
f"{pre_processed}{n}",
|
|
||||||
f"Cog Version: **{self.__version__}**",
|
|
||||||
f"Author: {humanize_list(items=self.__author__)}",
|
|
||||||
f"Documentation: {self.__documentation__}",
|
|
||||||
]
|
|
||||||
return "\n".join(text)
|
|
||||||
|
|
||||||
async def fetch_twemoji(self, unicode_emoji) -> str:
|
|
||||||
base_url = "https://cdn.jsdelivr.net/gh/jdecked/twemoji@latest/assets/72x72/"
|
|
||||||
emoji_codepoint = "-".join([hex(ord(char))[2:] for char in unicode_emoji])
|
|
||||||
segments = emoji_codepoint.split("-")
|
|
||||||
valid_segments = [seg for seg in segments if len(seg) >= 4]
|
|
||||||
emoji_url = f"{base_url}{valid_segments[0]}.png"
|
|
||||||
return emoji_url
|
|
||||||
|
|
||||||
async def fetch_primary_color(self, emoji_url: str) -> discord.Color | None:
|
|
||||||
async with aiohttp.ClientSession() as session:
|
|
||||||
async with session.get(emoji_url) as response:
|
|
||||||
if response.status != 200:
|
|
||||||
return None
|
|
||||||
image = await response.read()
|
|
||||||
dominant_color = ColorThief(io.BytesIO(image)).get_color(quality=1)
|
|
||||||
color = discord.Color.from_rgb(*dominant_color)
|
|
||||||
return color
|
|
||||||
|
|
||||||
async def get_emoji_info(self, emoji: PartialEmoji) -> tuple[str, str]:
|
|
||||||
if emoji.is_unicode_emoji():
|
|
||||||
try:
|
|
||||||
emoji_url = await self.fetch_twemoji(unicode_emoji=emoji.name)
|
|
||||||
except IndexError as e:
|
|
||||||
raise e
|
|
||||||
else:
|
|
||||||
emoji_url = emoji.url
|
|
||||||
|
|
||||||
if emoji.id is not None:
|
|
||||||
emoji_id = f"{bold('ID:')} `{emoji.id}`\n"
|
|
||||||
markdown = f"`<{'a' if emoji.animated else ''}:{emoji.name}:{emoji.id}>`"
|
|
||||||
name = f"{bold('Name:')} {emoji.name}\n"
|
|
||||||
aliases = ""
|
|
||||||
group = ""
|
|
||||||
else:
|
|
||||||
emoji_id = ""
|
|
||||||
markdown = f"`{emoji}`"
|
|
||||||
name = f"{bold('Name:')} {emoji.aliases.pop(0)}\n"
|
|
||||||
aliases = f"{bold('Aliases:')} {', '.join(emoji.aliases)}\n" if emoji.aliases else ""
|
|
||||||
group = f"{bold('Group:')} {emoji.group}\n"
|
|
||||||
|
|
||||||
return (
|
|
||||||
f"{name}"
|
|
||||||
f"{emoji_id}"
|
|
||||||
f"{bold('Native:')} {emoji.is_unicode_emoji()}\n"
|
|
||||||
f"{group}"
|
|
||||||
f"{aliases}"
|
|
||||||
f"{bold('Animated:')} {emoji.animated}\n"
|
|
||||||
f"{bold('Markdown:')} {markdown}\n"
|
|
||||||
f"{bold('URL:')} [Click Here]({emoji_url})"
|
|
||||||
), emoji_url
|
|
||||||
|
|
||||||
@app_commands.command(name="emoji")
|
|
||||||
@app_commands.describe(
|
|
||||||
emoji="What emoji would you like to get information on?",
|
|
||||||
ephemeral="Would you like the response to be hidden?"
|
|
||||||
)
|
|
||||||
async def emoji_slash(self, interaction: discord.Interaction, emoji: str, ephemeral: bool = True) -> None:
|
|
||||||
"""Retrieve information about an emoji."""
|
|
||||||
await interaction.response.defer(ephemeral=ephemeral)
|
|
||||||
|
|
||||||
try:
|
|
||||||
emoji: PartialEmoji = PartialEmoji.from_str(self, value=emoji)
|
|
||||||
string, emoji_url, = await self.get_emoji_info(emoji)
|
|
||||||
self.logger.verbose(f"Emoji:\n{string}")
|
|
||||||
except (IndexError, UnboundLocalError):
|
|
||||||
return await interaction.followup.send("Please provide a valid emoji!")
|
|
||||||
|
|
||||||
if await self.bot.embed_requested(channel=interaction.channel):
|
|
||||||
embed = embed = discord.Embed(title="Emoji Information", description=string, color = await self.fetch_primary_color(emoji_url) or await self.bot.get_embed_color(interaction.channel))
|
|
||||||
embed.set_thumbnail(url=emoji_url)
|
|
||||||
|
|
||||||
await interaction.followup.send(embed=embed)
|
|
||||||
else:
|
|
||||||
await interaction.followup.send(content=string)
|
|
||||||
|
|
||||||
@commands.command(name="emoji")
|
|
||||||
async def emoji(self, ctx: commands.Context, *, emoji: str) -> None:
|
|
||||||
"""Retrieve information about an emoji."""
|
|
||||||
try:
|
|
||||||
emoji: PartialEmoji = PartialEmoji.from_str(self, value=emoji)
|
|
||||||
string, emoji_url, = await self.get_emoji_info(emoji)
|
|
||||||
self.logger.verbose(f"Emoji:\n{string}")
|
|
||||||
except (IndexError, UnboundLocalError):
|
|
||||||
return await ctx.send("Please provide a valid emoji!")
|
|
||||||
|
|
||||||
if await ctx.embed_requested():
|
|
||||||
embed = embed = discord.Embed(title="Emoji Information", description=string, color = await self.fetch_primary_color(emoji_url) or await ctx.embed_color)
|
|
||||||
embed.set_thumbnail(url=emoji_url)
|
|
||||||
|
|
||||||
await ctx.send(embed=embed)
|
|
||||||
else:
|
|
||||||
await ctx.send(content=string)
|
|
|
@ -1,16 +0,0 @@
|
||||||
{
|
|
||||||
"author" : ["SeaswimmerTheFsh (seasw.)"],
|
|
||||||
"install_msg" : "Thank you for installing Emoji!",
|
|
||||||
"name" : "Emoji",
|
|
||||||
"short" : "Retrieve information about emojis.",
|
|
||||||
"description" : "Retrieve information about emojis.",
|
|
||||||
"end_user_data_statement" : "This cog does not store end user data.",
|
|
||||||
"hidden": false,
|
|
||||||
"disabled": false,
|
|
||||||
"min_bot_version": "3.5.0",
|
|
||||||
"min_python_version": [3, 10, 0],
|
|
||||||
"requirements": ["colorthief"],
|
|
||||||
"tags": [
|
|
||||||
"utility"
|
|
||||||
]
|
|
||||||
}
|
|
|
@ -1,91 +0,0 @@
|
||||||
import json
|
|
||||||
|
|
||||||
import discord
|
|
||||||
from redbot.core import commands, data_manager
|
|
||||||
|
|
||||||
|
|
||||||
class PartialEmoji(discord.PartialEmoji):
|
|
||||||
"""Represents a "partial" emoji. Subclasses `discord.PartialEmoji`
|
|
||||||
|
|
||||||
.. container:: operations
|
|
||||||
|
|
||||||
.. describe:: x == y
|
|
||||||
|
|
||||||
Checks if two emoji are the same.
|
|
||||||
|
|
||||||
.. describe:: x != y
|
|
||||||
|
|
||||||
Checks if two emoji are not the same.
|
|
||||||
|
|
||||||
.. describe:: hash(x)
|
|
||||||
|
|
||||||
Return the emoji's hash.
|
|
||||||
|
|
||||||
.. describe:: str(x)
|
|
||||||
|
|
||||||
Returns the emoji rendered for discord.
|
|
||||||
|
|
||||||
Attributes
|
|
||||||
-----------
|
|
||||||
name: Optional[:class:`str`]
|
|
||||||
The custom emoji name, if applicable, or the unicode codepoint
|
|
||||||
of the non-custom emoji. This can be ``None`` if the emoji
|
|
||||||
got deleted (e.g. removing a reaction with a deleted emoji).
|
|
||||||
animated: :class:`bool`
|
|
||||||
Whether the emoji is animated or not.
|
|
||||||
id: Optional[:class:`int`]
|
|
||||||
The ID of the custom emoji, if applicable.
|
|
||||||
group: Optional[:class:`str`]
|
|
||||||
The group name of the emoji if it is a native emoji.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, *, name: str, animated: bool = False, id: int | None = None, group: str | None = None, aliases: list | None = None) -> None: # pylint: disable=redefined-builtin
|
|
||||||
super().__init__(name=name, animated=animated, id=id)
|
|
||||||
self.group = group
|
|
||||||
self.aliases = aliases
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def from_str(cls, coginstance: commands.Cog, value: str) -> "PartialEmoji":
|
|
||||||
"""Converts a Discord string representation of an emoji to a :class:`PartialEmoji`.
|
|
||||||
|
|
||||||
The formats accepted are:
|
|
||||||
|
|
||||||
- ``a:name:id``
|
|
||||||
- ``<a:name:id>``
|
|
||||||
- ``name:id``
|
|
||||||
- ``<:name:id>``
|
|
||||||
|
|
||||||
If the format does not match then it is assumed to be a unicode emoji.
|
|
||||||
|
|
||||||
.. versionadded:: 2.0
|
|
||||||
|
|
||||||
Parameters
|
|
||||||
------------
|
|
||||||
value: :class:`str`
|
|
||||||
The string representation of an emoji.
|
|
||||||
|
|
||||||
Returns
|
|
||||||
--------
|
|
||||||
:class:`PartialEmoji`
|
|
||||||
The partial emoji from this string.
|
|
||||||
"""
|
|
||||||
match = cls._CUSTOM_EMOJI_RE.match(value)
|
|
||||||
if match is not None:
|
|
||||||
groups = match.groupdict()
|
|
||||||
animated = bool(groups['animated'])
|
|
||||||
emoji_id = int(groups['id'])
|
|
||||||
name = groups['name']
|
|
||||||
return cls(name=name, animated=animated, id=emoji_id)
|
|
||||||
|
|
||||||
path: data_manager.Path = data_manager.bundled_data_path(coginstance) / "emojis.json"
|
|
||||||
with open(path, "r", encoding="UTF-8") as file:
|
|
||||||
emojis: dict = json.load(file)
|
|
||||||
emoji_aliases = []
|
|
||||||
emoji_group = None
|
|
||||||
for dict_name, group in emojis.items():
|
|
||||||
for k, v in group.items():
|
|
||||||
if v == value:
|
|
||||||
emoji_group = dict_name
|
|
||||||
if k not in emoji_aliases:
|
|
||||||
emoji_aliases.append(k)
|
|
||||||
return cls(name=value, animated=False, id=None, group=emoji_group, aliases=emoji_aliases)
|
|
|
@ -3,7 +3,7 @@
|
||||||
"SeaswimmerTheFsh (seasw.)"
|
"SeaswimmerTheFsh (seasw.)"
|
||||||
],
|
],
|
||||||
"install_msg": "Thanks for installing my repo!\n\nIf you have any issues with any of the cogs, please create an issue [here](https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs/issues) or join my [Discord Server](https://discord.gg/eMUMe77Yb8 ).",
|
"install_msg": "Thanks for installing my repo!\n\nIf you have any issues with any of the cogs, please create an issue [here](https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs/issues) or join my [Discord Server](https://discord.gg/eMUMe77Yb8 ).",
|
||||||
"index_name": "sea-cogs",
|
"name": "SeaCogs",
|
||||||
"short": "Various cogs for Red, by SeaswimmerTheFsh (seasw.)",
|
"short": "Various cogs for Red, by SeaswimmerTheFsh (seasw.)",
|
||||||
"description": "Various cogs for Red, by SeaswimmerTheFsh (seasw.)"
|
"description": "Various cogs for Red, by SeaswimmerTheFsh (seasw.)"
|
||||||
}
|
}
|
||||||
|
|
|
@ -18,7 +18,6 @@ nav:
|
||||||
- Configuration: aurora/configuration.md
|
- Configuration: aurora/configuration.md
|
||||||
- Bible: bible.md
|
- Bible: bible.md
|
||||||
- Backup: backup.md
|
- Backup: backup.md
|
||||||
- EmojiInfo: emojiinfo.md
|
|
||||||
- Nerdify: nerdify.md
|
- Nerdify: nerdify.md
|
||||||
- Pterodactyl:
|
- Pterodactyl:
|
||||||
- pterodactyl/index.md
|
- pterodactyl/index.md
|
||||||
|
@ -30,7 +29,7 @@ nav:
|
||||||
plugins:
|
plugins:
|
||||||
- git-authors
|
- git-authors
|
||||||
- search
|
- search
|
||||||
#- social
|
- social
|
||||||
- git-revision-date-localized:
|
- git-revision-date-localized:
|
||||||
enable_creation_date: true
|
enable_creation_date: true
|
||||||
type: timeago
|
type: timeago
|
||||||
|
|
|
@ -18,8 +18,7 @@ class Nerdify(commands.Cog):
|
||||||
"""Nerdify your text."""
|
"""Nerdify your text."""
|
||||||
|
|
||||||
__author__ = ["SeaswimmerTheFsh"]
|
__author__ = ["SeaswimmerTheFsh"]
|
||||||
__version__ = "1.3.4"
|
__version__ = "1.3.3"
|
||||||
__documentation__ = "https://seacogs.coastalcommits.com/nerdify/"
|
|
||||||
|
|
||||||
def __init__(self, bot):
|
def __init__(self, bot):
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
|
@ -31,7 +30,6 @@ class Nerdify(commands.Cog):
|
||||||
f"{pre_processed}{n}",
|
f"{pre_processed}{n}",
|
||||||
f"Cog Version: **{self.__version__}**",
|
f"Cog Version: **{self.__version__}**",
|
||||||
f"Author: {chat_formatting.humanize_list(self.__author__)}",
|
f"Author: {chat_formatting.humanize_list(self.__author__)}",
|
||||||
f"Documentation: {self.__documentation__}"
|
|
||||||
]
|
]
|
||||||
return "\n".join(text)
|
return "\n".join(text)
|
||||||
|
|
||||||
|
|
2050
poetry.lock
generated
2050
poetry.lock
generated
File diff suppressed because it is too large
Load diff
|
@ -1,8 +1,8 @@
|
||||||
from red_commons import logging
|
from red_commons import logging
|
||||||
from red_commons.logging import getLogger
|
from red_commons.logging import getLogger
|
||||||
|
|
||||||
logger = getLogger('red.SeaCogs.Pterodactyl')
|
logger = getLogger('red.seacogs.pterodactyl')
|
||||||
websocket_logger = getLogger('red.SeaCogs.Pterodactyl.websocket')
|
websocket_logger = getLogger('red.seacogs.pterodactyl.websocket')
|
||||||
if logger.level >= logging.VERBOSE:
|
if logger.level >= logging.VERBOSE:
|
||||||
websocket_logger.setLevel(logging.logging.INFO)
|
websocket_logger.setLevel(logging.logging.INFO)
|
||||||
elif logger.level < logging.VERBOSE:
|
elif logger.level < logging.VERBOSE:
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
import aiohttp
|
import aiohttp
|
||||||
|
|
||||||
|
|
||||||
async def get_status(host: str, port: int = 25565) -> tuple[bool, dict]:
|
async def get_status(host, port = 25565) -> tuple[bool, dict]:
|
||||||
async with aiohttp.ClientSession() as session:
|
async with aiohttp.ClientSession() as session:
|
||||||
async with session.get(f'https://api.mcsrvstat.us/2/{host}:{port}') as response:
|
async with session.get(f'https://api.mcsrvstat.us/2/{host}:{port}') as response:
|
||||||
response = await response.json()
|
response = await response.json()
|
||||||
|
|
|
@ -9,7 +9,7 @@ from pydactyl import PterodactylClient
|
||||||
from redbot.core import app_commands, commands
|
from redbot.core import app_commands, commands
|
||||||
from redbot.core.app_commands import Choice
|
from redbot.core.app_commands import Choice
|
||||||
from redbot.core.bot import Red
|
from redbot.core.bot import Red
|
||||||
from redbot.core.utils.chat_formatting import box, error, humanize_list
|
from redbot.core.utils.chat_formatting import box, error
|
||||||
from redbot.core.utils.views import ConfirmView
|
from redbot.core.utils.views import ConfirmView
|
||||||
|
|
||||||
from pterodactyl import mcsrvstatus
|
from pterodactyl import mcsrvstatus
|
||||||
|
@ -20,10 +20,6 @@ from pterodactyl.logger import logger
|
||||||
class Pterodactyl(commands.Cog):
|
class Pterodactyl(commands.Cog):
|
||||||
"""Pterodactyl allows you to manage your Pterodactyl Panel from Discord."""
|
"""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):
|
def __init__(self, bot: Red):
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
self.client: Optional[PterodactylClient] = None
|
self.client: Optional[PterodactylClient] = None
|
||||||
|
@ -34,17 +30,6 @@ class Pterodactyl(commands.Cog):
|
||||||
self.task = self.get_task()
|
self.task = self.get_task()
|
||||||
self.update_topic.start()
|
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:
|
async def cog_unload(self) -> None:
|
||||||
self.update_topic.cancel()
|
self.update_topic.cancel()
|
||||||
self.task.cancel()
|
self.task.cancel()
|
||||||
|
@ -74,7 +59,6 @@ class Pterodactyl(commands.Cog):
|
||||||
|
|
||||||
@tasks.loop(minutes=6)
|
@tasks.loop(minutes=6)
|
||||||
async def update_topic(self):
|
async def update_topic(self):
|
||||||
await self.bot.wait_until_red_ready()
|
|
||||||
topic = await self.get_topic()
|
topic = await self.get_topic()
|
||||||
console = self.bot.get_channel(await config.console_channel())
|
console = self.bot.get_channel(await config.console_channel())
|
||||||
chat = self.bot.get_channel(await config.chat_channel())
|
chat = self.bot.get_channel(await config.chat_channel())
|
||||||
|
@ -148,7 +132,7 @@ class Pterodactyl(commands.Cog):
|
||||||
"C": str(message.author.color),
|
"C": str(message.author.color),
|
||||||
"D": message.author.discriminator,
|
"D": message.author.discriminator,
|
||||||
"I": str(message.author.id),
|
"I": str(message.author.id),
|
||||||
"M": message.content.replace('"','').replace("\n", " "),
|
"M": message.content.replace('"',''),
|
||||||
"N": message.author.display_name,
|
"N": message.author.display_name,
|
||||||
"U": message.author.name,
|
"U": message.author.name,
|
||||||
"V": await config.invite() or "use [p]pterodactyl config invite to change me",
|
"V": await config.invite() or "use [p]pterodactyl config invite to change me",
|
||||||
|
@ -161,7 +145,9 @@ class Pterodactyl(commands.Cog):
|
||||||
if await config.api_endpoint() == "minecraft":
|
if await config.api_endpoint() == "minecraft":
|
||||||
status, response = await mcsrvstatus.get_status(await config.topic_hostname(), await config.topic_port())
|
status, response = await mcsrvstatus.get_status(await config.topic_hostname(), await config.topic_port())
|
||||||
if status and 'list' in response['players']:
|
if status and 'list' in response['players']:
|
||||||
output_str = '\n'.join(response['players']['list'])
|
output_str = ''
|
||||||
|
for player in response['players']['list']:
|
||||||
|
output_str += f"{player}\n"
|
||||||
return output_str, response['players']['list']
|
return output_str, response['players']['list']
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
@ -545,7 +531,7 @@ class Pterodactyl(commands.Cog):
|
||||||
await view.wait()
|
await view.wait()
|
||||||
if view.result is True:
|
if view.result is True:
|
||||||
blacklist.update({name: regex})
|
blacklist.update({name: regex})
|
||||||
await msg.edit(content=f"Updated `{name}` in the regex blacklist.\n{box(regex, 're')}")
|
await msg.edit(f"Updated `{name}` in the regex blacklist.\n{box(regex, 're')}")
|
||||||
else:
|
else:
|
||||||
await msg.edit(content="Cancelled.")
|
await msg.edit(content="Cancelled.")
|
||||||
|
|
||||||
|
@ -560,7 +546,7 @@ class Pterodactyl(commands.Cog):
|
||||||
await view.wait()
|
await view.wait()
|
||||||
if view.result is True:
|
if view.result is True:
|
||||||
del blacklist[name]
|
del blacklist[name]
|
||||||
await msg.edit(content=f"Removed `{name}` from the regex blacklist.")
|
await msg.edit(content="Removed `{name}` from the regex blacklist.")
|
||||||
else:
|
else:
|
||||||
await msg.edit(content="Cancelled.")
|
await msg.edit(content="Cancelled.")
|
||||||
else:
|
else:
|
||||||
|
|
|
@ -15,7 +15,6 @@ from pterodactyl.pterodactyl import Pterodactyl
|
||||||
|
|
||||||
|
|
||||||
async def establish_websocket_connection(coginstance: Pterodactyl) -> None:
|
async def establish_websocket_connection(coginstance: Pterodactyl) -> None:
|
||||||
await coginstance.bot.wait_until_red_ready()
|
|
||||||
base_url = await config.base_url()
|
base_url = await config.base_url()
|
||||||
base_url = base_url[:-1] if base_url.endswith('/') else base_url
|
base_url = base_url[:-1] if base_url.endswith('/') else base_url
|
||||||
|
|
||||||
|
|
|
@ -5,18 +5,12 @@ description = "My assorted cogs for Red-DiscordBot."
|
||||||
authors = ["SeaswimmerTheFsh"]
|
authors = ["SeaswimmerTheFsh"]
|
||||||
license = "MPL 2"
|
license = "MPL 2"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
package-mode = false
|
|
||||||
|
|
||||||
[tool.poetry.dependencies]
|
[tool.poetry.dependencies]
|
||||||
python = ">=3.11,<3.12"
|
python = ">=3.11,<3.12"
|
||||||
Red-DiscordBot = "^3.5.5"
|
Red-DiscordBot = "^3.5.5"
|
||||||
py-dactyl = "^2.0.4"
|
py-dactyl = "^2.0.4"
|
||||||
websockets = "^12.0"
|
websockets = "^12.0"
|
||||||
pillow = "^10.3.0"
|
|
||||||
numpy = "^1.26.4"
|
|
||||||
colorthief = "^0.2.1"
|
|
||||||
beautifulsoup4 = "^4.12.3"
|
|
||||||
markdownify = "^0.12.1"
|
|
||||||
|
|
||||||
[tool.poetry.group.dev]
|
[tool.poetry.group.dev]
|
||||||
optional = true
|
optional = true
|
||||||
|
|
|
@ -1,5 +0,0 @@
|
||||||
from .seautils import SeaUtils
|
|
||||||
|
|
||||||
|
|
||||||
async def setup(bot):
|
|
||||||
await bot.add_cog(SeaUtils(bot))
|
|
|
@ -1,13 +0,0 @@
|
||||||
{
|
|
||||||
"author" : ["SeaswimmerTheFsh (seasw.)"],
|
|
||||||
"install_msg" : "Thank you for installing SeaUtils!\nYou can find the source code of this cog [here](https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs).",
|
|
||||||
"name" : "SeaUtils",
|
|
||||||
"short" : "A collection of useful utilities.",
|
|
||||||
"description" : "A collection of useful utilities.",
|
|
||||||
"end_user_data_statement" : "This cog does not store end user data.",
|
|
||||||
"hidden": true,
|
|
||||||
"disabled": false,
|
|
||||||
"min_bot_version": "3.5.0",
|
|
||||||
"min_python_version": [3, 8, 0],
|
|
||||||
"requirements": ["beautifulsoup4", "markdownify"]
|
|
||||||
}
|
|
|
@ -1,250 +0,0 @@
|
||||||
# _____ _
|
|
||||||
# / ____| (_)
|
|
||||||
# | (___ ___ __ _ _____ ___ _ __ ___ _ __ ___ ___ _ __
|
|
||||||
# \___ \ / _ \/ _` / __\ \ /\ / / | '_ ` _ \| '_ ` _ \ / _ \ '__|
|
|
||||||
# ____) | __/ (_| \__ \\ V V /| | | | | | | | | | | | __/ |
|
|
||||||
# |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_|
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import inspect
|
|
||||||
import operator
|
|
||||||
import re
|
|
||||||
from asyncio.subprocess import Process
|
|
||||||
from functools import partial, partialmethod
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
import aiohttp
|
|
||||||
import yaml
|
|
||||||
from bs4 import BeautifulSoup
|
|
||||||
from discord import Color, Embed, app_commands
|
|
||||||
from discord.utils import CachedSlotProperty, cached_property
|
|
||||||
from markdownify import MarkdownConverter
|
|
||||||
from redbot.core import commands
|
|
||||||
from redbot.core.bot import Red
|
|
||||||
from redbot.core.dev_commands import cleanup_code
|
|
||||||
from redbot.core.utils import chat_formatting as cf
|
|
||||||
from redbot.core.utils.views import SimpleMenu
|
|
||||||
|
|
||||||
|
|
||||||
def md(soup: BeautifulSoup, **options) -> Any | str:
|
|
||||||
return MarkdownConverter(**options).convert_soup(soup=soup)
|
|
||||||
|
|
||||||
def format_rfc_text(text: str, number: int) -> str:
|
|
||||||
one: str = re.sub(r"\(\.\/rfc(\d+)", r"(https://www.rfc-editor.org/rfc/rfc\1.html", text)
|
|
||||||
two: str = re.sub(r"\((#(?:section|page)-\d+(?:.\d+)?)\)", f"(https://www.rfc-editor.org/rfc/rfc{number}.html\1)", one)
|
|
||||||
three: str = re.sub(r"\n{3,}", "\n\n", two)
|
|
||||||
return three
|
|
||||||
|
|
||||||
class SeaUtils(commands.Cog):
|
|
||||||
"""A collection of random utilities."""
|
|
||||||
|
|
||||||
__author__ = ["SeaswimmerTheFsh"]
|
|
||||||
__version__ = "1.0.0"
|
|
||||||
|
|
||||||
def __init__(self, bot: Red) -> None:
|
|
||||||
self.bot = bot
|
|
||||||
|
|
||||||
def format_help_for_context(self, ctx: commands.Context) -> str:
|
|
||||||
pre_processed = super().format_help_for_context(ctx=ctx) or ""
|
|
||||||
n = "\n" if "\n\n" not in pre_processed else ""
|
|
||||||
text = [
|
|
||||||
f"{pre_processed}{n}",
|
|
||||||
f"Cog Version: **{self.__version__}**",
|
|
||||||
f"Author: {cf.humanize_list(items=self.__author__)}"
|
|
||||||
]
|
|
||||||
return "\n".join(text)
|
|
||||||
|
|
||||||
def format_src(self, obj: Any) -> str:
|
|
||||||
"""A large portion of this code is repurposed from Zephyrkul's RTFS cog.
|
|
||||||
https://github.com/Zephyrkul/FluffyCogs/blob/master/rtfs/rtfs.py"""
|
|
||||||
obj = inspect.unwrap(func=obj)
|
|
||||||
src: Any = getattr(obj, "__func__", obj)
|
|
||||||
if isinstance(obj, (commands.Command, app_commands.Command)):
|
|
||||||
src = obj.callback
|
|
||||||
elif isinstance(obj, (partial, partialmethod)):
|
|
||||||
src = obj.func
|
|
||||||
elif isinstance(obj, property):
|
|
||||||
src = obj.fget
|
|
||||||
elif isinstance(obj, (cached_property, CachedSlotProperty)):
|
|
||||||
src = obj.function
|
|
||||||
return inspect.getsource(object=src)
|
|
||||||
|
|
||||||
@commands.command(aliases=["source", "src", "code", "showsource"])
|
|
||||||
@commands.is_owner()
|
|
||||||
async def showcode(self, ctx: commands.Context, *, object: str) -> None: # pylint: disable=redefined-builtin
|
|
||||||
"""Show the code for a particular object."""
|
|
||||||
try:
|
|
||||||
if object.startswith("/") and (obj := ctx.bot.tree.get_command(object[1:])):
|
|
||||||
text = self.format_src(obj)
|
|
||||||
elif obj := ctx.bot.get_cog(object):
|
|
||||||
text = self.format_src(type(obj))
|
|
||||||
elif obj := ctx.bot.get_command(object):
|
|
||||||
text = self.format_src(obj)
|
|
||||||
else:
|
|
||||||
raise AttributeError
|
|
||||||
temp_content = cf.pagify(
|
|
||||||
text=cleanup_code(text),
|
|
||||||
escape_mass_mentions=True,
|
|
||||||
page_length = 1977
|
|
||||||
)
|
|
||||||
content = []
|
|
||||||
max_i = operator.length_hint(temp_content)
|
|
||||||
i = 1
|
|
||||||
for page in temp_content:
|
|
||||||
content.append(f"**Page {i}/{max_i}**\n{cf.box(page, lang='py')}")
|
|
||||||
i += 1
|
|
||||||
await SimpleMenu(pages=content, disable_after_timeout=True, timeout=180).start(ctx)
|
|
||||||
except (OSError, AttributeError, UnboundLocalError):
|
|
||||||
if ctx.embed_requested():
|
|
||||||
embed = Embed(title="Object not found!", color=await ctx.embed_color())
|
|
||||||
await ctx.send(embed=embed, reference=ctx.message.to_reference(fail_if_not_exists=False))
|
|
||||||
else:
|
|
||||||
await ctx.send(content="Object not found!", reference=ctx.message.to_reference(fail_if_not_exists=False))
|
|
||||||
|
|
||||||
@commands.command(name='dig', aliases=['dnslookup', 'nslookup'])
|
|
||||||
@commands.is_owner()
|
|
||||||
async def dig(self, ctx: commands.Context, name: str, record_type: str | None = None, server: str | None = None, port: int = 53) -> None:
|
|
||||||
"""Retrieve DNS information for a domain.
|
|
||||||
|
|
||||||
Uses `dig` to perform a DNS query. Will fall back to `nslookup` if `dig` is not installed on the system.
|
|
||||||
`nslookup` does not provide as much information as `dig`, so only the `name` parameter will be used if `nslookup` is used.
|
|
||||||
Will return the A, AAAA, and CNAME records for a domain by default. You can specify a different record type with the `type` parameter."""
|
|
||||||
command_opts: list[str | int] = ['dig']
|
|
||||||
query_types: list[str] = [record_type] if record_type else ['A', 'AAAA', 'CNAME']
|
|
||||||
if server:
|
|
||||||
command_opts.extend(['@', server])
|
|
||||||
for query_type in query_types:
|
|
||||||
command_opts.extend([name, query_type])
|
|
||||||
command_opts.extend(['-p', str(port), '+yaml'])
|
|
||||||
|
|
||||||
try:
|
|
||||||
process: Process = await asyncio.create_subprocess_exec(*command_opts, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
|
|
||||||
stdout, stderr = await process.communicate()
|
|
||||||
if stderr:
|
|
||||||
await ctx.maybe_send_embed(message="An error was encountered!\n" + cf.box(text=stderr.decode()))
|
|
||||||
else:
|
|
||||||
data = yaml.safe_load(stdout.decode())
|
|
||||||
message_data: dict = data[0]['message']
|
|
||||||
response_data: dict = message_data['response_message_data']
|
|
||||||
if ctx.embed_requested():
|
|
||||||
embed = Embed(
|
|
||||||
title="DNS Query Result",
|
|
||||||
color=await ctx.embed_color(),
|
|
||||||
timestamp=message_data['response_time']
|
|
||||||
)
|
|
||||||
embed.add_field(name="Response Address", value=message_data['response_address'], inline=True)
|
|
||||||
embed.add_field(name="Response Port", value=message_data['response_port'], inline=True)
|
|
||||||
embed.add_field(name="Query Address", value=message_data['query_address'], inline=True)
|
|
||||||
embed.add_field(name="Query Port", value=message_data['query_port'], inline=True)
|
|
||||||
embed.add_field(name="Status", value=response_data['status'], inline=True)
|
|
||||||
embed.add_field(name="Flags", value=response_data['flags'], inline=True)
|
|
||||||
|
|
||||||
if response_data.get('status') != 'NOERROR':
|
|
||||||
embed.colour = Color.red()
|
|
||||||
embed.description = cf.error("Dig query did not return `NOERROR` status.")
|
|
||||||
|
|
||||||
questions = []
|
|
||||||
answers = []
|
|
||||||
authorities = []
|
|
||||||
for m in data:
|
|
||||||
response = m['message']['response_message_data']
|
|
||||||
if 'QUESTION_SECTION' in response:
|
|
||||||
for question in response['QUESTION_SECTION']:
|
|
||||||
if question not in questions:
|
|
||||||
questions.append(question)
|
|
||||||
|
|
||||||
if 'ANSWER_SECTION' in response:
|
|
||||||
for answer in response['ANSWER_SECTION']:
|
|
||||||
if answer not in answers:
|
|
||||||
answers.append(answer)
|
|
||||||
|
|
||||||
if 'AUTHORITY_SECTION' in response:
|
|
||||||
for authority in response['AUTHORITY_SECTION']:
|
|
||||||
if authority not in authorities:
|
|
||||||
authorities.append(authority)
|
|
||||||
|
|
||||||
if questions:
|
|
||||||
question_section = "\n".join(questions)
|
|
||||||
embed.add_field(name="Question Section", value=f"{cf.box(text=question_section, lang='prolog')}", inline=False)
|
|
||||||
|
|
||||||
if answers:
|
|
||||||
answer_section = "\n".join(answers)
|
|
||||||
if len(answer_section) > 1024:
|
|
||||||
embed.description = cf.warning("Answer section is too long to fit within embed field, falling back to description.") + cf.box(answer_section)
|
|
||||||
else:
|
|
||||||
embed.add_field(name="Answer Section", value=f"{cf.box(text=answer_section, lang='prolog')}", inline=False)
|
|
||||||
|
|
||||||
if authorities:
|
|
||||||
authority_section = "\n".join(authorities)
|
|
||||||
embed.add_field(name="Authority Section", value=f"{cf.box(text=authority_section, lang='prolog')}", inline=False)
|
|
||||||
await ctx.send(embed=embed)
|
|
||||||
else:
|
|
||||||
await ctx.send(content=cf.box(text=stdout, lang='yaml'))
|
|
||||||
except (FileNotFoundError):
|
|
||||||
try:
|
|
||||||
ns_process = await asyncio.create_subprocess_exec('nslookup', name, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
|
|
||||||
ns_stdout, ns_stderr = await ns_process.communicate()
|
|
||||||
if ns_stderr:
|
|
||||||
await ctx.maybe_send_embed(message="An error was encountered!\n" + cf.box(text=ns_stderr.decode()))
|
|
||||||
else:
|
|
||||||
warning = cf.warning("`dig` is not installed! Defaulting to `nslookup`.\nThis command provides more information when `dig` is installed on the system.\n")
|
|
||||||
if await ctx.embed_requested():
|
|
||||||
embed = Embed(
|
|
||||||
title="DNS Query Result",
|
|
||||||
color=await ctx.embed_color(),
|
|
||||||
timestamp=ctx.message.created_at
|
|
||||||
)
|
|
||||||
embed.description = warning + cf.box(text=ns_stdout.decode())
|
|
||||||
await ctx.send(embed=embed)
|
|
||||||
else:
|
|
||||||
await ctx.send(content = warning + cf.box(text=ns_stdout.decode()))
|
|
||||||
except (FileNotFoundError):
|
|
||||||
await ctx.maybe_send_embed(message=cf.error("Neither `dig` nor `nslookup` are installed on the system. Unable to resolve DNS query."))
|
|
||||||
|
|
||||||
@commands.command()
|
|
||||||
async def rfc(self, ctx: commands.Context, number: int) -> None:
|
|
||||||
"""Retrieve the text of an RFC document.
|
|
||||||
|
|
||||||
This command uses the [RFC Editor website](https://www.rfc-editor.org/) to fetch the text of an RFC document.
|
|
||||||
A [Request for Comments (RFC)](https://en.wikipedia.org/wiki/Request_for_Comments) is a publication in a series from the principal technical development and standards-setting bodies for the [Internet](https://en.wikipedia.org/wiki/Internet), most prominently the [Internet Engineering Task Force](https://en.wikipedia.org/wiki/Internet_Engineering_Task_Force). An RFC is authored by individuals or groups of engineers and [computer scientists](https://en.wikipedia.org/wiki/Computer_scientist) in the form of a [memorandum](https://en.wikipedia.org/wiki/Memorandum) describing methods, behaviors, research, or innovations applicable to the working of the Internet and Internet-connected systems. It is submitted either for [peer review](https://en.wikipedia.org/wiki/Peer_review) or to convey new concepts, information, or, occasionally, engineering humor.""" # noqa: E501
|
|
||||||
url = f"https://www.rfc-editor.org/rfc/rfc{number}.html"
|
|
||||||
datatracker_url = f"https://datatracker.ietf.org/doc/rfc{number}"
|
|
||||||
async with aiohttp.ClientSession() as session:
|
|
||||||
async with session.get(url=url) as response:
|
|
||||||
if response.status == 200:
|
|
||||||
html = await response.text()
|
|
||||||
soup = BeautifulSoup(html, 'html.parser')
|
|
||||||
pre_tags = soup.find_all('pre')
|
|
||||||
content: list[Embed | str] = []
|
|
||||||
for pre_tag in pre_tags:
|
|
||||||
text = format_rfc_text(md(pre_tag), number)
|
|
||||||
if len(text) > 4096:
|
|
||||||
pagified_text = cf.pagify(text, delims=["\n\n"], page_length=4096)
|
|
||||||
for page in pagified_text:
|
|
||||||
if await ctx.embed_requested():
|
|
||||||
embed = Embed(
|
|
||||||
title=f"RFC Document {number}",
|
|
||||||
url=datatracker_url,
|
|
||||||
description=page,
|
|
||||||
color=await ctx.embed_color()
|
|
||||||
)
|
|
||||||
content.append(embed)
|
|
||||||
else:
|
|
||||||
content.append(page)
|
|
||||||
else:
|
|
||||||
if await ctx.embed_requested():
|
|
||||||
embed = Embed(
|
|
||||||
title=f"RFC Document {number}",
|
|
||||||
url=datatracker_url,
|
|
||||||
description=text,
|
|
||||||
color=await ctx.embed_color()
|
|
||||||
)
|
|
||||||
content.append(embed)
|
|
||||||
else:
|
|
||||||
content.append(text)
|
|
||||||
if await ctx.embed_requested():
|
|
||||||
for embed in content:
|
|
||||||
embed.set_footer(text=f"Page {content.index(embed) + 1}/{len(content)}")
|
|
||||||
await SimpleMenu(pages=content, disable_after_timeout=True, timeout=300).start(ctx)
|
|
||||||
else:
|
|
||||||
await ctx.maybe_send_embed(content=cf.error(f"An error occurred while fetching RFC {number}. Status code: {response.status}."))
|
|
5
welcomer/__init__.py
Normal file
5
welcomer/__init__.py
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
from .welcomer import Welcomer
|
||||||
|
|
||||||
|
|
||||||
|
async def setup(bot):
|
||||||
|
await bot.add_cog(Welcomer(bot))
|
17
welcomer/info.json
Normal file
17
welcomer/info.json
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
{
|
||||||
|
"author" : ["SeaswimmerTheFsh (seasw.)"],
|
||||||
|
"install_msg" : "Thank you for installing Nerdify!\nYou can find the source code of this cog [here](https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs). Based off of PhasecoreX's [UwU](<https://github.com/PhasecoreX/PCXCogs/tree/master/uwu>) cog.",
|
||||||
|
"name" : "Nerdify",
|
||||||
|
"short" : "Nerdify your text!",
|
||||||
|
"description" : "Nerdify your text!",
|
||||||
|
"end_user_data_statement" : "This cog does not store end user data.",
|
||||||
|
"hidden": false,
|
||||||
|
"disabled": false,
|
||||||
|
"min_bot_version": "3.5.0",
|
||||||
|
"min_python_version": [3, 8, 0],
|
||||||
|
"tags": [
|
||||||
|
"fun",
|
||||||
|
"text",
|
||||||
|
"meme"
|
||||||
|
]
|
||||||
|
}
|
39
welcomer/welcomer.py
Normal file
39
welcomer/welcomer.py
Normal file
|
@ -0,0 +1,39 @@
|
||||||
|
# _____ _
|
||||||
|
# / ____| (_)
|
||||||
|
# | (___ ___ __ _ _____ ___ _ __ ___ _ __ ___ ___ _ __
|
||||||
|
# \___ \ / _ \/ _` / __\ \ /\ / / | '_ ` _ \| '_ ` _ \ / _ \ '__|
|
||||||
|
# ____) | __/ (_| \__ \\ V V /| | | | | | | | | | | | __/ |
|
||||||
|
# |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_|
|
||||||
|
|
||||||
|
|
||||||
|
from redbot.core import commands, Config
|
||||||
|
from redbot.core.utils import chat_formatting as cf
|
||||||
|
|
||||||
|
|
||||||
|
class Welcomer(commands.Cog):
|
||||||
|
"""Manage welcome messages for new members and leave messages for former members."""
|
||||||
|
|
||||||
|
__author__ = ["SeaswimmerTheFsh"]
|
||||||
|
__version__ = "0.1.0"
|
||||||
|
|
||||||
|
def __init__(self, bot):
|
||||||
|
self.bot = bot
|
||||||
|
self.config = Config.get_conf(self, identifier=1234567890, force_registration=True)
|
||||||
|
self.config.register_guild(
|
||||||
|
welcome_message=None,
|
||||||
|
leave_message=None,
|
||||||
|
channel=None,
|
||||||
|
enabled=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
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: {cf.humanize_list(self.__author__)}",
|
||||||
|
]
|
||||||
|
return "\n".join(text)
|
||||||
|
|
||||||
|
def placeholders(self, )
|
Loading…
Reference in a new issue