jack1142 febca8ccbb
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
2022-04-03 03:21:20 +02:00

561 lines
20 KiB
Python

import asyncio
import logging
from typing import Tuple
import discord
from redbot.core import Config, checks, commands
from redbot.core.i18n import Translator, cog_i18n
from redbot.core.utils.chat_formatting import box
from redbot.core.utils.predicates import MessagePredicate
from .announcer import Announcer
from .converters import SelfRole
log = logging.getLogger("red.admin")
T_ = Translator("Admin", __file__)
_ = lambda s: s
GENERIC_FORBIDDEN = _(
"I attempted to do something that Discord denied me permissions for."
" Your command failed to successfully complete."
)
HIERARCHY_ISSUE_ADD = _(
"I can not give {role.name} to {member.display_name}"
" because that role is higher than or equal to my highest role"
" in the Discord hierarchy."
)
HIERARCHY_ISSUE_REMOVE = _(
"I can not remove {role.name} from {member.display_name}"
" because that role is higher than or equal to my highest role"
" in the Discord hierarchy."
)
ROLE_HIERARCHY_ISSUE = _(
"I can not edit {role.name}"
" because that role is higher than my or equal to highest role"
" in the Discord hierarchy."
)
USER_HIERARCHY_ISSUE_ADD = _(
"I can not let you give {role.name} to {member.display_name}"
" because that role is higher than or equal to your highest role"
" in the Discord hierarchy."
)
USER_HIERARCHY_ISSUE_REMOVE = _(
"I can not let you remove {role.name} from {member.display_name}"
" because that role is higher than or equal to your highest role"
" in the Discord hierarchy."
)
ROLE_USER_HIERARCHY_ISSUE = _(
"I can not let you edit {role.name}"
" because that role is higher than or equal to your highest role"
" in the Discord hierarchy."
)
NEED_MANAGE_ROLES = _('I need the "Manage Roles" permission to do that.')
RUNNING_ANNOUNCEMENT = _(
"I am already announcing something. If you would like to make a"
" different announcement please use `{prefix}announce cancel`"
" first."
)
_ = T_
@cog_i18n(_)
class Admin(commands.Cog):
"""A collection of server administration utilities."""
def __init__(self, bot):
self.bot = bot
self.config = Config.get_conf(self, 8237492837454039, force_registration=True)
self.config.register_global(serverlocked=False, schema_version=0)
self.config.register_guild(
announce_channel=None, # Integer ID
selfroles=[], # List of integer ID's
)
self.__current_announcer = None
async def cog_load(self) -> None:
await self.handle_migrations()
async def red_delete_data_for_user(self, **kwargs):
"""Nothing to delete"""
return
async def handle_migrations(self):
lock = self.config.get_guilds_lock()
async with lock:
# This prevents the edge case of someone loading admin,
# unloading it, loading it again during a migration
current_schema = await self.config.schema_version()
if current_schema == 0:
await self.migrate_config_from_0_to_1()
await self.config.schema_version.set(1)
async def migrate_config_from_0_to_1(self) -> None:
all_guilds = await self.config.all_guilds()
for guild_id, guild_data in all_guilds.items():
if guild_data.get("announce_ignore", False):
async with self.config.guild_from_id(guild_id).all(
acquire_lock=False
) as guild_config:
guild_config.pop("announce_channel", None)
guild_config.pop("announce_ignore", None)
def cog_unload(self):
try:
self.__current_announcer.cancel()
except AttributeError:
pass
def is_announcing(self) -> bool:
"""
Is the bot currently announcing something?
:return:
"""
if self.__current_announcer is None:
return False
return self.__current_announcer.active or False
@staticmethod
def pass_hierarchy_check(ctx: commands.Context, role: discord.Role) -> bool:
"""
Determines if the bot has a higher role than the given one.
:param ctx:
:param role: Role object.
:return:
"""
return ctx.guild.me.top_role > role
@staticmethod
def pass_user_hierarchy_check(ctx: commands.Context, role: discord.Role) -> bool:
"""
Determines if a user is allowed to add/remove/edit the given role.
:param ctx:
:param role:
:return:
"""
return ctx.author.top_role > role or ctx.author == ctx.guild.owner
async def _addrole(
self, ctx: commands.Context, member: discord.Member, role: discord.Role, *, check_user=True
):
if role in member.roles:
await ctx.send(
_("{member.display_name} already has the role {role.name}.").format(
role=role, member=member
)
)
return
if check_user and not self.pass_user_hierarchy_check(ctx, role):
await ctx.send(_(USER_HIERARCHY_ISSUE_ADD).format(role=role, member=member))
return
if not self.pass_hierarchy_check(ctx, role):
await ctx.send(_(HIERARCHY_ISSUE_ADD).format(role=role, member=member))
return
if not ctx.guild.me.guild_permissions.manage_roles:
await ctx.send(_(NEED_MANAGE_ROLES))
return
try:
await member.add_roles(role)
except discord.Forbidden:
await ctx.send(_(GENERIC_FORBIDDEN))
else:
await ctx.send(
_("I successfully added {role.name} to {member.display_name}").format(
role=role, member=member
)
)
async def _removerole(
self, ctx: commands.Context, member: discord.Member, role: discord.Role, *, check_user=True
):
if role not in member.roles:
await ctx.send(
_("{member.display_name} does not have the role {role.name}.").format(
role=role, member=member
)
)
return
if check_user and not self.pass_user_hierarchy_check(ctx, role):
await ctx.send(_(USER_HIERARCHY_ISSUE_REMOVE).format(role=role, member=member))
return
if not self.pass_hierarchy_check(ctx, role):
await ctx.send(_(HIERARCHY_ISSUE_REMOVE).format(role=role, member=member))
return
if not ctx.guild.me.guild_permissions.manage_roles:
await ctx.send(_(NEED_MANAGE_ROLES))
return
try:
await member.remove_roles(role)
except discord.Forbidden:
await ctx.send(_(GENERIC_FORBIDDEN))
else:
await ctx.send(
_("I successfully removed {role.name} from {member.display_name}").format(
role=role, member=member
)
)
@commands.command()
@commands.guild_only()
@checks.admin_or_permissions(manage_roles=True)
async def addrole(
self, ctx: commands.Context, rolename: discord.Role, *, user: discord.Member = None
):
"""
Add a role to a user.
Use double quotes if the role contains spaces.
If user is left blank it defaults to the author of the command.
"""
if user is None:
user = ctx.author
await self._addrole(ctx, user, rolename)
@commands.command()
@commands.guild_only()
@checks.admin_or_permissions(manage_roles=True)
async def removerole(
self, ctx: commands.Context, rolename: discord.Role, *, user: discord.Member = None
):
"""
Remove a role from a user.
Use double quotes if the role contains spaces.
If user is left blank it defaults to the author of the command.
"""
if user is None:
user = ctx.author
await self._removerole(ctx, user, rolename)
@commands.group()
@commands.guild_only()
@checks.admin_or_permissions(manage_roles=True)
async def editrole(self, ctx: commands.Context):
"""Edit role settings."""
pass
@editrole.command(name="colour", aliases=["color"])
async def editrole_colour(
self, ctx: commands.Context, role: discord.Role, value: discord.Colour
):
"""
Edit a role's colour.
Use double quotes if the role contains spaces.
Colour must be in hexadecimal format.
[Online colour picker](http://www.w3schools.com/colors/colors_picker.asp)
Examples:
`[p]editrole colour "The Transistor" #ff0000`
`[p]editrole colour Test #ff9900`
"""
author = ctx.author
reason = "{}({}) changed the colour of role '{}'".format(author.name, author.id, role.name)
if not self.pass_user_hierarchy_check(ctx, role):
await ctx.send(_(ROLE_USER_HIERARCHY_ISSUE).format(role=role))
return
if not self.pass_hierarchy_check(ctx, role):
await ctx.send(_(ROLE_HIERARCHY_ISSUE).format(role=role))
return
if not ctx.guild.me.guild_permissions.manage_roles:
await ctx.send(_(NEED_MANAGE_ROLES))
return
try:
await role.edit(reason=reason, color=value)
except discord.Forbidden:
await ctx.send(_(GENERIC_FORBIDDEN))
else:
log.info(reason)
await ctx.send(_("Done."))
@editrole.command(name="name")
async def edit_role_name(self, ctx: commands.Context, role: discord.Role, name: str):
"""
Edit a role's name.
Use double quotes if the role or the name contain spaces.
Example:
`[p]editrole name \"The Transistor\" Test`
"""
author = ctx.message.author
old_name = role.name
reason = "{}({}) changed the name of role '{}' to '{}'".format(
author.name, author.id, old_name, name
)
if not self.pass_user_hierarchy_check(ctx, role):
await ctx.send(_(ROLE_USER_HIERARCHY_ISSUE).format(role=role))
return
if not self.pass_hierarchy_check(ctx, role):
await ctx.send(_(ROLE_HIERARCHY_ISSUE).format(role=role))
return
if not ctx.guild.me.guild_permissions.manage_roles:
await ctx.send(_(NEED_MANAGE_ROLES))
return
try:
await role.edit(reason=reason, name=name)
except discord.Forbidden:
await ctx.send(_(GENERIC_FORBIDDEN))
else:
log.info(reason)
await ctx.send(_("Done."))
@commands.group(invoke_without_command=True)
@checks.is_owner()
async def announce(self, ctx: commands.Context, *, message: str):
"""Announce a message to all servers the bot is in."""
if not self.is_announcing():
announcer = Announcer(ctx, message, config=self.config)
announcer.start()
self.__current_announcer = announcer
await ctx.send(_("The announcement has begun."))
else:
prefix = ctx.clean_prefix
await ctx.send(_(RUNNING_ANNOUNCEMENT).format(prefix=prefix))
@announce.command(name="cancel")
async def announce_cancel(self, ctx):
"""Cancel a running announce."""
if not self.is_announcing():
await ctx.send(_("There is no currently running announcement."))
return
self.__current_announcer.cancel()
await ctx.send(_("The current announcement has been cancelled."))
@commands.group()
@commands.guild_only()
@checks.guildowner_or_permissions(administrator=True)
async def announceset(self, ctx):
"""Change how announcements are sent in this guild."""
pass
@announceset.command(name="channel")
async def announceset_channel(self, ctx, *, channel: discord.TextChannel):
"""Change the channel where the bot will send announcements."""
await self.config.guild(ctx.guild).announce_channel.set(channel.id)
await ctx.send(
_("The announcement channel has been set to {channel.mention}").format(channel=channel)
)
@announceset.command(name="clearchannel")
async def announceset_clear_channel(self, ctx):
"""Unsets the channel for announcements."""
await self.config.guild(ctx.guild).announce_channel.clear()
await ctx.tick()
async def _valid_selfroles(self, guild: discord.Guild) -> Tuple[discord.Role]:
"""
Returns a tuple of valid selfroles
:param guild:
:return:
"""
selfrole_ids = set(await self.config.guild(guild).selfroles())
guild_roles = guild.roles
valid_roles = tuple(r for r in guild_roles if r.id in selfrole_ids)
valid_role_ids = set(r.id for r in valid_roles)
if selfrole_ids != valid_role_ids:
await self.config.guild(guild).selfroles.set(list(valid_role_ids))
# noinspection PyTypeChecker
return valid_roles
@commands.guild_only()
@commands.group(invoke_without_command=True)
async def selfrole(self, ctx: commands.Context, *, selfrole: SelfRole):
"""
Add or remove a selfrole from yourself.
Server admins must have configured the role as user settable.
NOTE: The role is case sensitive!
"""
if selfrole in ctx.author.roles:
return await self._removerole(ctx, ctx.author, selfrole, check_user=False)
else:
return await self._addrole(ctx, ctx.author, selfrole, check_user=False)
@selfrole.command(name="add", hidden=True)
async def selfrole_add(self, ctx: commands.Context, *, selfrole: SelfRole):
"""
Add a selfrole to yourself.
Server admins must have configured the role as user settable.
NOTE: The role is case sensitive!
"""
# noinspection PyTypeChecker
await self._addrole(ctx, ctx.author, selfrole, check_user=False)
@selfrole.command(name="remove", hidden=True)
async def selfrole_remove(self, ctx: commands.Context, *, selfrole: SelfRole):
"""
Remove a selfrole from yourself.
Server admins must have configured the role as user settable.
NOTE: The role is case sensitive!
"""
# noinspection PyTypeChecker
await self._removerole(ctx, ctx.author, selfrole, check_user=False)
@selfrole.command(name="list")
async def selfrole_list(self, ctx: commands.Context):
"""
Lists all available selfroles.
"""
selfroles = await self._valid_selfroles(ctx.guild)
fmt_selfroles = "\n".join(["+ " + r.name for r in selfroles])
if not fmt_selfroles:
await ctx.send("There are currently no selfroles.")
return
msg = _("Available Selfroles:\n{selfroles}").format(selfroles=fmt_selfroles)
await ctx.send(box(msg, "diff"))
@commands.group()
@checks.admin_or_permissions(manage_roles=True)
async def selfroleset(self, ctx: commands.Context):
"""Manage selfroles."""
pass
@selfroleset.command(name="add")
async def selfroleset_add(self, ctx: commands.Context, *roles: discord.Role):
"""
Add a role, or a selection of roles, to the list of available selfroles.
NOTE: The role is case sensitive!
"""
current_selfroles = await self.config.guild(ctx.guild).selfroles()
for role in roles:
if not self.pass_user_hierarchy_check(ctx, role):
await ctx.send(
_(
"I cannot let you add {role.name} as a selfrole because that role is"
" higher than or equal to your highest role in the Discord hierarchy."
).format(role=role)
)
return
if role.id not in current_selfroles:
current_selfroles.append(role.id)
else:
await ctx.send(
_('The role "{role.name}" is already a selfrole.').format(role=role)
)
return
await self.config.guild(ctx.guild).selfroles.set(current_selfroles)
if (count := len(roles)) > 1:
message = _("Added {count} selfroles.").format(count=count)
else:
message = _("Added 1 selfrole.")
await ctx.send(message)
@selfroleset.command(name="remove")
async def selfroleset_remove(self, ctx: commands.Context, *roles: SelfRole):
"""
Remove a role, or a selection of roles, from the list of available selfroles.
NOTE: The role is case sensitive!
"""
current_selfroles = await self.config.guild(ctx.guild).selfroles()
for role in roles:
if not self.pass_user_hierarchy_check(ctx, role):
await ctx.send(
_(
"I cannot let you remove {role.name} from being a selfrole because that role is higher than or equal to your highest role in the Discord hierarchy."
).format(role=role)
)
return
current_selfroles.remove(role.id)
await self.config.guild(ctx.guild).selfroles.set(current_selfroles)
if (count := len(roles)) > 1:
message = _("Removed {count} selfroles.").format(count=count)
else:
message = _("Removed 1 selfrole.")
await ctx.send(message)
@selfroleset.command(name="clear")
async def selfroleset_clear(self, ctx: commands.Context):
"""Clear the list of available selfroles for this server."""
current_selfroles = await self.config.guild(ctx.guild).selfroles()
if not current_selfroles:
return await ctx.send(_("There are currently no selfroles."))
await ctx.send(
_("Are you sure you want to clear this server's selfrole list?") + " (yes/no)"
)
try:
pred = MessagePredicate.yes_or_no(ctx, user=ctx.author)
await ctx.bot.wait_for("message", check=pred, timeout=60)
except asyncio.TimeoutError:
await ctx.send(_("You took too long to respond."))
return
if pred.result:
for role in current_selfroles:
role = ctx.guild.get_role(role)
if role is None:
continue
if not self.pass_user_hierarchy_check(ctx, role):
await ctx.send(
_(
"I cannot clear the selfroles because the selfrole '{role.name}' is higher than or equal to your highest role in the Discord hierarchy."
).format(role=role)
)
return
await self.config.guild(ctx.guild).selfroles.clear()
await ctx.send(_("Selfrole list cleared."))
else:
await ctx.send(_("No changes have been made."))
@commands.command()
@checks.is_owner()
async def serverlock(self, ctx: commands.Context):
"""Lock a bot to its current servers only."""
serverlocked = await self.config.serverlocked()
await self.config.serverlocked.set(not serverlocked)
if serverlocked:
await ctx.send(_("The bot is no longer serverlocked."))
else:
await ctx.send(_("The bot is now serverlocked."))
# region Event Handlers
@commands.Cog.listener()
async def on_guild_join(self, guild: discord.Guild):
if await self.config.serverlocked():
if len(self.bot.guilds) == 1: # will be 0 once left
log.warning(
f"Leaving guild '{guild.name}' ({guild.id}) due to serverlock. You can "
"temporarily disable serverlock by starting up the bot with the --no-cogs flag."
)
else:
log.info(f"Leaving guild '{guild.name}' ({guild.id}) due to serverlock.")
await guild.leave()
# endregion