mirror of
https://github.com/Cog-Creators/Red-DiscordBot.git
synced 2025-11-06 11:18:54 -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
256 lines
8.4 KiB
Python
256 lines
8.4 KiB
Python
import asyncio
|
|
import discord
|
|
from datetime import datetime
|
|
from redbot.core.utils.chat_formatting import pagify
|
|
import io
|
|
import weakref
|
|
from typing import List, Optional, Union
|
|
from .common_filters import filter_mass_mentions
|
|
|
|
_instances = weakref.WeakValueDictionary({})
|
|
|
|
|
|
class TunnelMeta(type):
|
|
"""
|
|
lets prevent having multiple tunnels with the same
|
|
places involved.
|
|
"""
|
|
|
|
def __call__(cls, *args, **kwargs):
|
|
lockout_tuple = ((kwargs.get("sender"), kwargs.get("origin")), kwargs.get("recipient"))
|
|
|
|
if lockout_tuple in _instances:
|
|
return _instances[lockout_tuple]
|
|
|
|
# this is needed because weakvalue dicts can
|
|
# change size without warning if an object is discarded
|
|
# it can raise a runtime error, so ..
|
|
while True:
|
|
try:
|
|
if not (
|
|
any(lockout_tuple[0] == x[0] for x in _instances.keys())
|
|
or any(lockout_tuple[1] == x[1] for x in _instances.keys())
|
|
):
|
|
# if this isn't temporarily stored, the weakref dict
|
|
# will discard this before the return statement,
|
|
# causing a key error
|
|
temp = super(TunnelMeta, cls).__call__(*args, **kwargs)
|
|
_instances[lockout_tuple] = temp
|
|
return temp
|
|
except: # NOQA: E722
|
|
# Am I really supposed to except a runtime error flake >.>
|
|
continue
|
|
else:
|
|
return None
|
|
|
|
|
|
class Tunnel(metaclass=TunnelMeta):
|
|
"""
|
|
A tunnel interface for messages
|
|
|
|
This will return None on init if the destination
|
|
or source + origin pair is already in use, or the
|
|
existing tunnel object if one exists for the designated
|
|
parameters
|
|
|
|
Attributes
|
|
----------
|
|
sender: `discord.Member`
|
|
The person who opened the tunnel
|
|
origin: `discord.TextChannel` or `discord.Thread`
|
|
The channel in which it was opened
|
|
recipient: `discord.User`
|
|
The user on the other end of the tunnel
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
*,
|
|
sender: discord.Member,
|
|
origin: Union[discord.TextChannel, discord.Thread],
|
|
recipient: discord.User,
|
|
):
|
|
self.sender = sender
|
|
self.origin = origin
|
|
self.recipient = recipient
|
|
self.last_interaction = datetime.utcnow()
|
|
|
|
async def react_close(self, *, uid: int, message: str = ""):
|
|
send_to = self.recipient if uid == self.sender.id else self.origin
|
|
closer = next(filter(lambda x: x.id == uid, (self.sender, self.recipient)), None)
|
|
await send_to.send(filter_mass_mentions(message.format(closer=closer)))
|
|
|
|
@property
|
|
def members(self):
|
|
return self.sender, self.recipient
|
|
|
|
@property
|
|
def minutes_since(self):
|
|
return int((self.last_interaction - datetime.utcnow()).seconds / 60)
|
|
|
|
@staticmethod
|
|
async def message_forwarder(
|
|
*,
|
|
destination: discord.abc.Messageable,
|
|
content: str = None,
|
|
embed=None,
|
|
files: Optional[List[discord.File]] = None,
|
|
) -> List[discord.Message]:
|
|
"""
|
|
This does the actual sending, use this instead of a full tunnel
|
|
if you are using command initiated reactions instead of persistent
|
|
event based ones
|
|
|
|
Parameters
|
|
----------
|
|
destination: discord.abc.Messageable
|
|
Where to send
|
|
content: str
|
|
The message content
|
|
embed: discord.Embed
|
|
The embed to send
|
|
files: Optional[List[discord.File]]
|
|
A list of files to send.
|
|
|
|
Returns
|
|
-------
|
|
List[discord.Message]
|
|
The messages sent as a result.
|
|
|
|
Raises
|
|
------
|
|
discord.Forbidden
|
|
see `discord.abc.Messageable.send`
|
|
discord.HTTPException
|
|
see `discord.abc.Messageable.send`
|
|
"""
|
|
rets = []
|
|
if content:
|
|
for page in pagify(content):
|
|
rets.append(await destination.send(page, files=files, embed=embed))
|
|
if files:
|
|
del files
|
|
if embed:
|
|
del embed
|
|
elif embed or files:
|
|
rets.append(await destination.send(files=files, embed=embed))
|
|
return rets
|
|
|
|
@staticmethod
|
|
async def files_from_attach(
|
|
m: discord.Message, *, use_cached: bool = False, images_only: bool = False
|
|
) -> List[discord.File]:
|
|
"""
|
|
makes a list of file objects from a message
|
|
returns an empty list if none, or if the sum of file sizes
|
|
is too large for the bot to send
|
|
|
|
Parameters
|
|
---------
|
|
m: `discord.Message`
|
|
A message to get attachments from
|
|
use_cached: `bool`
|
|
Whether to use ``proxy_url`` rather than ``url`` when downloading the attachment
|
|
images_only: `bool`
|
|
Whether only image attachments should be added to returned list
|
|
|
|
Returns
|
|
-------
|
|
list of `discord.File`
|
|
A list of `discord.File` objects
|
|
|
|
"""
|
|
files = []
|
|
max_size = 8 * 1000 * 1000
|
|
if m.attachments and sum(a.size for a in m.attachments) <= max_size:
|
|
for a in m.attachments:
|
|
if images_only and a.height is None:
|
|
# if this is None, it's not an image
|
|
continue
|
|
_fp = io.BytesIO()
|
|
try:
|
|
await a.save(_fp, use_cached=use_cached)
|
|
except discord.HTTPException as e:
|
|
# this is required, because animated webp files aren't cached
|
|
if not (e.status == 415 and images_only and use_cached):
|
|
raise
|
|
files.append(discord.File(_fp, filename=a.filename))
|
|
return files
|
|
|
|
# Backwards-compatible typo fix (GH-2496)
|
|
files_from_attatch = files_from_attach
|
|
|
|
async def close_because_disabled(self, close_message: str):
|
|
"""
|
|
Sends a mesage to both ends of the tunnel that the tunnel is now closed.
|
|
|
|
Parameters
|
|
----------
|
|
close_message: str
|
|
The message to send to both ends of the tunnel.
|
|
"""
|
|
|
|
tasks = [destination.send(close_message) for destination in (self.recipient, self.origin)]
|
|
await asyncio.gather(*tasks, return_exceptions=True)
|
|
|
|
async def communicate(
|
|
self, *, message: discord.Message, topic: str = None, skip_message_content: bool = False
|
|
):
|
|
"""
|
|
Forwards a message.
|
|
|
|
Parameters
|
|
----------
|
|
message : `discord.Message`
|
|
The message to forward
|
|
topic : `str`
|
|
A string to prepend
|
|
skip_message_content : `bool`
|
|
If this flag is set, only the topic will be sent
|
|
|
|
Returns
|
|
-------
|
|
`int`, `int`
|
|
a pair of ints matching the ids of the
|
|
message which was forwarded
|
|
and the last message the bot sent to do that.
|
|
useful if waiting for reactions.
|
|
|
|
Raises
|
|
------
|
|
discord.Forbidden
|
|
This should only happen if the user's DMs are disabled
|
|
the bot can't upload at the origin channel
|
|
or can't add reactions there.
|
|
"""
|
|
if message.channel.id == self.origin.id and message.author == self.sender:
|
|
send_to = self.recipient
|
|
elif message.author == self.recipient and message.guild is None:
|
|
send_to = self.origin
|
|
else:
|
|
return None
|
|
|
|
if not skip_message_content:
|
|
content = "\n".join((topic, message.content)) if topic else message.content
|
|
else:
|
|
content = topic
|
|
|
|
if message.attachments:
|
|
attach = await self.files_from_attach(message)
|
|
if not attach:
|
|
await message.channel.send(
|
|
"Could not forward attachments. "
|
|
"Total size of attachments in a single "
|
|
"message must be less than 8MB."
|
|
)
|
|
else:
|
|
attach = []
|
|
|
|
rets = await self.message_forwarder(destination=send_to, content=content, files=attach)
|
|
|
|
await message.add_reaction("\N{WHITE HEAVY CHECK MARK}")
|
|
await message.add_reaction("\N{NEGATIVE SQUARED CROSS MARK}")
|
|
self.last_interaction = datetime.utcnow()
|
|
await rets[-1].add_reaction("\N{NEGATIVE SQUARED CROSS MARK}")
|
|
return [rets[-1].id, message.id]
|