Compare commits
103 commits
Author | SHA1 | Date | |
---|---|---|---|
d173dd68a5 | |||
24239425c5 | |||
e3e96e5b84 | |||
28f814db56 | |||
7354769962 | |||
2ac1dacd19 | |||
66b933569b | |||
c06db07f08 | |||
46f189a297 | |||
545106d496 | |||
037a26deb0 | |||
f51329524c | |||
5b23f2f0fb | |||
8f492cd937 | |||
dfabac55f5 | |||
4f25e3d0f3 | |||
7207cd3747 | |||
069ea800db | |||
58245c621c | |||
b9f0dbf98a | |||
2d895d16c9 | |||
861a03719b | |||
ac5d4df36b | |||
ae8d0d5db4 | |||
0ea80075f6 | |||
8d3f5c1d5f | |||
42e209b547 | |||
0ed96babdb | |||
29b6a2141a | |||
c4ef2a7d4b | |||
99cd13ccf1 | |||
28246121a6 | |||
a641cae640 | |||
2886d5e80d | |||
50094b85fc | |||
7f46d6accc | |||
cb6ddabb4d | |||
8608e6a34e | |||
fb468ee63e | |||
b27a3ee778 | |||
54491cb9c9 | |||
29bb64b35c | |||
5ffc42480a | |||
7d51814a28 | |||
25fdf7b402 | |||
091f4fe36d | |||
d444242245 | |||
7a2ee0a655 | |||
8b68cb7530 | |||
028cae9e99 | |||
aa7e347a95 | |||
93f358cfad | |||
8867cc627f | |||
e2059eac77 | |||
e9c062afa9 | |||
ee9b62db5b | |||
1405dae49e | |||
7ed836a1cd | |||
d95c9b3255 | |||
c9a47603a7 | |||
d8758cfb1d | |||
3fd91d9776 | |||
d556ee3704 | |||
7019b9ffe5 | |||
5116598788 | |||
2dcbcb0a59 | |||
059badaa9b | |||
84d2728d3a | |||
bb1aca83dd | |||
59848fe857 | |||
516c0feecc | |||
7bd9531b58 | |||
09ab8aa69d | |||
fb34593707 | |||
ebdd3e3525 | |||
e1bfa79cb9 | |||
e59503829f | |||
d126f1e6d3 | |||
66df7664a5 | |||
ce53908938 | |||
8f6afe754d | |||
aa6e0d7590 | |||
d65d04fa7a | |||
bc9bc53967 | |||
2b5a00f512 | |||
4bf3e85df2 | |||
ce595e50da | |||
9ed16a44f2 | |||
59097b676d | |||
537b2edafa | |||
8ebb383a84 | |||
1ed1eb2681 | |||
a02a7ab3d7 | |||
80dcfea95e | |||
7ae8226ca5 | |||
b910d8c614 | |||
d87c37239d | |||
c266997a78 | |||
20c3007306 | |||
8fdf587bde | |||
ea1f7a7f8e | |||
384ce7fc6d | |||
c618f9be72 |
24 changed files with 6054 additions and 1416 deletions
19
.docs/emojiinfo.md
Normal file
19
.docs/emojiinfo.md
Normal file
|
@ -0,0 +1,19 @@
|
|||
# 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.
|
|
@ -18,4 +18,5 @@
|
|||
import-self,
|
||||
relative-beyond-top-level,
|
||||
too-many-instance-attributes,
|
||||
duplicate-code
|
||||
duplicate-code,
|
||||
too-many-nested-blocks
|
||||
|
|
|
@ -58,7 +58,7 @@ jobs:
|
|||
npx -p "@getmeli/cli" meli upload ./site \
|
||||
--url "https://pages.coastalcommits.com" \
|
||||
--site "${{ vars.MELI_SITE_ID }}" \
|
||||
--token "${{ secrets.MELI_SITE_SECRET }}" \
|
||||
--token "${{ secrets.MELI_SECRET }}" \
|
||||
--release "$CI_ACTION_REF_NAME_SLUG/${{ env.GITHUB_SHA }}" \
|
||||
--branch "$CI_ACTION_REF_NAME_SLUG"
|
||||
|
||||
|
|
|
@ -19,8 +19,7 @@ from redbot.core import app_commands, commands, data_manager
|
|||
from redbot.core.app_commands import Choice
|
||||
from redbot.core.bot import Red
|
||||
from redbot.core.commands.converter import parse_relativedelta, parse_timedelta
|
||||
from redbot.core.utils.chat_formatting import (box, error, humanize_list,
|
||||
humanize_timedelta, warning)
|
||||
from redbot.core.utils.chat_formatting import box, error, humanize_list, humanize_timedelta, warning
|
||||
|
||||
from aurora.importers.aurora import ImportAuroraView
|
||||
from aurora.importers.galacticbot import ImportGalacticBotView
|
||||
|
@ -29,19 +28,10 @@ from aurora.menus.guild import Guild
|
|||
from aurora.menus.immune import Immune
|
||||
from aurora.menus.overrides import Overrides
|
||||
from aurora.utilities.config import config, register_config
|
||||
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.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.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, get_footer_image, log, send_evidenceformat, timedelta_from_relativedelta
|
||||
|
||||
|
||||
class Aurora(commands.Cog):
|
||||
|
@ -50,7 +40,7 @@ class Aurora(commands.Cog):
|
|||
This cog stores all of its data in an SQLite database."""
|
||||
|
||||
__author__ = ["SeaswimmerTheFsh"]
|
||||
__version__ = "2.1.2"
|
||||
__version__ = "2.1.3"
|
||||
__documentation__ = "https://seacogs.coastalcommits.com/aurora/"
|
||||
|
||||
async def red_delete_data_for_user(self, *, requester, user_id: int):
|
||||
|
|
|
@ -43,7 +43,7 @@ class ImportAuroraView(ui.View):
|
|||
file = await self.ctx.message.attachments[0].read()
|
||||
data: list[dict] = sorted(json.loads(file), key=lambda x: x["moderation_id"])
|
||||
|
||||
user_mod_types = ["NOTE", "WARN", "MUTE", "UNMUTE", "KICK", "BAN", "UNBAN"]
|
||||
user_mod_types = ["NOTE", "WARN", "ADDROLE", "REMOVEROLE", "MUTE", "UNMUTE", "KICK", "TEMPBAN", "BAN", "UNBAN"]
|
||||
|
||||
channel_mod_types = ["SLOWMODE", "LOCKDOWN"]
|
||||
|
||||
|
@ -58,6 +58,8 @@ class ImportAuroraView(ui.View):
|
|||
case["target_type"] = "USER"
|
||||
elif case["moderation_type"] in channel_mod_types:
|
||||
case["target_type"] = "CHANNEL"
|
||||
else:
|
||||
case["target_type"] = "USER"
|
||||
|
||||
if "role_id" not in case or not case["role_id"]:
|
||||
case["role_id"] = 0
|
||||
|
|
|
@ -381,6 +381,10 @@ 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']})"
|
||||
|
||||
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":
|
||||
hours, minutes, seconds = map(int, case_dict["duration"].split(":"))
|
||||
td = timedelta(hours=hours, minutes=minutes, seconds=seconds)
|
||||
|
|
|
@ -100,7 +100,7 @@ class Backup(commands.Cog):
|
|||
except (json.JSONDecodeError, IndexError):
|
||||
try:
|
||||
export = json.loads(await ctx.message.reference.resolved.attachments[0].read())
|
||||
except (json.JSONDecodeError, IndexError):
|
||||
except (json.JSONDecodeError, IndexError, AttributeError):
|
||||
await ctx.send(error("Please provide a valid JSON export file."))
|
||||
return
|
||||
|
||||
|
|
5
emojiinfo/__init__.py
Normal file
5
emojiinfo/__init__.py
Normal file
|
@ -0,0 +1,5 @@
|
|||
from .emojiinfo import EmojiInfo
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(EmojiInfo(bot))
|
5309
emojiinfo/data/emojis.json
Normal file
5309
emojiinfo/data/emojis.json
Normal file
File diff suppressed because it is too large
Load diff
129
emojiinfo/emojiinfo.py
Normal file
129
emojiinfo/emojiinfo.py
Normal file
|
@ -0,0 +1,129 @@
|
|||
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)
|
16
emojiinfo/info.json
Normal file
16
emojiinfo/info.json
Normal file
|
@ -0,0 +1,16 @@
|
|||
{
|
||||
"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"
|
||||
]
|
||||
}
|
91
emojiinfo/model.py
Normal file
91
emojiinfo/model.py
Normal file
|
@ -0,0 +1,91 @@
|
|||
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.)"
|
||||
],
|
||||
"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 ).",
|
||||
"name": "SeaCogs",
|
||||
"index_name": "sea-cogs",
|
||||
"short": "Various cogs for Red, by SeaswimmerTheFsh (seasw.)",
|
||||
"description": "Various cogs for Red, by SeaswimmerTheFsh (seasw.)"
|
||||
}
|
||||
|
|
|
@ -18,6 +18,7 @@ nav:
|
|||
- Configuration: aurora/configuration.md
|
||||
- Bible: bible.md
|
||||
- Backup: backup.md
|
||||
- EmojiInfo: emojiinfo.md
|
||||
- Nerdify: nerdify.md
|
||||
- Pterodactyl:
|
||||
- pterodactyl/index.md
|
||||
|
|
1419
poetry.lock
generated
1419
poetry.lock
generated
File diff suppressed because it is too large
Load diff
|
@ -14,7 +14,9 @@ py-dactyl = "^2.0.4"
|
|||
websockets = "^12.0"
|
||||
pillow = "^10.3.0"
|
||||
numpy = "^1.26.4"
|
||||
py-lav = {extras = ["all"], version = ">=1.14.3,<1.15"}
|
||||
colorthief = "^0.2.1"
|
||||
beautifulsoup4 = "^4.12.3"
|
||||
markdownify = "^0.12.1"
|
||||
|
||||
[tool.poetry.group.dev]
|
||||
optional = true
|
||||
|
|
5
seautils/__init__.py
Normal file
5
seautils/__init__.py
Normal file
|
@ -0,0 +1,5 @@
|
|||
from .seautils import SeaUtils
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(SeaUtils(bot))
|
13
seautils/info.json
Normal file
13
seautils/info.json
Normal file
|
@ -0,0 +1,13 @@
|
|||
{
|
||||
"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"]
|
||||
}
|
250
seautils/seautils.py
Normal file
250
seautils/seautils.py
Normal file
|
@ -0,0 +1,250 @@
|
|||
# _____ _
|
||||
# / ____| (_)
|
||||
# | (___ ___ __ _ _____ ___ _ __ ___ _ __ ___ ___ _ __
|
||||
# \___ \ / _ \/ _` / __\ \ /\ / / | '_ ` _ \| '_ ` _ \ / _ \ '__|
|
||||
# ____) | __/ (_| \__ \\ 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}."))
|
|
@ -1,12 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from pylav.extension.red.utils.required_methods import pylav_auto_setup
|
||||
from pylav.type_hints.bot import DISCORD_BOT_TYPE
|
||||
from redbot.core.utils import get_end_user_data_statement
|
||||
|
||||
from .tts import TTS
|
||||
|
||||
__red_end_user_data_statement__ = get_end_user_data_statement(__file__)
|
||||
|
||||
async def setup(bot: DISCORD_BOT_TYPE):
|
||||
await pylav_auto_setup(bot, TTS)
|
|
@ -1,14 +0,0 @@
|
|||
from redbot.core import Config
|
||||
|
||||
config: Config = Config.get_conf(None, identifier=69737245070283, cog_name="TTS")
|
||||
|
||||
|
||||
def register_config(config_obj: Config):
|
||||
config_obj.register_global(
|
||||
use_google_tts = False,
|
||||
)
|
||||
config_obj.register_guild(
|
||||
enabled_channels = [],
|
||||
announce = False,
|
||||
voice_channels = True
|
||||
)
|
|
@ -1,21 +0,0 @@
|
|||
{
|
||||
"author" : ["SeaswimmerTheFsh (seasw.)"],
|
||||
"install_msg" : "Thank you for installing TTS!\nPlease read the [documentation](https://seacogs.coastalcommits.com/tts) for more information.\nYou can find the source code of this cog [here](https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs).",
|
||||
"name" : "TTS",
|
||||
"short" : "Text to Speech through Pylav",
|
||||
"description" : "Text to Speech through Pylav",
|
||||
"end_user_data_statement" : "This cog does not store end user data.",
|
||||
"hidden": false,
|
||||
"disabled": false,
|
||||
"min_bot_version": "3.5.0",
|
||||
"min_python_version": [3, 11, 0],
|
||||
"requirements": [
|
||||
"Py-Lav[all]"
|
||||
],
|
||||
"tags": [
|
||||
"pylav",
|
||||
"audio",
|
||||
"tts"
|
||||
],
|
||||
"required_cogs": {"audio" : "https://github.com/PyLav/Red-Cogs"}
|
||||
}
|
68
tts/menu.py
68
tts/menu.py
|
@ -1,68 +0,0 @@
|
|||
from discord import ButtonStyle, Embed, Interaction, ui
|
||||
from redbot.core import commands
|
||||
from redbot.core.utils.chat_formatting import bold
|
||||
|
||||
from tts.config import config
|
||||
|
||||
|
||||
class Menu(ui.View):
|
||||
def __init__(self, ctx: commands.Context):
|
||||
super().__init__()
|
||||
self.ctx = ctx
|
||||
|
||||
@ui.button(label="Announce", style=ButtonStyle.green, row=0)
|
||||
async def announce(self, interaction: Interaction, button: ui.Button):
|
||||
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
|
||||
return
|
||||
await interaction.response.defer()
|
||||
current_setting = await config.guild(interaction.guild).announce
|
||||
await config.guild(interaction.guild).announce.set(not current_setting)
|
||||
await interaction.message.edit(embed=await embed(self.ctx))
|
||||
|
||||
@ui.button(label="Use Voice Channels", style=ButtonStyle.green, row=0)
|
||||
async def voice_channels(self, interaction: Interaction, button: ui.Button):
|
||||
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
|
||||
return
|
||||
await interaction.response.defer()
|
||||
current_setting = await config.guild(interaction.guild).voice_channels()
|
||||
await config.guild(interaction.guild).voice_channels.set(not current_setting)
|
||||
await interaction.message.edit(embed=await embed(self.ctx))
|
||||
|
||||
@ui.select(placeholder="Enabled Channels", cls=ui.ChannelSelect, row=1)
|
||||
async def log_channel(self, interaction: Interaction, select: ui.ChannelSelect):
|
||||
if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator:
|
||||
await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True)
|
||||
return
|
||||
await interaction.response.defer()
|
||||
channels: list = await config.guild(interaction.guild).enabled_channels()
|
||||
if select.values[0] in channels:
|
||||
channels.remove(select.values[0])
|
||||
else:
|
||||
channels.append(select.values[0])
|
||||
await config.guild(interaction.guild).enabled_channels.set(channels)
|
||||
await interaction.message.edit(embed=await embed(self.ctx))
|
||||
|
||||
async def embed(ctx: commands.Context):
|
||||
embed = Embed(title="TTS Settings", color=ctx.embed_color)
|
||||
override_settings = {
|
||||
"announce": await config.guild(ctx.guild).announce(),
|
||||
"voice_channels": await config.guild(ctx.guild).voice_channels(),
|
||||
"enabled_channels": await config.guild(ctx.guild).enabled_channels(),
|
||||
}
|
||||
|
||||
override_str = [
|
||||
"- " + bold("Announce: ") + get_bool_emoji(override_settings["announce"]),
|
||||
"- " + bold("Voice Channels: ") + get_bool_emoji(override_settings["voice_channels"]),
|
||||
"- " + ", ".join([f"<#{channel}>" for channel in override_settings["voice_channels"]])
|
||||
]
|
||||
embed.description = "\n".join(override_str)
|
||||
|
||||
def get_bool_emoji(value: bool) -> str:
|
||||
"""Returns a unicode emoji based on a boolean value."""
|
||||
if value is True:
|
||||
return "\N{WHITE HEAVY CHECK MARK}"
|
||||
if value is False:
|
||||
return "\N{NO ENTRY SIGN}"
|
||||
return "\N{BLACK QUESTION MARK ORNAMENT}\N{VARIATION SELECTOR-16}"
|
57
tts/tts.py
57
tts/tts.py
|
@ -1,57 +0,0 @@
|
|||
# _____ _
|
||||
# / ____| (_)
|
||||
# | (___ ___ __ _ _____ ___ _ __ ___ _ __ ___ ___ _ __
|
||||
# \___ \ / _ \/ _` / __\ \ /\ / / | '_ ` _ \| '_ ` _ \ / _ \ '__|
|
||||
# ____) | __/ (_| \__ \\ V V /| | | | | | | | | | | | __/ |
|
||||
# |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_|
|
||||
|
||||
import logging
|
||||
|
||||
from discord import Message
|
||||
from redbot.core import commands
|
||||
from redbot.core.bot import Red
|
||||
|
||||
from tts.config import config
|
||||
from tts.menu import Menu, embed
|
||||
|
||||
|
||||
class TTS(commands.Cog):
|
||||
"""Text to Speech through Pylav"""
|
||||
|
||||
def __init__(self, bot: Red):
|
||||
self.bot = bot
|
||||
self.logger = logging.getLogger("red.sea.tts")
|
||||
|
||||
async def on_message(self, message: Message):
|
||||
await self.bot.wait_until_red_ready()
|
||||
if message.author.bot:
|
||||
return
|
||||
if message.guild is None:
|
||||
return
|
||||
valid_prefixes = await self.bot.get_valid_prefixes(message.guild)
|
||||
valid_prefixes.append("\\")
|
||||
if any(message.content.startswith(prefix) for prefix in valid_prefixes):
|
||||
return
|
||||
if message.channel.id in await self.config.guild(message.guild).enabled_channels():
|
||||
pylav = self.bot.get_cog("PyLavPlayer")
|
||||
if pylav is None:
|
||||
self.logger.error("PyLav is not loaded, so TTS is not available.")
|
||||
await message.reply("PyLav is not loaded, so TTS is not available.\nPlease report this to the bot owner.\nIf you are the bot owner, see [https://github.com/PyLav/Red-Cogs](PyLav/RedCogs) for more information.")
|
||||
return
|
||||
#TODO - add PyLav integration
|
||||
return
|
||||
|
||||
@commands.group(name="tts")
|
||||
@commands.admin_or_permissions(manage_guild=True)
|
||||
async def tts(self, ctx: commands.Context):
|
||||
"""Text to Speech settings"""
|
||||
await ctx.send(embed=await embed(ctx), view=Menu(ctx))
|
||||
|
||||
@tts.command(name="google")
|
||||
@commands.is_owner()
|
||||
async def tts_google(self, ctx: commands.Context, enable: bool = None):
|
||||
"""Enable or disable Google Cloud TTS"""
|
||||
if enable is None:
|
||||
enable = not await config.use_google_tts()
|
||||
await config.use_google_tts.set(enable)
|
||||
await ctx.send(f"Google TTS has been {'enabled' if enable else 'disabled'}.")
|
Loading…
Add table
Add a link
Reference in a new issue