mirror of
https://github.com/Cog-Creators/Red-DiscordBot.git
synced 2025-11-05 18:58:53 -05:00
* Temporarily set d.py to use latest git revision
* Remove `bot` param to Client.start
* Switch to aware datetimes
A lot of this is removing `.replace(...)` which while not technically
needed, simplifies the code base. There's only a few changes that are
actually necessary here.
* Update to work with new Asset design
* [threads] Update core ModLog API to support threads
- Added proper support for passing `Thread` to `channel`
when creating/editing case
- Added `parent_channel_id` attribute to Modlog API's Case
- Added `parent_channel` property that tries to get parent channel
- Updated case's content to show both thread and parent information
* [threads] Disallow usage of threads in some of the commands
- announceset channel
- filter channel clear
- filter channel add
- filter channel remove
- GlobalUniqueObjectFinder converter
- permissions addglobalrule
- permissions removeglobalrule
- permissions removeserverrule
- Permissions cog does not perform any validation for IDs
when setting through YAML so that has not been touched
- streamalert twitch/youtube/picarto
- embedset channel
- set ownernotifications adddestination
* [threads] Handle threads in Red's permissions system (Requires)
- Made permissions system apply rules of (only) parent in threads
* [threads] Update embed_requested to support threads
- Threads don't have their own embed settings and inherit from parent
* [threads] Update Red.message_eligible_as_command to support threads
* [threads] Properly handle invocation of [p](un)mutechannel in threads
Usage of a (un)mutechannel will mute/unmute user in the parent channel
if it's invoked in a thread.
* [threads] Update Filter cog to properly handle threads
- `[p]filter channel list` in a threads sends list for parent channel
- Checking for filter hits for a message in a thread checks its parent
channel's word list. There's no separate word list for threads.
* [threads] Support threads in Audio cog
- Handle threads being notify channels
- Update type hint for `is_query_allowed()`
* [threads] Update type hints and documentation to reflect thread support
- Documented that `{channel}` in CCs might be a thread
- Allowed (documented) usage of threads with `Config.channel()`
- Separate thread scope is still in the picture though
if it were to be done, it's going to be in separate in PR
- GuildContext.channel might be Thread
* Use less costy channel check in customcom's on_message_without_command
This isn't needed for d.py 2.0 but whatever...
* Update for in-place edits
* Embed's bool changed behavior, I'm hoping it doesn't affect us
* Address User.permissions_in() removal
* Swap VerificationLevel.extreme with VerificationLevel.highest
* Change to keyword-only parameters
* Change of `Guild.vanity_invite()` return type
* avatar -> display_avatar
* Fix metaclass shenanigans with Converter
* Update Red.add_cog() to be inline with `dpy_commands.Bot.add_cog()`
This means adding `override` keyword-only parameter and causing
small breakage by swapping RuntimeError with discord.ClientException.
* Address all DEP-WARNs
* Remove Context.clean_prefix and use upstream implementation instead
* Remove commands.Literal and use upstream implementation instead
Honestly, this was a rather bad implementation anyway...
Breaking but actually not really - it was provisional.
* Update Command.callback's setter
Support for functools.partial is now built into d.py
* Add new perms in HUMANIZED_PERM mapping (some from d.py 1.7 it seems)
BTW, that should really be in core instead of what we have now...
* Remove the part of do_conversion that has not worked for a long while
* Stop wrapping BadArgument in ConversionFailure
This is breaking but it's best to resolve it like this.
The functionality of ConversionFailure can be replicated with
Context.current_parameter and Context.current_argument.
* Add custom errors for int and float converters
* Remove Command.__call__ as it's now implemented in d.py
* Get rid of _dpy_reimplements
These were reimplemented for the purpose of typing
so it is no longer needed now that d.py is type hinted.
* Add return to Red.remove_cog
* Ensure we don't delete messages that differ only by used sticker
* discord.InvalidArgument->ValueError
* Move from raw <t:...> syntax to discord.utils.format_dt()
* Address AsyncIter removal
* Swap to pos-only for params that are pos-only in upstream
* Update for changes to Command.params
* [threads] Support threads in ignore checks and allow ignoring them
- Updated `[p](un)ignore channel` to accept threads
- Updated `[p]ignore list` to list ignored threads
- Updated logic in `Red.ignored_channel_or_guild()`
Ignores for guild channels now work as follows (only changes for threads):
- if channel is not a thread:
- check if user has manage channels perm in channel
and allow command usage if so
- check if channel is ignored and disallow command usage if so
- allow command usage if none of the conditions above happened
- if channel is a thread:
- check if user has manage channels perm in parent channel
and allow command usage if so
- check if parent channel is ignored and disallow command usage
if so
- check if user has manage thread perm in parent channel
and allow command usage if so
- check if thread is ignored and disallow command usage if so
- allow command usage if none of the conditions above happened
* [partial] Raise TypeError when channel is of PartialMessageable type
- Red.embed_requested
- Red.ignored_channel_or_guild
* [partial] Discard command messages when channel is PartialMessageable
* [threads] Add utilities for checking appropriate perms in both channels & threads
* [threads] Update code to use can_react_in() and @bot_can_react()
* [threads] Update code to use can_send_messages_in
* [threads] Add send_messages_in_threads perm to mute role and overrides
* [threads] Update code to use (bot/user)_can_manage_channel
* [threads] Update [p]diagnoseissues to work with threads
* Type hint fix
* [threads] Patch vendored discord.ext.menus to check proper perms in threads
I guess we've reached time when we have to patch the lib we vendor...
* Make docs generation work with non-final d.py releases
* Update discord.utils.oauth_url() usage
* Swap usage of discord.Embed.Empty/discord.embeds.EmptyEmbed to None
* Update usage of Guild.member_count to work with `None`
* Switch from Guild.vanity_invite() to Guild.vanity_url
* Update startup process to work with d.py's new asynchronous startup
* Use setup_hook() for pre-connect actions
* Update core's add_cog, remove_cog, and load_extension methods
* Update all setup functions to async and add awaits to bot.add_cog calls
* Modernize cogs by using async cog_load and cog_unload
* Address StoreChannel removal
* [partial] Disallow passing PartialMessageable to Case.channel
* [partial] Update cogs and utils to work better with PartialMessageable
- Ignore messages with PartialMessageable channel in CustomCommands cog
- In Filter cog, don't pass channel to modlog.create_case()
if it's PartialMessageable
- In Trivia cog, only compare channel IDs
- Make `.utils.menus.menu()` work for messages
with PartialMessageable channel
- Make checks in `.utils.tunnel.Tunnel.communicate()` more rigid
* Add few missing DEP-WARNs
279 lines
10 KiB
Python
279 lines
10 KiB
Python
from typing import Tuple, Dict, Optional, List, Union
|
|
from re import findall
|
|
|
|
import discord
|
|
from discord.ext.commands.view import StringView # DEP-WARN
|
|
from redbot.core import commands, Config
|
|
from redbot.core.i18n import Translator
|
|
from redbot.core.utils import AsyncIter
|
|
|
|
_ = Translator("Alias", __file__)
|
|
|
|
|
|
class ArgParseError(Exception):
|
|
pass
|
|
|
|
|
|
class AliasEntry:
|
|
"""An object containing all required information about an alias"""
|
|
|
|
name: str
|
|
command: Union[Tuple[str], str]
|
|
creator: int
|
|
guild: Optional[int]
|
|
uses: int
|
|
|
|
def __init__(
|
|
self, name: str, command: Union[Tuple[str], str], creator: int, guild: Optional[int]
|
|
):
|
|
super().__init__()
|
|
self.name = name
|
|
self.command = command
|
|
self.creator = creator
|
|
|
|
self.guild = guild
|
|
self.uses = 0
|
|
|
|
def inc(self):
|
|
"""
|
|
Increases the `uses` stat by 1.
|
|
:return: new use count
|
|
"""
|
|
self.uses += 1
|
|
return self.uses
|
|
|
|
def get_extra_args_from_alias(self, message: discord.Message, prefix: str) -> str:
|
|
"""
|
|
When an alias is executed by a user in chat this function tries
|
|
to get any extra arguments passed in with the call.
|
|
Whitespace will be trimmed from both ends.
|
|
:param message:
|
|
:param prefix:
|
|
:param alias:
|
|
:return:
|
|
"""
|
|
known_content_length = len(prefix) + len(self.name)
|
|
extra = message.content[known_content_length:]
|
|
view = StringView(extra)
|
|
view.skip_ws()
|
|
extra = []
|
|
while not view.eof:
|
|
prev = view.index
|
|
word = view.get_quoted_word()
|
|
if len(word) < view.index - prev:
|
|
word = "".join((view.buffer[prev], word, view.buffer[view.index - 1]))
|
|
extra.append(word)
|
|
view.skip_ws()
|
|
return extra
|
|
|
|
def to_json(self) -> dict:
|
|
return {
|
|
"name": self.name,
|
|
"command": self.command,
|
|
"creator": self.creator,
|
|
"guild": self.guild,
|
|
"uses": self.uses,
|
|
}
|
|
|
|
@classmethod
|
|
def from_json(cls, data: dict):
|
|
ret = cls(data["name"], data["command"], data["creator"], data["guild"])
|
|
ret.uses = data.get("uses", 0)
|
|
return ret
|
|
|
|
|
|
class AliasCache:
|
|
def __init__(self, config: Config, cache_enabled: bool = True):
|
|
self.config = config
|
|
self._cache_enabled = cache_enabled
|
|
self._loaded = False
|
|
self._aliases: Dict[Optional[int], Dict[str, AliasEntry]] = {None: {}}
|
|
|
|
async def anonymize_aliases(self, user_id: int):
|
|
async with self.config.entries() as global_aliases:
|
|
for a in global_aliases:
|
|
if a.get("creator", 0) == user_id:
|
|
a["creator"] = 0xDE1
|
|
if self._cache_enabled:
|
|
self._aliases[None][a["name"]] = AliasEntry.from_json(a)
|
|
|
|
all_guilds = await self.config.all_guilds()
|
|
async for guild_id, guild_data in AsyncIter(all_guilds.items(), steps=100):
|
|
for a in guild_data["entries"]:
|
|
if a.get("creator", 0) == user_id:
|
|
break
|
|
else:
|
|
continue
|
|
# basically, don't build a context manager without a need.
|
|
async with self.config.guild_from_id(guild_id).entries() as entry_list:
|
|
for a in entry_list:
|
|
if a.get("creator", 0) == user_id:
|
|
a["creator"] = 0xDE1
|
|
if self._cache_enabled:
|
|
self._aliases[guild_id][a["name"]] = AliasEntry.from_json(a)
|
|
|
|
async def load_aliases(self):
|
|
if not self._cache_enabled:
|
|
self._loaded = True
|
|
return
|
|
for alias in await self.config.entries():
|
|
self._aliases[None][alias["name"]] = AliasEntry.from_json(alias)
|
|
|
|
all_guilds = await self.config.all_guilds()
|
|
async for guild_id, guild_data in AsyncIter(all_guilds.items(), steps=100):
|
|
if guild_id not in self._aliases:
|
|
self._aliases[guild_id] = {}
|
|
for alias in guild_data["entries"]:
|
|
self._aliases[guild_id][alias["name"]] = AliasEntry.from_json(alias)
|
|
self._loaded = True
|
|
|
|
async def get_aliases(self, ctx: commands.Context) -> List[AliasEntry]:
|
|
"""Returns all possible aliases with the given context"""
|
|
global_aliases: List[AliasEntry] = []
|
|
server_aliases: List[AliasEntry] = []
|
|
global_aliases = await self.get_global_aliases()
|
|
if ctx.guild and ctx.guild.id in self._aliases:
|
|
server_aliases = await self.get_guild_aliases(ctx.guild)
|
|
return global_aliases + server_aliases
|
|
|
|
async def get_guild_aliases(self, guild: discord.Guild) -> List[AliasEntry]:
|
|
"""Returns all guild specific aliases"""
|
|
aliases: List[AliasEntry] = []
|
|
|
|
if self._cache_enabled:
|
|
if guild.id in self._aliases:
|
|
for _, alias in self._aliases[guild.id].items():
|
|
aliases.append(alias)
|
|
else:
|
|
aliases = [AliasEntry.from_json(d) for d in await self.config.guild(guild).entries()]
|
|
return aliases
|
|
|
|
async def get_global_aliases(self) -> List[AliasEntry]:
|
|
"""Returns all global specific aliases"""
|
|
aliases: List[AliasEntry] = []
|
|
if self._cache_enabled:
|
|
for _, alias in self._aliases[None].items():
|
|
aliases.append(alias)
|
|
else:
|
|
aliases = [AliasEntry.from_json(d) for d in await self.config.entries()]
|
|
return aliases
|
|
|
|
async def get_alias(
|
|
self, guild: Optional[discord.Guild], alias_name: str
|
|
) -> Optional[AliasEntry]:
|
|
"""Returns an AliasEntry object if the provided alias_name is a registered alias"""
|
|
server_aliases: List[AliasEntry] = []
|
|
|
|
if self._cache_enabled:
|
|
if alias_name in self._aliases[None]:
|
|
return self._aliases[None][alias_name]
|
|
if guild is not None:
|
|
if guild.id in self._aliases:
|
|
if alias_name in self._aliases[guild.id]:
|
|
return self._aliases[guild.id][alias_name]
|
|
else:
|
|
if guild:
|
|
server_aliases = [
|
|
AliasEntry.from_json(d) for d in await self.config.guild(guild.id).entries()
|
|
]
|
|
global_aliases = [AliasEntry.from_json(d) for d in await self.config.entries()]
|
|
all_aliases = global_aliases + server_aliases
|
|
|
|
for alias in all_aliases:
|
|
if alias.name == alias_name:
|
|
return alias
|
|
|
|
return None
|
|
|
|
@staticmethod
|
|
def format_command_for_alias(command: str) -> str:
|
|
# This was present in add_alias previously
|
|
# Made this into a separate method so as to reuse the same code in edit_alias
|
|
indices = findall(r"{(\d*)}", command)
|
|
if indices:
|
|
try:
|
|
indices = [int(a[0]) for a in indices]
|
|
except IndexError:
|
|
raise ArgParseError(_("Arguments must be specified with a number."))
|
|
low = min(indices)
|
|
indices = [a - low for a in indices]
|
|
high = max(indices)
|
|
gaps = set(indices).symmetric_difference(range(high + 1))
|
|
if gaps:
|
|
raise ArgParseError(
|
|
_("Arguments must be sequential. Missing arguments: ")
|
|
+ ", ".join(str(i + low) for i in gaps)
|
|
)
|
|
command = command.format(*(f"{{{i}}}" for i in range(-low, high + low + 1)))
|
|
return command
|
|
|
|
async def add_alias(
|
|
self, ctx: commands.Context, alias_name: str, command: str, global_: bool = False
|
|
) -> AliasEntry:
|
|
command = self.format_command_for_alias(command)
|
|
|
|
if global_:
|
|
alias = AliasEntry(alias_name, command, ctx.author.id, None)
|
|
settings = self.config
|
|
if self._cache_enabled:
|
|
self._aliases[None][alias.name] = alias
|
|
else:
|
|
alias = AliasEntry(alias_name, command, ctx.author.id, ctx.guild.id)
|
|
settings = self.config.guild(ctx.guild)
|
|
if self._cache_enabled:
|
|
if ctx.guild.id not in self._aliases:
|
|
self._aliases[ctx.guild.id] = {}
|
|
self._aliases[ctx.guild.id][alias.name] = alias
|
|
|
|
async with settings.entries() as curr_aliases:
|
|
curr_aliases.append(alias.to_json())
|
|
|
|
return alias
|
|
|
|
async def edit_alias(
|
|
self, ctx: commands.Context, alias_name: str, command: str, global_: bool = False
|
|
) -> bool:
|
|
command = self.format_command_for_alias(command)
|
|
|
|
if global_:
|
|
settings = self.config
|
|
else:
|
|
settings = self.config.guild(ctx.guild)
|
|
|
|
async with settings.entries() as aliases:
|
|
for index, alias in enumerate(aliases):
|
|
if alias["name"] == alias_name:
|
|
alias_edited = AliasEntry.from_json(alias)
|
|
alias_edited.command = command
|
|
aliases[index] = alias_edited.to_json()
|
|
|
|
if self._cache_enabled:
|
|
if global_:
|
|
self._aliases[None][alias_edited.name] = alias_edited
|
|
else:
|
|
self._aliases[ctx.guild.id][alias_edited.name] = alias_edited
|
|
return True
|
|
|
|
return False
|
|
|
|
async def delete_alias(
|
|
self, ctx: commands.Context, alias_name: str, global_: bool = False
|
|
) -> bool:
|
|
if global_:
|
|
settings = self.config
|
|
else:
|
|
settings = self.config.guild(ctx.guild)
|
|
|
|
async with settings.entries() as aliases:
|
|
for alias in aliases:
|
|
if alias["name"] == alias_name:
|
|
aliases.remove(alias)
|
|
if self._cache_enabled:
|
|
if global_:
|
|
del self._aliases[None][alias_name]
|
|
else:
|
|
del self._aliases[ctx.guild.id][alias_name]
|
|
return True
|
|
|
|
return False
|