Migration to discord.py 2.0 (#5600)

* 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
This commit is contained in:
jack1142
2022-04-03 03:21:20 +02:00
committed by GitHub
parent c9a0971945
commit febca8ccbb
104 changed files with 1427 additions and 999 deletions

View File

@@ -3,7 +3,7 @@ from redbot.core.bot import Red
from .core import Audio
def setup(bot: Red):
async def setup(bot: Red) -> None:
cog = Audio(bot)
bot.add_cog(cog)
await bot.add_cog(cog)
cog.start_up_task()

View File

@@ -973,7 +973,7 @@ class AudioAPIInterface:
and not query.local_track_path.exists()
):
continue
notify_channel = player.guild.get_channel(notify_channel_id)
notify_channel = player.guild.get_channel_or_thread(notify_channel_id)
if not await self.cog.is_query_allowed(
self.config,
notify_channel,

View File

@@ -74,7 +74,6 @@ class Audio(
self.permission_cache = discord.Permissions(
embed_links=True,
read_messages=True,
send_messages=True,
read_message_history=True,
add_reactions=True,
)

View File

@@ -196,7 +196,7 @@ class MixinMeta(ABC):
async def is_query_allowed(
self,
config: Config,
ctx_or_channel: Optional[Union[Context, discord.TextChannel]],
ctx_or_channel: Optional[Union[Context, discord.TextChannel, discord.Thread]],
query: str,
query_obj: Query,
) -> bool:
@@ -250,7 +250,7 @@ class MixinMeta(ABC):
raise NotImplementedError()
@abstractmethod
def _has_notify_perms(self, channel: discord.TextChannel) -> bool:
def _has_notify_perms(self, channel: Union[discord.TextChannel, discord.Thread]) -> bool:
raise NotImplementedError()
@abstractmethod

View File

@@ -78,7 +78,7 @@ class AudioSetCommands(MixinMeta, metaclass=CompositeMetaClass):
)
@command_audioset_perms_global_whitelist.command(name="list")
@commands.bot_has_permissions(add_reactions=True)
@commands.bot_can_react()
async def command_audioset_perms_global_whitelist_list(self, ctx: commands.Context):
"""List all keywords added to the whitelist."""
whitelist = await self.config.url_keyword_whitelist()
@@ -172,7 +172,7 @@ class AudioSetCommands(MixinMeta, metaclass=CompositeMetaClass):
)
@command_audioset_perms_global_blacklist.command(name="list")
@commands.bot_has_permissions(add_reactions=True)
@commands.bot_can_react()
async def command_audioset_perms_global_blacklist_list(self, ctx: commands.Context):
"""List all keywords added to the blacklist."""
blacklist = await self.config.url_keyword_blacklist()
@@ -268,7 +268,7 @@ class AudioSetCommands(MixinMeta, metaclass=CompositeMetaClass):
)
@command_audioset_perms_whitelist.command(name="list")
@commands.bot_has_permissions(add_reactions=True)
@commands.bot_can_react()
async def command_audioset_perms_whitelist_list(self, ctx: commands.Context):
"""List all keywords added to the whitelist."""
whitelist = await self.config.guild(ctx.guild).url_keyword_whitelist()
@@ -361,7 +361,7 @@ class AudioSetCommands(MixinMeta, metaclass=CompositeMetaClass):
)
@command_audioset_perms_blacklist.command(name="list")
@commands.bot_has_permissions(add_reactions=True)
@commands.bot_can_react()
async def command_audioset_perms_blacklist_list(self, ctx: commands.Context):
"""List all keywords added to the blacklist."""
blacklist = await self.config.guild(ctx.guild).url_keyword_blacklist()
@@ -453,7 +453,7 @@ class AudioSetCommands(MixinMeta, metaclass=CompositeMetaClass):
await self.set_player_settings(ctx)
@command_audioset_autoplay.command(name="playlist", usage="<playlist_name_OR_id> [args]")
@commands.bot_has_permissions(add_reactions=True)
@commands.bot_can_react()
async def command_audioset_autoplay_playlist(
self,
ctx: commands.Context,
@@ -496,9 +496,7 @@ class AudioSetCommands(MixinMeta, metaclass=CompositeMetaClass):
ctx,
title=_("Playlists Are Not Available"),
description=_("The playlist section of Audio is currently unavailable"),
footer=discord.Embed.Empty
if not await self.bot.is_owner(ctx.author)
else _("Check your logs."),
footer=None if not await self.bot.is_owner(ctx.author) else _("Check your logs."),
)
if scope_data is None:
scope_data = [None, ctx.author, ctx.guild, False]
@@ -782,7 +780,7 @@ class AudioSetCommands(MixinMeta, metaclass=CompositeMetaClass):
@command_audioset.command(name="localpath")
@commands.is_owner()
@commands.bot_has_permissions(add_reactions=True)
@commands.bot_can_react()
async def command_audioset_localpath(self, ctx: commands.Context, *, local_path=None):
"""Set the localtracks path if the Lavalink.jar is not run from the Audio data folder.

View File

@@ -81,7 +81,8 @@ class PlayerControllerCommands(MixinMeta, metaclass=CompositeMetaClass):
@commands.command(name="now")
@commands.guild_only()
@commands.bot_has_permissions(embed_links=True, add_reactions=True)
@commands.bot_has_permissions(embed_links=True)
@commands.bot_can_react()
async def command_now(self, ctx: commands.Context):
"""Now playing."""
if not self._player_check(ctx):

View File

@@ -25,7 +25,8 @@ class EqualizerCommands(MixinMeta, metaclass=CompositeMetaClass):
@commands.group(name="eq", invoke_without_command=True)
@commands.guild_only()
@commands.cooldown(1, 15, commands.BucketType.guild)
@commands.bot_has_permissions(embed_links=True, add_reactions=True)
@commands.bot_has_permissions(embed_links=True)
@commands.bot_can_react()
async def command_equalizer(self, ctx: commands.Context):
"""Equalizer management.

View File

@@ -21,7 +21,8 @@ _ = Translator("Audio", Path(__file__))
class LocalTrackCommands(MixinMeta, metaclass=CompositeMetaClass):
@commands.group(name="local")
@commands.guild_only()
@commands.bot_has_permissions(embed_links=True, add_reactions=True)
@commands.bot_has_permissions(embed_links=True)
@commands.bot_can_react()
async def command_local(self, ctx: commands.Context):
"""Local playback commands."""

View File

@@ -41,7 +41,8 @@ class MiscellaneousCommands(MixinMeta, metaclass=CompositeMetaClass):
@commands.command(name="audiostats")
@commands.guild_only()
@commands.is_owner()
@commands.bot_has_permissions(embed_links=True, add_reactions=True)
@commands.bot_has_permissions(embed_links=True)
@commands.bot_can_react()
async def command_audiostats(self, ctx: commands.Context):
"""Audio stats."""
server_num = len(lavalink.active_players())

View File

@@ -9,7 +9,6 @@ import discord
import lavalink
from red_commons.logging import getLogger
from discord.embeds import EmptyEmbed
from lavalink import NodeNotFound
from redbot.core import commands
@@ -67,7 +66,7 @@ class PlayerCommands(MixinMeta, metaclass=CompositeMetaClass):
if not self._player_check(ctx):
if self.lavalink_connection_aborted:
msg = _("Connection to Lavalink node has failed")
desc = EmptyEmbed
desc = None
if await self.bot.is_owner(ctx.author):
desc = _("Please check your console or logs for details.")
return await self.send_embed_msg(ctx, title=msg, description=desc)
@@ -175,7 +174,7 @@ class PlayerCommands(MixinMeta, metaclass=CompositeMetaClass):
if not self._player_check(ctx):
if self.lavalink_connection_aborted:
msg = _("Connection to Lavalink node has failed")
desc = EmptyEmbed
desc = None
if await self.bot.is_owner(ctx.author):
desc = _("Please check your console or logs for details.")
return await self.send_embed_msg(ctx, title=msg, description=desc)
@@ -438,7 +437,7 @@ class PlayerCommands(MixinMeta, metaclass=CompositeMetaClass):
if not self._player_check(ctx):
if self.lavalink_connection_aborted:
msg = _("Connection to Lavalink node has failed")
desc = EmptyEmbed
desc = None
if await self.bot.is_owner(ctx.author):
desc = _("Please check your console or logs for details.")
return await self.send_embed_msg(ctx, title=msg, description=desc)
@@ -554,7 +553,7 @@ class PlayerCommands(MixinMeta, metaclass=CompositeMetaClass):
if not self._player_check(ctx):
if self.lavalink_connection_aborted:
msg = _("Connection to Lavalink node has failed")
desc = EmptyEmbed
desc = None
if await self.bot.is_owner(ctx.author):
desc = _("Please check your console or logs for details.")
return await self.send_embed_msg(ctx, title=msg, description=desc)
@@ -610,7 +609,7 @@ class PlayerCommands(MixinMeta, metaclass=CompositeMetaClass):
except DatabaseError:
notify_channel = player.fetch("notify_channel")
if notify_channel:
notify_channel = ctx.guild.get_channel(notify_channel)
notify_channel = ctx.guild.get_channel_or_thread(notify_channel)
await self.send_embed_msg(notify_channel, title=_("Couldn't get a valid track."))
return
except TrackEnqueueError:
@@ -636,7 +635,8 @@ class PlayerCommands(MixinMeta, metaclass=CompositeMetaClass):
@commands.command(name="search")
@commands.guild_only()
@commands.bot_has_permissions(embed_links=True, add_reactions=True)
@commands.bot_has_permissions(embed_links=True)
@commands.bot_can_react()
async def command_search(self, ctx: commands.Context, *, query: str):
"""Pick a track with a search.
@@ -678,7 +678,7 @@ class PlayerCommands(MixinMeta, metaclass=CompositeMetaClass):
if not self._player_check(ctx):
if self.lavalink_connection_aborted:
msg = _("Connection to Lavalink has failed")
desc = EmptyEmbed
desc = None
if await self.bot.is_owner(ctx.author):
desc = _("Please check your console or logs for details.")
return await self.send_embed_msg(ctx, title=msg, description=desc)

View File

@@ -38,7 +38,8 @@ _ = Translator("Audio", Path(__file__))
class PlaylistCommands(MixinMeta, metaclass=CompositeMetaClass):
@commands.group(name="playlist")
@commands.guild_only()
@commands.bot_has_permissions(embed_links=True, add_reactions=True)
@commands.bot_has_permissions(embed_links=True)
@commands.bot_can_react()
async def command_playlist(self, ctx: commands.Context):
"""Playlist configuration options.
@@ -263,9 +264,7 @@ class PlaylistCommands(MixinMeta, metaclass=CompositeMetaClass):
ctx,
title=_("Playlists Are Not Available"),
description=_("The playlist section of Audio is currently unavailable"),
footer=discord.Embed.Empty
if not await self.bot.is_owner(ctx.author)
else _("Check your logs."),
footer=None if not await self.bot.is_owner(ctx.author) else _("Check your logs."),
)
if scope_data is None:
scope_data = [
@@ -392,9 +391,7 @@ class PlaylistCommands(MixinMeta, metaclass=CompositeMetaClass):
ctx,
title=_("Playlists Are Not Available"),
description=_("The playlist section of Audio is currently unavailable"),
footer=discord.Embed.Empty
if not await self.bot.is_owner(ctx.author)
else _("Check your logs."),
footer=None if not await self.bot.is_owner(ctx.author) else _("Check your logs."),
)
if scope_data is None:
scope_data = [None, ctx.author, ctx.guild, False]
@@ -471,9 +468,7 @@ class PlaylistCommands(MixinMeta, metaclass=CompositeMetaClass):
ctx,
title=_("Playlists Are Not Available"),
description=_("The playlist section of Audio is currently unavailable"),
footer=discord.Embed.Empty
if not await self.bot.is_owner(ctx.author)
else _("Check your logs."),
footer=None if not await self.bot.is_owner(ctx.author) else _("Check your logs."),
)
if scope_data is None:
scope_data = [None, ctx.author, ctx.guild, False]
@@ -561,9 +556,7 @@ class PlaylistCommands(MixinMeta, metaclass=CompositeMetaClass):
ctx,
title=_("Playlists Are Not Available"),
description=_("The playlist section of Audio is currently unavailable"),
footer=discord.Embed.Empty
if not await self.bot.is_owner(ctx.author)
else _("Check your logs."),
footer=None if not await self.bot.is_owner(ctx.author) else _("Check your logs."),
)
async with ctx.typing():
if scope_data is None:
@@ -696,9 +689,7 @@ class PlaylistCommands(MixinMeta, metaclass=CompositeMetaClass):
ctx,
title=_("Playlists Are Not Available"),
description=_("The playlist section of Audio is currently unavailable"),
footer=discord.Embed.Empty
if not await self.bot.is_owner(ctx.author)
else _("Check your logs."),
footer=None if not await self.bot.is_owner(ctx.author) else _("Check your logs."),
)
if scope_data is None:
scope_data = [None, ctx.author, ctx.guild, False]
@@ -829,9 +820,7 @@ class PlaylistCommands(MixinMeta, metaclass=CompositeMetaClass):
ctx,
title=_("Playlists Are Not Available"),
description=_("The playlist section of Audio is currently unavailable"),
footer=discord.Embed.Empty
if not await self.bot.is_owner(ctx.author)
else _("Check your logs."),
footer=None if not await self.bot.is_owner(ctx.author) else _("Check your logs."),
)
if scope_data is None:
scope_data = [None, ctx.author, ctx.guild, False]
@@ -952,9 +941,7 @@ class PlaylistCommands(MixinMeta, metaclass=CompositeMetaClass):
ctx,
title=_("Playlists Are Not Available"),
description=_("The playlist section of Audio is currently unavailable"),
footer=discord.Embed.Empty
if not await self.bot.is_owner(ctx.author)
else _("Check your logs."),
footer=None if not await self.bot.is_owner(ctx.author) else _("Check your logs."),
)
if scope_data is None:
scope_data = [None, ctx.author, ctx.guild, False]
@@ -1107,9 +1094,7 @@ class PlaylistCommands(MixinMeta, metaclass=CompositeMetaClass):
ctx,
title=_("Playlists Are Not Available"),
description=_("The playlist section of Audio is currently unavailable"),
footer=discord.Embed.Empty
if not await self.bot.is_owner(ctx.author)
else _("Check your logs."),
footer=None if not await self.bot.is_owner(ctx.author) else _("Check your logs."),
)
async with ctx.typing():
if scope_data is None:
@@ -1217,9 +1202,7 @@ class PlaylistCommands(MixinMeta, metaclass=CompositeMetaClass):
ctx,
title=_("Playlists Are Not Available"),
description=_("The playlist section of Audio is currently unavailable"),
footer=discord.Embed.Empty
if not await self.bot.is_owner(ctx.author)
else _("Check your logs."),
footer=None if not await self.bot.is_owner(ctx.author) else _("Check your logs."),
)
if scope_data is None:
scope_data = [None, ctx.author, ctx.guild, False]
@@ -1335,9 +1318,7 @@ class PlaylistCommands(MixinMeta, metaclass=CompositeMetaClass):
ctx,
title=_("Playlists Are Not Available"),
description=_("The playlist section of Audio is currently unavailable"),
footer=discord.Embed.Empty
if not await self.bot.is_owner(ctx.author)
else _("Check your logs."),
footer=None if not await self.bot.is_owner(ctx.author) else _("Check your logs."),
)
if scope_data is None:
scope_data = [None, ctx.author, ctx.guild, False]
@@ -1461,9 +1442,7 @@ class PlaylistCommands(MixinMeta, metaclass=CompositeMetaClass):
ctx,
title=_("Playlists Are Not Available"),
description=_("The playlist section of Audio is currently unavailable"),
footer=discord.Embed.Empty
if not await self.bot.is_owner(ctx.author)
else _("Check your logs."),
footer=None if not await self.bot.is_owner(ctx.author) else _("Check your logs."),
)
if scope_data is None:
scope_data = [None, ctx.author, ctx.guild, False]
@@ -1639,9 +1618,7 @@ class PlaylistCommands(MixinMeta, metaclass=CompositeMetaClass):
ctx,
title=_("Playlists Are Not Available"),
description=_("The playlist section of Audio is currently unavailable"),
footer=discord.Embed.Empty
if not await self.bot.is_owner(ctx.author)
else _("Check your logs."),
footer=None if not await self.bot.is_owner(ctx.author) else _("Check your logs."),
)
if scope_data is None:
scope_data = [None, ctx.author, ctx.guild, False]
@@ -1810,9 +1787,7 @@ class PlaylistCommands(MixinMeta, metaclass=CompositeMetaClass):
ctx,
title=_("Playlists Are Not Available"),
description=_("The playlist section of Audio is currently unavailable"),
footer=discord.Embed.Empty
if not await self.bot.is_owner(ctx.author)
else _("Check your logs."),
footer=None if not await self.bot.is_owner(ctx.author) else _("Check your logs."),
)
if scope_data is None:
scope_data = [None, ctx.author, ctx.guild, False]
@@ -1976,9 +1951,7 @@ class PlaylistCommands(MixinMeta, metaclass=CompositeMetaClass):
ctx,
title=_("Playlists Are Not Available"),
description=_("The playlist section of Audio is currently unavailable"),
footer=discord.Embed.Empty
if not await self.bot.is_owner(ctx.author)
else _("Check your logs."),
footer=None if not await self.bot.is_owner(ctx.author) else _("Check your logs."),
)
if scope_data is None:
scope_data = [None, ctx.author, ctx.guild, False]

View File

@@ -33,7 +33,8 @@ _ = Translator("Audio", Path(__file__))
class QueueCommands(MixinMeta, metaclass=CompositeMetaClass):
@commands.group(name="queue", invoke_without_command=True)
@commands.guild_only()
@commands.bot_has_permissions(embed_links=True, add_reactions=True)
@commands.bot_has_permissions(embed_links=True)
@commands.bot_can_react()
async def command_queue(self, ctx: commands.Context, *, page: int = 1):
"""List the songs in the queue."""

View File

@@ -197,7 +197,7 @@ class AudioEvents(MixinMeta, metaclass=CompositeMetaClass):
):
if not guild:
return
notify_channel = guild.get_channel(player.fetch("notify_channel"))
notify_channel = guild.get_channel_or_thread(player.fetch("notify_channel"))
has_perms = self._has_notify_perms(notify_channel)
tries = 0
while not player._is_playing:

View File

@@ -18,6 +18,7 @@ from lavalink import NodeNotFound, PlayerNotFound
from redbot.core import commands
from redbot.core.i18n import Translator
from redbot.core.utils import can_user_send_messages_in
from redbot.core.utils.antispam import AntiSpam
from redbot.core.utils.chat_formatting import box, humanize_list, underline, bold
@@ -61,6 +62,16 @@ HUMANIZED_PERM = {
"manage_roles": _("Manage Roles"),
"manage_webhooks": _("Manage Webhooks"),
"manage_emojis": _("Manage Emojis"),
"use_slash_commands": _("Use Slash Commands"),
"request_to_speak": _("Request to Speak"),
"manage_events": _("Manage Events"),
"manage_threads": _("Manage Threads"),
"create_public_threads": _("Create Public Threads"),
"create_private_threads": _("Create Private Threads"),
"external_stickers": _("Use External Stickers"),
"send_messages_in_threads": _("Send Messages in Threads"),
"start_embedded_activities": _("Start Activities"),
"moderate_members": _("Moderate Member"),
}
DANGEROUS_COMMANDS = {
@@ -175,13 +186,31 @@ class DpyEvents(MixinMeta, metaclass=CompositeMetaClass):
"Not running Audio command due to invalid machine architecture for the managed Lavalink node."
)
current_perms = ctx.channel.permissions_for(ctx.me)
surpass_ignore = (
isinstance(ctx.channel, discord.abc.PrivateChannel)
or await ctx.bot.is_owner(ctx.author)
or await ctx.bot.is_admin(ctx.author)
)
guild = ctx.guild
if guild and not can_user_send_messages_in(ctx.me, ctx.channel):
log.debug(
"Missing perms to send messages in %d, Owner ID: %d",
guild.id,
guild.owner.id,
)
if not surpass_ignore:
text = _(
"I'm missing permissions to send messages in this server. "
"Please address this as soon as possible."
)
log.info(
"Missing write permission in %d, Owner ID: %d",
guild.id,
guild.owner.id,
)
raise CheckFailure(message=text)
current_perms = ctx.channel.permissions_for(ctx.me)
if guild and not current_perms.is_superset(self.permission_cache):
current_perms_set = set(iter(current_perms))
expected_perms_set = set(iter(self.permission_cache))
@@ -207,14 +236,7 @@ class DpyEvents(MixinMeta, metaclass=CompositeMetaClass):
perm=_(HUMANIZED_PERM.get(perm, perm)),
)
text = text.strip()
if current_perms.send_messages and current_perms.read_messages:
await ctx.send(box(text=text, lang="ini"))
else:
log.info(
"Missing write permission in %s, Owner ID: %s",
ctx.guild.id,
ctx.guild.owner.id,
)
await ctx.send(box(text=text, lang="ini"))
raise CheckFailure(message=text)
with contextlib.suppress(Exception):
@@ -312,7 +334,7 @@ class DpyEvents(MixinMeta, metaclass=CompositeMetaClass):
)
if error.send_cmd_help:
await ctx.send_help()
elif isinstance(error, commands.ConversionFailure):
elif isinstance(error, commands.BadArgument):
handled = True
if error.args:
if match := RE_CONVERSION.search(error.args[0]):
@@ -390,10 +412,10 @@ class DpyEvents(MixinMeta, metaclass=CompositeMetaClass):
if not handled:
await self.bot.on_command_error(ctx, error, unhandled_by_cog=True)
def cog_unload(self) -> None:
async def cog_unload(self) -> None:
if not self.cog_cleaned_up:
self.bot.dispatch("red_audio_unload", self)
self.session.detach()
await self.session.close()
if self.player_automated_timer_task:
self.player_automated_timer_task.cancel()
@@ -408,10 +430,10 @@ class DpyEvents(MixinMeta, metaclass=CompositeMetaClass):
lavalink.unregister_event_listener(self.lavalink_event_handler)
lavalink.unregister_update_listener(self.lavalink_update_handler)
asyncio.create_task(lavalink.close(self.bot))
asyncio.create_task(self._close_database())
await lavalink.close(self.bot)
await self._close_database()
if self.managed_node_controller is not None:
asyncio.create_task(self.managed_node_controller.shutdown())
await self.managed_node_controller.shutdown()
self.cog_cleaned_up = True

View File

@@ -165,14 +165,14 @@ class LavalinkEvents(MixinMeta, metaclass=CompositeMetaClass):
try:
await self.api_interface.autoplay(player, self.playlist_api)
except DatabaseError:
notify_channel = guild.get_channel(notify_channel_id)
notify_channel = guild.get_channel_or_thread(notify_channel_id)
if notify_channel and self._has_notify_perms(notify_channel):
await self.send_embed_msg(
notify_channel, title=_("Couldn't get a valid track.")
)
return
except TrackEnqueueError:
notify_channel = guild.get_channel(notify_channel_id)
notify_channel = guild.get_channel_or_thread(notify_channel_id)
if notify_channel and self._has_notify_perms(notify_channel):
await self.send_embed_msg(
notify_channel,
@@ -185,7 +185,7 @@ class LavalinkEvents(MixinMeta, metaclass=CompositeMetaClass):
return
if event_type == lavalink.LavalinkEvents.TRACK_START and notify:
notify_channel_id = player.fetch("notify_channel")
notify_channel = guild.get_channel(notify_channel_id)
notify_channel = guild.get_channel_or_thread(notify_channel_id)
if notify_channel and self._has_notify_perms(notify_channel):
if player.fetch("notify_message") is not None:
with contextlib.suppress(discord.HTTPException):
@@ -226,7 +226,7 @@ class LavalinkEvents(MixinMeta, metaclass=CompositeMetaClass):
if event_type == lavalink.LavalinkEvents.QUEUE_END:
if not autoplay:
notify_channel_id = player.fetch("notify_channel")
notify_channel = guild.get_channel(notify_channel_id)
notify_channel = guild.get_channel_or_thread(notify_channel_id)
if notify_channel and notify and self._has_notify_perms(notify_channel):
await self.send_embed_msg(notify_channel, title=_("Queue ended."))
if disconnect:
@@ -282,7 +282,7 @@ class LavalinkEvents(MixinMeta, metaclass=CompositeMetaClass):
self._ll_guild_updates.discard(guild_id)
self.bot.dispatch("red_audio_audio_disconnect", guild)
if message_channel:
message_channel = guild.get_channel(message_channel)
message_channel = guild.get_channel_or_thread(message_channel)
if early_exit:
log.warning(
"Audio detected multiple continuous errors during playback "

View File

@@ -267,14 +267,14 @@ class StartUpTasks(MixinMeta, metaclass=CompositeMetaClass):
try:
await self.api_interface.autoplay(player, self.playlist_api)
except DatabaseError:
notify_channel = guild.get_channel(notify_channel)
notify_channel = guild.get_channel_or_thread(notify_channel)
if notify_channel:
await self.send_embed_msg(
notify_channel, title=_("Couldn't get a valid track.")
)
return
except TrackEnqueueError:
notify_channel = guild.get_channel(notify_channel)
notify_channel = guild.get_channel_or_thread(notify_channel)
if notify_channel:
await self.send_embed_msg(
notify_channel,

View File

@@ -9,7 +9,6 @@ import discord
import lavalink
from red_commons.logging import getLogger
from discord.embeds import EmptyEmbed
from lavalink import NodeNotFound
from redbot.core import commands
@@ -94,7 +93,7 @@ class FormattingUtilities(MixinMeta, metaclass=CompositeMetaClass):
if not self._player_check(ctx):
if self.lavalink_connection_aborted:
msg = _("Connection to Lavalink node has failed")
description = EmptyEmbed
description = None
if await self.bot.is_owner(ctx.author):
description = _("Please check your console or logs for details.")
return await self.send_embed_msg(ctx, title=msg, description=description)

View File

@@ -10,13 +10,12 @@ from typing import Any, Final, Mapping, MutableMapping, Pattern, Union, cast
import discord
import lavalink
from discord.embeds import EmptyEmbed
from red_commons.logging import getLogger
from redbot.core import bank, commands
from redbot.core.commands import Context
from redbot.core.i18n import Translator
from redbot.core.utils import AsyncIter
from redbot.core.utils import AsyncIter, can_user_send_messages_in
from redbot.core.utils.chat_formatting import humanize_number
from ...apis.playlist_interface import get_all_playlist_for_migration23
@@ -65,10 +64,10 @@ class MiscellaneousUtilities(MixinMeta, metaclass=CompositeMetaClass):
self, ctx: commands.Context, author: Mapping[str, str] = None, **kwargs
) -> discord.Message:
colour = kwargs.get("colour") or kwargs.get("color") or await self.bot.get_embed_color(ctx)
title = kwargs.get("title", EmptyEmbed) or EmptyEmbed
title = kwargs.get("title") or None
_type = kwargs.get("type", "rich") or "rich"
url = kwargs.get("url", EmptyEmbed) or EmptyEmbed
description = kwargs.get("description", EmptyEmbed) or EmptyEmbed
url = kwargs.get("url") or None
description = kwargs.get("description") or None
timestamp = kwargs.get("timestamp")
footer = kwargs.get("footer")
thumbnail = kwargs.get("thumbnail")
@@ -84,7 +83,6 @@ class MiscellaneousUtilities(MixinMeta, metaclass=CompositeMetaClass):
embed = discord.Embed.from_dict(contents)
embed.color = colour
if timestamp and isinstance(timestamp, datetime.datetime):
timestamp = timestamp.replace(tzinfo=datetime.timezone.utc)
embed.timestamp = timestamp
else:
embed.timestamp = datetime.datetime.now(tz=datetime.timezone.utc)
@@ -101,9 +99,9 @@ class MiscellaneousUtilities(MixinMeta, metaclass=CompositeMetaClass):
embed.set_author(name=name)
return await ctx.send(embed=embed)
def _has_notify_perms(self, channel: discord.TextChannel) -> bool:
def _has_notify_perms(self, channel: Union[discord.TextChannel, discord.Thread]) -> bool:
perms = channel.permissions_for(channel.guild.me)
return all((perms.send_messages, perms.embed_links))
return all((can_user_send_messages_in(channel.guild.me, channel), perms.embed_links))
async def maybe_run_pending_db_tasks(self, ctx: commands.Context) -> None:
if self.api_interface is not None:

View File

@@ -8,7 +8,6 @@ import discord
import lavalink
from red_commons.logging import getLogger
from discord.embeds import EmptyEmbed
from lavalink import NodeNotFound, PlayerNotFound
from redbot.core import commands
@@ -585,7 +584,7 @@ class PlayerUtilities(MixinMeta, metaclass=CompositeMetaClass):
except IndexError:
self.update_player_lock(ctx, False)
title = _("Nothing found")
desc = EmptyEmbed
desc = None
if await self.bot.is_owner(ctx.author):
desc = _("Please check your console or logs for details.")
return await self.send_embed_msg(ctx, title=title, description=desc)

View File

@@ -12,7 +12,6 @@ from typing import List, MutableMapping, Optional, Tuple, Union
import aiohttp
import discord
import lavalink
from discord.embeds import EmptyEmbed
from lavalink import NodeNotFound
from red_commons.logging import getLogger
@@ -525,7 +524,7 @@ class PlaylistUtilities(MixinMeta, metaclass=CompositeMetaClass):
if not self._player_check(ctx):
if self.lavalink_connection_aborted:
msg = _("Connection to Lavalink node has failed")
desc = EmptyEmbed
desc = None
if await self.bot.is_owner(ctx.author):
desc = _("Please check your console or logs for details.")
await self.send_embed_msg(ctx, title=msg, description=desc)

View File

@@ -60,7 +60,7 @@ class ValidationUtilities(MixinMeta, metaclass=CompositeMetaClass):
async def is_query_allowed(
self,
config: Config,
ctx_or_channel: Optional[Union[Context, discord.TextChannel]],
ctx_or_channel: Optional[Union[Context, discord.TextChannel, discord.Thread]],
query: str,
query_obj: Query,
) -> bool: