Black reformat.

This commit is contained in:
Sydney 2023-05-04 15:25:17 -04:00
parent 66bf686eec
commit 4b47440411
No known key found for this signature in database
GPG key ID: 6E62B942078EC9A2
23 changed files with 75 additions and 246 deletions

View file

@ -10,4 +10,4 @@ jobs:
- name: Black Code Formatter - name: Black Code Formatter
uses: lgeiger/black-action@v1.0.1 uses: lgeiger/black-action@v1.0.1
with: with:
args: "--line-length 120 --target-version py38 --check ." args: "--line-length 120 --target-version py310 --check ."

View file

@ -145,12 +145,10 @@ class Confession(commands.Cog):
await menu(ctx, pages=embeds, controls=SELECT_CONTROLS, message=None, page=0, timeout=20) await menu(ctx, pages=embeds, controls=SELECT_CONTROLS, message=None, page=0, timeout=20)
async def selected_guild(self, ctx, user_guilds, confession, page): async def selected_guild(self, ctx, user_guilds, confession, page):
confession_guild = user_guilds[page] confession_guild = user_guilds[page]
await self.send_confession(ctx, confession_guild, confession) await self.send_confession(ctx, confession_guild, confession)
async def send_confession(self, ctx, confession_guild: discord.Guild, confession: str): async def send_confession(self, ctx, confession_guild: discord.Guild, confession: str):
confession_room = await self.config.guild(confession_guild).confession_room() confession_room = await self.config.guild(confession_guild).confession_room()
confession_room = confession_guild.get_channel(confession_room) confession_room = confession_guild.get_channel(confession_room)

View file

@ -47,7 +47,6 @@ class CostManager(commands.Cog):
# permission hook checker for cost of command # permission hook checker for cost of command
async def cost_checker(self, ctx): async def cost_checker(self, ctx):
cost = await self.get_cost(ctx) cost = await self.get_cost(ctx)
if cost == 0: if cost == 0:

View file

@ -10,7 +10,6 @@ MessagePredicate = Callable[[discord.Message], bool]
class RecentActivityRecord: class RecentActivityRecord:
__slots__ = ("activities", "messages") __slots__ = ("activities", "messages")
def __init__(self): def __init__(self):
@ -32,7 +31,6 @@ class RecentActivityRecord:
after: Optional[datetime] = None, after: Optional[datetime] = None,
message_check: Optional[MessagePredicate] = None, message_check: Optional[MessagePredicate] = None,
) -> List[Union[datetime, discord.Message]]: ) -> List[Union[datetime, discord.Message]]:
ret: List[Union[datetime, discord.Message]] = [] ret: List[Union[datetime, discord.Message]] = []
for a in self.activities: for a in self.activities:
@ -57,7 +55,6 @@ class RecentActivityRecord:
after: Optional[datetime] = None, after: Optional[datetime] = None,
message_check: Optional[MessagePredicate] = None, message_check: Optional[MessagePredicate] = None,
) -> int: ) -> int:
ret = len(self._filter(after=after, message_check=message_check)) ret = len(self._filter(after=after, message_check=message_check))
return ret return ret
@ -84,14 +81,12 @@ RecordDict = Dict[discord.Guild, Dict[discord.Member, RecentActivityRecord]]
class RecordHandler: class RecordHandler:
__slots__ = ("records",) __slots__ = ("records",)
def __init__(self): def __init__(self):
self.records: RecordDict = {} self.records: RecordDict = {}
def proccess_message(self, message): def proccess_message(self, message):
try: try:
member = message.author member = message.author
guild = member.guild guild = member.guild
@ -115,7 +110,6 @@ class RecordHandler:
after: datetime, after: datetime,
message_check: Optional[MessagePredicate] = None, message_check: Optional[MessagePredicate] = None,
) -> Iterator[discord.Member]: ) -> Iterator[discord.Member]:
with contextlib.suppress(KeyError): with contextlib.suppress(KeyError):
for member, rec in self.records[guild].items(): for member, rec in self.records[guild].items():
if rec.conditional_count(after=after, message_check=message_check): if rec.conditional_count(after=after, message_check=message_check):

View file

@ -19,7 +19,6 @@ configable_guild_defaults = {
def settings_converter(user_input: str) -> dict: def settings_converter(user_input: str) -> dict:
if user_input.startswith("```") and user_input.endswith("```"): if user_input.startswith("```") and user_input.endswith("```"):
user_input = "\n".join(user_input.split("\n")[1:-1]) user_input = "\n".join(user_input.split("\n")[1:-1])

View file

@ -56,7 +56,6 @@ class EconomyTrickle(commands.Cog):
self.recordhandler.proccess_message(message) self.recordhandler.proccess_message(message)
async def main_loop(self): async def main_loop(self):
minutes = defaultdict(int) minutes = defaultdict(int)
while self is self.bot.get_cog(self.__class__.__name__): while self is self.bot.get_cog(self.__class__.__name__):
@ -74,7 +73,6 @@ class EconomyTrickle(commands.Cog):
self.extra_tasks.append(tsk) self.extra_tasks.append(tsk)
async def do_rewards_for(self, guild: discord.Guild, now: datetime, data: dict): async def do_rewards_for(self, guild: discord.Guild, now: datetime, data: dict):
after = now - timedelta(minutes=data["interval"], seconds=10) after = now - timedelta(minutes=data["interval"], seconds=10)
voice_mem = await self.config.guild(guild).min_voice_members() voice_mem = await self.config.guild(guild).min_voice_members()
if data["mode"] == "blacklist": if data["mode"] == "blacklist":

View file

@ -8,6 +8,7 @@ from PIL import Image as PILImage
MAX_SIZE = 8 * 1024 * 1024 MAX_SIZE = 8 * 1024 * 1024
# by Flame442 # by Flame442
class ImageFindError(Exception): class ImageFindError(Exception):
"""Generic error for the __get_image function.""" """Generic error for the __get_image function."""
@ -19,9 +20,7 @@ class ImageMagic(commands.Cog):
def __init__(self, bot): def __init__(self, bot):
super().__init__() super().__init__()
self.config = Config.get_conf( self.config = Config.get_conf(self, identifier=4928034571, force_registration=True)
self, identifier=4928034571, force_registration=True
)
self.bot = bot self.bot = bot
async def _get_image(self, ctx, link: str = None) -> Image: async def _get_image(self, ctx, link: str = None) -> Image:
@ -36,9 +35,7 @@ class ImageMagic(commands.Cog):
if ctx.message.reference: if ctx.message.reference:
msg = ctx.message.reference.resolved msg = ctx.message.reference.resolved
if msg is None: if msg is None:
msg = await ctx.channel.fetch_message( msg = await ctx.channel.fetch_message(ctx.message.reference.message_id)
ctx.message.reference.message_id
)
if msg and msg.attachments: if msg and msg.attachments:
for a in msg.attachments: for a in msg.attachments:
path = urllib.parse.urlparse(a.url).path path = urllib.parse.urlparse(a.url).path
@ -66,9 +63,7 @@ class ImageMagic(commands.Cog):
except: except:
raise ImageFindError("Invalid filetype") raise ImageFindError("Invalid filetype")
except (OSError, aiohttp.ClientError): except (OSError, aiohttp.ClientError):
raise ImageFindError( raise ImageFindError("An image could not be found. Make sure you provide a direct link.")
"An image could not be found. Make sure you provide a direct link."
)
else: # attached image else: # attached image
path = urllib.parse.urlparse(ctx.message.attachments[0].url).path path = urllib.parse.urlparse(ctx.message.attachments[0].url).path
if ctx.message.attachments[0].size > max_filesize: if ctx.message.attachments[0].size > max_filesize:
@ -165,9 +160,7 @@ class ImageMagic(commands.Cog):
return return
try: try:
await ctx.reply( await ctx.reply(file=discord.File(BytesIO(img.make_blob()), name), mention_author=False)
file=discord.File(BytesIO(img.make_blob()), name), mention_author=False
)
except discord.errors.HTTPException: except discord.errors.HTTPException:
await ctx.reply("That image is too large.", mention_author=False) await ctx.reply("That image is too large.", mention_author=False)
return return
@ -236,9 +229,7 @@ class ImageMagic(commands.Cog):
except ImageFindError as e: except ImageFindError as e:
return await ctx.reply(e, mention_author=False) return await ctx.reply(e, mention_author=False)
await self._command_body( await self._command_body(ctx, args=(self._distortion, img, "implode", (amount * intensity,)))
ctx, args=(self._distortion, img, "implode", (amount * intensity,))
)
@distort.command() @distort.command()
async def swirl(self, ctx, intensity: Optional[float] = 10, *, link: str = None): async def swirl(self, ctx, intensity: Optional[float] = 10, *, link: str = None):
@ -267,9 +258,7 @@ class ImageMagic(commands.Cog):
except ImageFindError as e: except ImageFindError as e:
return await ctx.reply(e, mention_author=False) return await ctx.reply(e, mention_author=False)
await self._command_body( await self._command_body(ctx, args=(self._distortion, img, "swirl", (intensity,)))
ctx, args=(self._distortion, img, "swirl", (intensity,))
)
@distort.command() @distort.command()
async def charcoal(self, ctx, intensity: Optional[float], *, link: str = None): async def charcoal(self, ctx, intensity: Optional[float], *, link: str = None):
@ -283,9 +272,7 @@ class ImageMagic(commands.Cog):
except ImageFindError as e: except ImageFindError as e:
return await ctx.reply(e, mention_author=False) return await ctx.reply(e, mention_author=False)
await self._command_body( await self._command_body(ctx, args=(self._distortion, img, "charcoal", (1.5, 0.5)))
ctx, args=(self._distortion, img, "charcoal", (1.5, 0.5))
)
@distort.command() @distort.command()
async def sketch(self, ctx, intensity: Optional[float], *, link: str = None): async def sketch(self, ctx, intensity: Optional[float], *, link: str = None):
@ -299,9 +286,7 @@ class ImageMagic(commands.Cog):
except ImageFindError as e: except ImageFindError as e:
return await ctx.reply(e, mention_author=False) return await ctx.reply(e, mention_author=False)
await self._command_body( await self._command_body(ctx, args=(self._distortion, img, "sketch", (0.5, 0.0, 98.0)))
ctx, args=(self._distortion, img, "sketch", (0.5, 0.0, 98.0))
)
@distort.command() @distort.command()
async def zoom(self, ctx, intensity: Optional[float], *, link: str = None): async def zoom(self, ctx, intensity: Optional[float], *, link: str = None):

View file

@ -432,7 +432,6 @@ class Isolate(commands.Cog):
await self.bot.request_offline_members(guild) await self.bot.request_offline_members(guild)
for member_id, member_data in isolated.items(): for member_id, member_data in isolated.items():
member = guild.get_member(member_id) member = guild.get_member(member_id)
if not member: if not member:
@ -859,7 +858,6 @@ class Isolate(commands.Cog):
isolated = await self.config.guild(guild).ISOLATED() isolated = await self.config.guild(guild).ISOLATED()
for member_id, data in isolated.items(): for member_id, data in isolated.items():
until = data["until"] until = data["until"]
member = guild.get_member(int(member_id)) member = guild.get_member(int(member_id))
@ -1252,7 +1250,6 @@ class Isolate(commands.Cog):
await self.cancel_queue_event(member.guild.id, member.id) await self.cancel_queue_event(member.guild.id, member.id)
if apply_roles: if apply_roles:
# readd removed roles from user, by replacing user's roles with all of their roles plus the ones that # readd removed roles from user, by replacing user's roles with all of their roles plus the ones that
# were removed (and can be re-added), minus the isolate role # were removed (and can be re-added), minus the isolate role
user_roles = set(member.roles) user_roles = set(member.roles)

View file

@ -175,7 +175,6 @@ class Memeify(commands.Cog):
text_arr = text.split(" ") text_arr = text.split(" ")
for key, word in enumerate(text_arr): for key, word in enumerate(text_arr):
if self.__compare_format(word) == "hello": if self.__compare_format(word) == "hello":
text_arr[key] = "'allo 'allo" text_arr[key] = "'allo 'allo"
elif self.__compare_format(word) == "hi": elif self.__compare_format(word) == "hi":

View file

@ -1261,7 +1261,6 @@ class MoreAdmin(commands.Cog):
await channel.send(embed=data) await channel.send(embed=data)
elif sus_kick_threshold and age < sus_kick_threshold: elif sus_kick_threshold and age < sus_kick_threshold:
data = discord.Embed(title="NEW ACCOUNT KICKED", colour=member.colour) data = discord.Embed(title="NEW ACCOUNT KICKED", colour=member.colour)
data.add_field(name="Account Age", value=parse_seconds(age)) data.add_field(name="Account Age", value=parse_seconds(age))
data.add_field(name="Kick Threshold", value=parse_seconds(sus_kick_threshold)) data.add_field(name="Kick Threshold", value=parse_seconds(sus_kick_threshold))

View file

@ -56,7 +56,6 @@ def parse_seconds(seconds: int) -> str:
def role_from_string(guild, role_name): def role_from_string(guild, role_name):
role = discord.utils.find(lambda r: r.name == role_name, guild.roles) role = discord.utils.find(lambda r: r.name == role_name, guild.roles)
# if couldnt find by role name, try to find by role id # if couldnt find by role name, try to find by role id
if role is None: if role is None:

View file

@ -186,7 +186,8 @@ class Pony(commands.Cog):
Leave blank to get current max filters. Leave blank to get current max filters.
Gives an error when a user tries to add a filter while the server's filter list contains a certain amount of tags""" Gives an error when a user tries to add a filter while the server's filter list contains a certain amount of tags
"""
if new_max_filters is None: if new_max_filters is None:
max_filters = self.config.maxfilters() max_filters = self.config.maxfilters()
await ctx.send("Current filter limit: {} filters.".format(max_filters)) await ctx.send("Current filter limit: {} filters.".format(max_filters))
@ -214,7 +215,6 @@ class Pony(commands.Cog):
import_settings = json.load(raw_settings) import_settings = json.load(raw_settings)
for json_guild_id, json_guild_verbose in import_settings.items(): for json_guild_id, json_guild_verbose in import_settings.items():
if json_guild_id != "maxfilters": if json_guild_id != "maxfilters":
guild = bot.get_guild(int(json_guild_id)) guild = bot.get_guild(int(json_guild_id))
if guild is None: if guild is None:
continue continue
@ -234,7 +234,6 @@ class Pony(commands.Cog):
msg = "Filters import successful for these guilds:\n" msg = "Filters import successful for these guilds:\n"
for json_guild_id, json_guild_filters in import_filters.items(): for json_guild_id, json_guild_filters in import_filters.items():
if json_guild_id != "default": if json_guild_id != "default":
guild = bot.get_guild(int(json_guild_id)) # returns None if guild is not found guild = bot.get_guild(int(json_guild_id)) # returns None if guild is not found
if guild is None: if guild is None:
continue continue

View file

@ -526,7 +526,6 @@ class Punish(commands.Cog):
guild_remove_roles = set(role_memo.filter(remove_roles, skip_nulls=True)) guild_remove_roles = set(role_memo.filter(remove_roles, skip_nulls=True))
for member_id, member_data in punished.items(): for member_id, member_data in punished.items():
member = guild.get_member(int(member_id)) member = guild.get_member(int(member_id))
if not member: if not member:
@ -951,7 +950,6 @@ class Punish(commands.Cog):
punished = await self.config.guild(guild).PUNISHED() punished = await self.config.guild(guild).PUNISHED()
for member_id, data in punished.items(): for member_id, data in punished.items():
until = data["until"] until = data["until"]
member = guild.get_member(int(member_id)) member = guild.get_member(int(member_id))
@ -1381,7 +1379,6 @@ class Punish(commands.Cog):
await self.cancel_queue_event(member.guild.id, member.id) await self.cancel_queue_event(member.guild.id, member.id)
if apply_roles: if apply_roles:
# readd removed roles from user, by replacing user's roles with all of their roles plus the ones that # readd removed roles from user, by replacing user's roles with all of their roles plus the ones that
# were removed (and can be re-added), minus the punish role # were removed (and can be re-added), minus the punish role
user_roles = set(member.roles) user_roles = set(member.roles)

View file

@ -61,7 +61,6 @@ class ComplexActionConverter(NamedTuple):
@classmethod @classmethod
async def convert(cls, ctx: Context, argument: str): async def convert(cls, ctx: Context, argument: str):
parser = NoExitParser(description="Role management syntax help", add_help=False) parser = NoExitParser(description="Role management syntax help", add_help=False)
parser.add_argument("--has-any", nargs="*", dest="any", default=[]) parser.add_argument("--has-any", nargs="*", dest="any", default=[])
parser.add_argument("--has-all", nargs="*", dest="all", default=[]) parser.add_argument("--has-all", nargs="*", dest="all", default=[])
@ -120,7 +119,6 @@ class ComplexActionConverter(NamedTuple):
vals[attr] = await _RoleConverter.convert(ctx, vals[attr]) vals[attr] = await _RoleConverter.convert(ctx, vals[attr])
for attr in ("hasperm", "anyperm", "notperm"): for attr in ("hasperm", "anyperm", "notperm"):
vals[attr] = [i.replace("_", " ").lower().replace(" ", "_").replace("server", "guild") for i in vals[attr]] vals[attr] = [i.replace("_", " ").lower().replace(" ", "_").replace("server", "guild") for i in vals[attr]]
if any(perm not in dir(discord.Permissions) for perm in vals[attr]): if any(perm not in dir(discord.Permissions) for perm in vals[attr]):
raise BadArgument("You gave an invalid permission") raise BadArgument("You gave an invalid permission")
@ -205,7 +203,6 @@ class ComplexSearchConverter(NamedTuple):
vals[attr] = await _RoleConverter.convert(ctx, vals[attr]) vals[attr] = await _RoleConverter.convert(ctx, vals[attr])
for attr in ("hasperm", "anyperm", "notperm"): for attr in ("hasperm", "anyperm", "notperm"):
vals[attr] = [i.replace("_", " ").lower().replace(" ", "_").replace("server", "guild") for i in vals[attr]] vals[attr] = [i.replace("_", " ").lower().replace(" ", "_").replace("server", "guild") for i in vals[attr]]
if any(perm not in dir(discord.Permissions) for perm in vals[attr]): if any(perm not in dir(discord.Permissions) for perm in vals[attr]):
raise BadArgument("You gave an invalid permission") raise BadArgument("You gave an invalid permission")

View file

@ -38,6 +38,7 @@ try:
except ImportError: except ImportError:
from redbot.core.commands import Context as GuildContext # type: ignore from redbot.core.commands import Context as GuildContext # type: ignore
# This previously used ``(type(commands.Cog), type(ABC))`` # This previously used ``(type(commands.Cog), type(ABC))``
# This was changed to be explicit so that mypy # This was changed to be explicit so that mypy
# would be slightly happier about it. # would be slightly happier about it.
@ -79,12 +80,8 @@ class RoleManagement(
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self.config = Config.get_conf( self.config = Config.get_conf(self, identifier=78631113035100160, force_registration=True)
self, identifier=78631113035100160, force_registration=True self.config.register_global(handled_variation=False, handled_full_str_emoji=False)
)
self.config.register_global(
handled_variation=False, handled_full_str_emoji=False
)
self.config.register_role( self.config.register_role(
exclusive_to={}, exclusive_to={},
requires_any=[], requires_any=[],
@ -106,9 +103,7 @@ class RoleManagement(
self.config.register_custom( self.config.register_custom(
"REACTROLE", roleid=None, channelid=None, guildid=None "REACTROLE", roleid=None, channelid=None, guildid=None
) # ID : Message.id, str(React) ) # ID : Message.id, str(React)
self.config.register_guild( self.config.register_guild(notify_channel=None, s_roles=[], free_roles=[], join_roles=[], age_log=False)
notify_channel=None, s_roles=[], free_roles=[], join_roles=[], age_log=False
)
self._ready = asyncio.Event() self._ready = asyncio.Event()
self._start_task: Optional[asyncio.Task] = None self._start_task: Optional[asyncio.Task] = None
self.loop = asyncio.get_event_loop() self.loop = asyncio.get_event_loop()
@ -266,9 +261,7 @@ class RoleManagement(
role_data = await self.sub_helper(guild, role, role_data) role_data = await self.sub_helper(guild, role, role_data)
await self.config.role(role).subscribed_users.set( await self.config.role(role).subscribed_users.set(role_data["subscribed_users"])
role_data["subscribed_users"]
)
if len(role_data["subscribed_users"]) == 0: if len(role_data["subscribed_users"]) == 0:
s_roles.remove(role_id) s_roles.remove(role_id)
@ -299,9 +292,7 @@ class RoleManagement(
if dob.year == datetime.now().year: if dob.year == datetime.now().year:
await ctx.send( await ctx.send(
error( error(f"Invalid date format, please make sure to include your birth year."),
f"Invalid date format, please make sure to include your birth year."
),
delete_after=30, delete_after=30,
) )
return return
@ -319,16 +310,13 @@ class RoleManagement(
""" """
if not await self.all_are_valid_roles(ctx, role): if not await self.all_are_valid_roles(ctx, role):
return await ctx.maybe_send_embed( return await ctx.maybe_send_embed("Can't do that. Discord role heirarchy applies here.")
"Can't do that. Discord role heirarchy applies here."
)
if not await self.config.role(role).sticky(): if not await self.config.role(role).sticky():
return await ctx.send("This only works on sticky roles.") return await ctx.send("This only works on sticky roles.")
member = ctx.guild.get_member(user_id) member = ctx.guild.get_member(user_id)
if member: if member:
try: try:
await self.update_roles_atomically(who=member, give=[role]) await self.update_roles_atomically(who=member, give=[role])
except PermissionOrHierarchyException: except PermissionOrHierarchyException:
@ -336,10 +324,7 @@ class RoleManagement(
else: else:
await ctx.maybe_send_embed("They are in the guild...assigned anyway.") await ctx.maybe_send_embed("They are in the guild...assigned anyway.")
else: else:
async with self.config.member_from_ids(ctx.guild.id, user_id).roles() as sticky:
async with self.config.member_from_ids(
ctx.guild.id, user_id
).roles() as sticky:
if role.id not in sticky: if role.id not in sticky:
sticky.append(role.id) sticky.append(role.id)
@ -400,9 +385,7 @@ class RoleManagement(
""" """
if not await self.all_are_valid_roles(ctx, role): if not await self.all_are_valid_roles(ctx, role):
return await ctx.maybe_send_embed( return await ctx.maybe_send_embed("Can't do that. Discord role heirarchy applies here.")
"Can't do that. Discord role heirarchy applies here."
)
try: try:
message = await channel.fetch_message(msgid) message = await channel.fetch_message(msgid)
@ -427,9 +410,7 @@ class RoleManagement(
try: try:
await message.add_reaction(_emoji) await message.add_reaction(_emoji)
except discord.HTTPException: except discord.HTTPException:
return await ctx.maybe_send_embed( return await ctx.maybe_send_embed("Hmm, that message couldn't be reacted to")
"Hmm, that message couldn't be reacted to"
)
cfg = self.config.custom("REACTROLE", str(message.id), eid) cfg = self.config.custom("REACTROLE", str(message.id), eid)
await cfg.set( await cfg.set(
@ -449,21 +430,15 @@ class RoleManagement(
@commands.bot_has_permissions(manage_roles=True) @commands.bot_has_permissions(manage_roles=True)
@checks.admin_or_permissions(manage_guild=True) @checks.admin_or_permissions(manage_guild=True)
@commands.command(name="roleunbind") @commands.command(name="roleunbind")
async def unbind_role_from_reactions( async def unbind_role_from_reactions(self, ctx: commands.Context, role: discord.Role, msgid: int, emoji: str):
self, ctx: commands.Context, role: discord.Role, msgid: int, emoji: str
):
""" """
unbinds a role from a reaction on a message unbinds a role from a reaction on a message
""" """
if not await self.all_are_valid_roles(ctx, role): if not await self.all_are_valid_roles(ctx, role):
return await ctx.maybe_send_embed( return await ctx.maybe_send_embed("Can't do that. Discord role heirarchy applies here.")
"Can't do that. Discord role heirarchy applies here."
)
await self.config.custom( await self.config.custom("REACTROLE", f"{msgid}", self.strip_variations(emoji)).clear()
"REACTROLE", f"{msgid}", self.strip_variations(emoji)
).clear()
await ctx.tick() await ctx.tick()
@commands.guild_only() @commands.guild_only()
@ -504,9 +479,7 @@ class RoleManagement(
await ctx.tick() await ctx.tick()
@rgroup.command(name="addwith") @rgroup.command(name="addwith")
async def rg_addwith( async def rg_addwith(self, ctx: GuildContext, add_role: discord.Role, *roles: discord.Role):
self, ctx: GuildContext, add_role: discord.Role, *roles: discord.Role
):
""" """
Sets a list of roles to add to a user when they receive Sets a list of roles to add to a user when they receive
the role specifed by `add_role` the role specifed by `add_role`
@ -538,12 +511,7 @@ class RoleManagement(
use_embeds = await ctx.embed_requested() use_embeds = await ctx.embed_requested()
react_roles = "\n".join( react_roles = "\n".join(
[ [msg async for msg in self.build_messages_for_react_roles(*ctx.guild.roles, use_embeds=use_embeds)]
msg
async for msg in self.build_messages_for_react_roles(
*ctx.guild.roles, use_embeds=use_embeds
)
]
) )
if not react_roles: if not react_roles:
@ -554,9 +522,7 @@ class RoleManagement(
color = await ctx.embed_colour() if use_embeds else None color = await ctx.embed_colour() if use_embeds else None
for page in pagify( for page in pagify(react_roles, escape_mass_mentions=False, page_length=1800, shorten_by=0):
react_roles, escape_mass_mentions=False, page_length=1800, shorten_by=0
):
# unrolling iterative calling of ctx.maybe_send_embed # unrolling iterative calling of ctx.maybe_send_embed
if use_embeds: if use_embeds:
await ctx.send(embed=discord.Embed(description=page, color=color)) await ctx.send(embed=discord.Embed(description=page, color=color))
@ -564,9 +530,7 @@ class RoleManagement(
await ctx.send(page) await ctx.send(page)
@rgroup.command(name="dm-message") @rgroup.command(name="dm-message")
async def rg_dm_message( async def rg_dm_message(self, ctx: GuildContext, role: discord.Role, *, msg: str = None):
self, ctx: GuildContext, role: discord.Role, *, msg: str = None
):
""" """
Set message to DM to user when they obtain the role. Set message to DM to user when they obtain the role.
Will send it in the channel they ran the command if DM fails to send. Will send it in the channel they ran the command if DM fails to send.
@ -632,9 +596,7 @@ class RoleManagement(
return return
roles = [ctx.guild.get_role(role) for role in roles] roles = [ctx.guild.get_role(role) for role in roles]
missing = len([role for role in roles if role is None]) missing = len([role for role in roles if role is None])
roles = [ roles = [f"{i+1}.{role.name}" for i, role in enumerate(roles) if role is not None]
f"{i+1}.{role.name}" for i, role in enumerate(roles) if role is not None
]
msg = "\n".join(sorted(roles)) msg = "\n".join(sorted(roles))
msg = pagify(msg) msg = pagify(msg)
@ -655,19 +617,13 @@ class RoleManagement(
f"\n{'is' if rsets['sticky'] else 'is not'} sticky." f"\n{'is' if rsets['sticky'] else 'is not'} sticky."
) )
if rsets["requires_any"]: if rsets["requires_any"]:
rstring = ", ".join( rstring = ", ".join(r.name for r in ctx.guild.roles if r.id in rsets["requires_any"])
r.name for r in ctx.guild.roles if r.id in rsets["requires_any"]
)
output += f"\nThis role requires any of the following roles: {rstring}" output += f"\nThis role requires any of the following roles: {rstring}"
if rsets["requires_all"]: if rsets["requires_all"]:
rstring = ", ".join( rstring = ", ".join(r.name for r in ctx.guild.roles if r.id in rsets["requires_all"])
r.name for r in ctx.guild.roles if r.id in rsets["requires_all"]
)
output += f"\nThis role requires all of the following roles: {rstring}" output += f"\nThis role requires all of the following roles: {rstring}"
if rsets["add_with"]: if rsets["add_with"]:
rstring = ", ".join( rstring = ", ".join(r.name for r in ctx.guild.roles if r.id in rsets["add_with"])
r.name for r in ctx.guild.roles if r.id in rsets["add_with"]
)
output += f"\nThis role when added will also be added with the following roles: {rstring}" output += f"\nThis role when added will also be added with the following roles: {rstring}"
if rsets["exclusive_to"]: if rsets["exclusive_to"]:
rstring = "" rstring = ""
@ -699,9 +655,7 @@ class RoleManagement(
await ctx.send(page) await ctx.send(page)
@rgroup.command(name="cost") @rgroup.command(name="cost")
async def make_purchasable( async def make_purchasable(self, ctx: GuildContext, cost: int, *, role: discord.Role):
self, ctx: GuildContext, cost: int, *, role: discord.Role
):
""" """
Makes a role purchasable for a specified cost. Makes a role purchasable for a specified cost.
Cost must be a number greater than 0. Cost must be a number greater than 0.
@ -714,9 +668,7 @@ class RoleManagement(
""" """
if not await self.all_are_valid_roles(ctx, role): if not await self.all_are_valid_roles(ctx, role):
return await ctx.maybe_send_embed( return await ctx.maybe_send_embed("Can't do that. Discord role heirarchy applies here.")
"Can't do that. Discord role heirarchy applies here."
)
if cost < 0: if cost < 0:
return await ctx.send_help() return await ctx.send_help()
@ -744,9 +696,7 @@ class RoleManagement(
(etc) (etc)
""" """
if not await self.all_are_valid_roles(ctx, role): if not await self.all_are_valid_roles(ctx, role):
return await ctx.maybe_send_embed( return await ctx.maybe_send_embed("Can't do that. Discord role heirarchy applies here.")
"Can't do that. Discord role heirarchy applies here."
)
role_cost = await self.config.role(role).cost() role_cost = await self.config.role(role).cost()
if role_cost == 0: if role_cost == 0:
@ -769,9 +719,7 @@ class RoleManagement(
await ctx.send(f"Subscription set to {parse_seconds(time.total_seconds())}.") await ctx.send(f"Subscription set to {parse_seconds(time.total_seconds())}.")
@rgroup.command(name="forbid") @rgroup.command(name="forbid")
async def forbid_role( async def forbid_role(self, ctx: GuildContext, role: discord.Role, *, user: discord.Member):
self, ctx: GuildContext, role: discord.Role, *, user: discord.Member
):
""" """
Forbids a user from gaining a specific role. Forbids a user from gaining a specific role.
""" """
@ -783,9 +731,7 @@ class RoleManagement(
await ctx.tick() await ctx.tick()
@rgroup.command(name="unforbid") @rgroup.command(name="unforbid")
async def unforbid_role( async def unforbid_role(self, ctx: GuildContext, role: discord.Role, *, user: discord.Member):
self, ctx: GuildContext, role: discord.Role, *, user: discord.Member
):
""" """
Unforbids a user from gaining a specific role. Unforbids a user from gaining a specific role.
""" """
@ -797,9 +743,7 @@ class RoleManagement(
await ctx.tick() await ctx.tick()
@rgroup.command(name="exclusive") @rgroup.command(name="exclusive")
async def set_exclusivity( async def set_exclusivity(self, ctx: GuildContext, group: str, *roles: discord.Role):
self, ctx: GuildContext, group: str, *roles: discord.Role
):
""" """
Set exclusive roles for group Set exclusive roles for group
Takes 2 or more roles and sets them as exclusive to eachother Takes 2 or more roles and sets them as exclusive to eachother
@ -817,16 +761,12 @@ class RoleManagement(
async with self.config.role(role).exclusive_to() as ex_list: async with self.config.role(role).exclusive_to() as ex_list:
if group not in ex_list.keys(): if group not in ex_list.keys():
ex_list[group] = [] ex_list[group] = []
ex_list[group].extend( ex_list[group].extend([r.id for r in _roles if r != role and r.id not in ex_list[group]])
[r.id for r in _roles if r != role and r.id not in ex_list[group]]
)
await ctx.tick() await ctx.tick()
@rgroup.command(name="unexclusive") @rgroup.command(name="unexclusive")
async def unset_exclusivity( async def unset_exclusivity(self, ctx: GuildContext, group: str, *roles: discord.Role):
self, ctx: GuildContext, group: str, *roles: discord.Role
):
""" """
Remove exclusive roles for group Remove exclusive roles for group
Takes any number of roles, and removes their exclusivity settings Takes any number of roles, and removes their exclusivity settings
@ -844,29 +784,21 @@ class RoleManagement(
ex_list = await self.config.role(role).exclusive_to() ex_list = await self.config.role(role).exclusive_to()
if group not in ex_list.keys(): if group not in ex_list.keys():
continue continue
ex_list[group] = [ ex_list[group] = [idx for idx in ex_list if idx not in [r.id for r in _roles]]
idx for idx in ex_list if idx not in [r.id for r in _roles]
]
if not ex_list[group]: if not ex_list[group]:
del ex_list[group] del ex_list[group]
await self.config.role(role).exclusive_to.set(ex_list) await self.config.role(role).exclusive_to.set(ex_list)
await ctx.tick() await ctx.tick()
@rgroup.command(name="sticky") @rgroup.command(name="sticky")
async def setsticky( async def setsticky(self, ctx: GuildContext, role: discord.Role, sticky: bool = None):
self, ctx: GuildContext, role: discord.Role, sticky: bool = None
):
""" """
sets a role as sticky if used without a settings, gets the current ones sets a role as sticky if used without a settings, gets the current ones
""" """
if sticky is None: if sticky is None:
is_sticky = await self.config.role(role).sticky() is_sticky = await self.config.role(role).sticky()
return await ctx.send( return await ctx.send("{role} {verb} sticky".format(role=role.name, verb=("is" if is_sticky else "is not")))
"{role} {verb} sticky".format(
role=role.name, verb=("is" if is_sticky else "is not")
)
)
await self.config.role(role).sticky.set(sticky) await self.config.role(role).sticky.set(sticky)
if sticky: if sticky:
@ -902,9 +834,7 @@ class RoleManagement(
await ctx.tick() await ctx.tick()
@rgroup.command(name="selfrem") @rgroup.command(name="selfrem")
async def selfrem( async def selfrem(self, ctx: GuildContext, role: discord.Role, removable: bool = None):
self, ctx: GuildContext, role: discord.Role, removable: bool = None
):
""" """
Sets if a role is self-removable (default False) Sets if a role is self-removable (default False)
@ -914,18 +844,14 @@ class RoleManagement(
if removable is None: if removable is None:
is_removable = await self.config.role(role).self_removable() is_removable = await self.config.role(role).self_removable()
return await ctx.send( return await ctx.send(
"{role} {verb} self-removable".format( "{role} {verb} self-removable".format(role=role.name, verb=("is" if is_removable else "is not"))
role=role.name, verb=("is" if is_removable else "is not")
)
) )
await self.config.role(role).self_removable.set(removable) await self.config.role(role).self_removable.set(removable)
await ctx.tick() await ctx.tick()
@rgroup.command(name="selfadd") @rgroup.command(name="selfadd")
async def selfadd( async def selfadd(self, ctx: GuildContext, role: discord.Role, assignable: bool = None):
self, ctx: GuildContext, role: discord.Role, assignable: bool = None
):
""" """
Sets if a role is self-assignable via command Sets if a role is self-assignable via command
@ -937,9 +863,7 @@ class RoleManagement(
if assignable is None: if assignable is None:
is_assignable = await self.config.role(role).self_role() is_assignable = await self.config.role(role).self_role()
return await ctx.send( return await ctx.send(
"{role} {verb} self-assignable".format( "{role} {verb} self-assignable".format(role=role.name, verb=("is" if is_assignable else "is not"))
role=role.name, verb=("is" if is_assignable else "is not")
)
) )
await self.config.role(role).self_role.set(assignable) await self.config.role(role).self_role.set(assignable)
@ -988,9 +912,7 @@ class RoleManagement(
return return
roles = [ctx.guild.get_role(role) for role in roles] roles = [ctx.guild.get_role(role) for role in roles]
missing = len([role for role in roles if role is None]) missing = len([role for role in roles if role is None])
roles = [ roles = [f"{i+1}.{role.name}" for i, role in enumerate(roles) if role is not None]
f"{i+1}.{role.name}" for i, role in enumerate(roles) if role is not None
]
msg = "\n".join(sorted(roles)) msg = "\n".join(sorted(roles))
msg = pagify(msg) msg = pagify(msg)
@ -1035,9 +957,7 @@ class RoleManagement(
embed = discord.Embed(title="Roles", colour=ctx.guild.me.colour) embed = discord.Embed(title="Roles", colour=ctx.guild.me.colour)
embed.set_footer(text="You can only have one role in the same unique group!") embed.set_footer(text="You can only have one role in the same unique group!")
i = 0 i = 0
for role, (cost, sub, ex_groups) in sorted( for role, (cost, sub, ex_groups) in sorted(data.items(), key=lambda kv: kv[1][0]):
data.items(), key=lambda kv: kv[1][0]
):
if ex_groups: if ex_groups:
groups = humanize_list(list(ex_groups.keys())) groups = humanize_list(list(ex_groups.keys()))
else: else:
@ -1073,9 +993,7 @@ class RoleManagement(
cost = await self.config.role(role).cost() cost = await self.config.role(role).cost()
subscription = await self.config.role(role).subscription() subscription = await self.config.role(role).subscription()
except PermissionOrHierarchyException: except PermissionOrHierarchyException:
await ctx.send( await ctx.send("I cannot assign roles which I can not manage. (Discord Hierarchy)")
"I cannot assign roles which I can not manage. (Discord Hierarchy)"
)
except MissingRequirementsException as e: except MissingRequirementsException as e:
msg = "" msg = ""
if e.miss_all: if e.miss_all:
@ -1093,14 +1011,10 @@ class RoleManagement(
) )
else: else:
if not eligible: if not eligible:
return await ctx.send( return await ctx.send(f"You aren't allowed to add `{role}` to yourself {ctx.author.mention}!")
f"You aren't allowed to add `{role}` to yourself {ctx.author.mention}!"
)
if not cost: if not cost:
return await ctx.send( return await ctx.send("This role doesn't have a cost. Please try again using `[p]selfrole add`.")
"This role doesn't have a cost. Please try again using `[p]selfrole add`."
)
if not await self.verify_age(role, ctx=ctx): if not await self.verify_age(role, ctx=ctx):
return await ctx.send( return await ctx.send(
@ -1111,9 +1025,7 @@ class RoleManagement(
currency_name = await bank.get_currency_name(ctx.guild) currency_name = await bank.get_currency_name(ctx.guild)
for m_role in ctx.author.roles: for m_role in ctx.author.roles:
if m_role.id in free_roles: if m_role.id in free_roles:
await ctx.send( await ctx.send(f"You're special, no {currency_name} will be deducted from your account.")
f"You're special, no {currency_name} will be deducted from your account."
)
cost = 0 cost = 0
# await self.update_roles_atomically(who=ctx.author, give=[role], remove=remove) # await self.update_roles_atomically(who=ctx.author, give=[role], remove=remove)
# await ctx.tick() # await ctx.tick()
@ -1123,15 +1035,11 @@ class RoleManagement(
if cost > 0: if cost > 0:
await bank.withdraw_credits(ctx.author, cost) await bank.withdraw_credits(ctx.author, cost)
except ValueError: except ValueError:
return await ctx.send( return await ctx.send(f"You don't have enough {currency_name} (Cost: {cost} {currency_name})")
f"You don't have enough {currency_name} (Cost: {cost} {currency_name})"
)
else: else:
if subscription > 0: if subscription > 0:
if cost > 0: if cost > 0:
await ctx.send( await ctx.send(f"{role.name} will be renewed every {parse_seconds(subscription)}")
f"{role.name} will be renewed every {parse_seconds(subscription)}"
)
async with self.config.role(role).subscribed_users() as s: async with self.config.role(role).subscribed_users() as s:
s[str(ctx.author.id)] = time.time() + subscription s[str(ctx.author.id)] = time.time() + subscription
async with self.config.guild(ctx.guild).s_roles() as s: async with self.config.guild(ctx.guild).s_roles() as s:
@ -1143,9 +1051,7 @@ class RoleManagement(
await ctx.send( await ctx.send(
f"Removed `{humanize_list([r.name for r in remove])}` role{plural} since they are exclusive to the role you added." f"Removed `{humanize_list([r.name for r in remove])}` role{plural} since they are exclusive to the role you added."
) )
await self.update_roles_atomically( await self.update_roles_atomically(who=ctx.author, give=[role], remove=remove)
who=ctx.author, give=[role], remove=remove
)
await self.dm_user(ctx, role) await self.dm_user(ctx, role)
await ctx.tick() await ctx.tick()
@ -1162,9 +1068,7 @@ class RoleManagement(
eligible = await self.config.role(role).self_role() eligible = await self.config.role(role).self_role()
cost = await self.config.role(role).cost() cost = await self.config.role(role).cost()
except PermissionOrHierarchyException: except PermissionOrHierarchyException:
await ctx.send( await ctx.send("I cannot assign roles which I can not manage. (Discord Hierarchy)")
"I cannot assign roles which I can not manage. (Discord Hierarchy)"
)
except MissingRequirementsException as e: except MissingRequirementsException as e:
msg = "" msg = ""
if e.miss_all: if e.miss_all:
@ -1182,9 +1086,7 @@ class RoleManagement(
) )
else: else:
if not eligible: if not eligible:
await ctx.send( await ctx.send(f"You aren't allowed to add `{role}` to yourself {ctx.author.mention}!")
f"You aren't allowed to add `{role}` to yourself {ctx.author.mention}!"
)
elif not await self.verify_age(role, ctx=ctx): elif not await self.verify_age(role, ctx=ctx):
return await ctx.send( return await ctx.send(
@ -1193,8 +1095,7 @@ class RoleManagement(
elif cost: elif cost:
await ctx.send( await ctx.send(
"This role is not free. " "This role is not free. " "Please use `[p]selfrole buy` if you would like to purchase it."
"Please use `[p]selfrole buy` if you would like to purchase it."
) )
else: else:
if remove: if remove:
@ -1202,9 +1103,7 @@ class RoleManagement(
await ctx.send( await ctx.send(
f"Removed `{humanize_list([r.name for r in remove])}` role{plural} since they are exclusive to the role you added." f"Removed `{humanize_list([r.name for r in remove])}` role{plural} since they are exclusive to the role you added."
) )
await self.update_roles_atomically( await self.update_roles_atomically(who=ctx.author, give=[role], remove=remove)
who=ctx.author, give=[role], remove=remove
)
await self.dm_user(ctx, role) await self.dm_user(ctx, role)
await ctx.tick() await ctx.tick()
@ -1225,15 +1124,11 @@ class RoleManagement(
pass pass
await ctx.tick() await ctx.tick()
else: else:
await ctx.send( await ctx.send(f"You aren't allowed to remove `{role}` from yourself {ctx.author.mention}!`")
f"You aren't allowed to remove `{role}` from yourself {ctx.author.mention}!`"
)
# Stuff for clean interaction with react role entries # Stuff for clean interaction with react role entries
async def build_messages_for_react_roles( async def build_messages_for_react_roles(self, *roles: discord.Role, use_embeds=True) -> AsyncIterator[str]:
self, *roles: discord.Role, use_embeds=True
) -> AsyncIterator[str]:
""" """
Builds info. Builds info.
@ -1249,7 +1144,6 @@ class RoleManagement(
for role in roles: for role in roles:
# pylint: disable=E1133 # pylint: disable=E1133
async for message_id, emoji_info, data in self.get_react_role_entries(role): async for message_id, emoji_info, data in self.get_react_role_entries(role):
channel_id = data.get("channelid", None) channel_id = data.get("channelid", None)
if channel_id: if channel_id:
link = linkfmt.format( link = linkfmt.format(
@ -1259,15 +1153,13 @@ class RoleManagement(
) )
else: else:
link = ( link = (
f"unknown message with id {message_id}" f"unknown message with id {message_id}" f" (use `roleset fixup` to find missing data for this)"
f" (use `roleset fixup` to find missing data for this)"
) )
emoji: Union[discord.Emoji, str] emoji: Union[discord.Emoji, str]
if emoji_info.isdigit(): if emoji_info.isdigit():
emoji = ( emoji = (
discord.utils.get(self.bot.emojis, id=int(emoji_info)) discord.utils.get(self.bot.emojis, id=int(emoji_info)) or f"A custom enoji with id {emoji_info}"
or f"A custom enoji with id {emoji_info}"
) )
else: else:
emoji = emoji_info emoji = emoji_info
@ -1312,9 +1204,7 @@ class RoleManagement(
if ctx is not None: if ctx is not None:
await ctx.send( await ctx.send(
info( info("Please check your DMs with me in order to continue getting this role!"),
"Please check your DMs with me in order to continue getting this role!"
),
delete_after=30, delete_after=30,
) )
@ -1330,9 +1220,7 @@ class RoleManagement(
return False return False
except asyncio.TimeoutError: except asyncio.TimeoutError:
await member.send( await member.send(
error( error(f"Took too long, the {role} role has not been added to you in {guild}!\nPlease try again."),
f"Took too long, the {role} role has not been added to you in {guild}!\nPlease try again."
),
delete_after=30, delete_after=30,
) )
return False return False
@ -1341,9 +1229,7 @@ class RoleManagement(
dob = parser.parse(msg.content.strip()) dob = parser.parse(msg.content.strip())
except: except:
await member.send( await member.send(
error( error(f"Invalid date format, the {role} role has not been added to you in {guild}!\nPlease try again."),
f"Invalid date format, the {role} role has not been added to you in {guild}!\nPlease try again."
),
delete_after=30, delete_after=30,
) )
return False return False
@ -1403,9 +1289,7 @@ class RoleManagement(
) )
await ctx.send(dm_msg) await ctx.send(dm_msg)
async def get_react_role_entries( async def get_react_role_entries(self, role: discord.Role) -> AsyncIterator[Tuple[str, str, dict]]:
self, role: discord.Role
) -> AsyncIterator[Tuple[str, str, dict]]:
""" """
yields: yields:
str, str, dict str, str, dict

View file

@ -68,9 +68,7 @@ class EventMixin(MixinMeta):
for r in gained: for r in gained:
add_with = await self.config.role_from_id(r).add_with() add_with = await self.config.role_from_id(r).add_with()
if add_with: if add_with:
to_add = [ to_add = [discord.utils.get(after.guild.roles, id=add) for add in add_with]
discord.utils.get(after.guild.roles, id=add) for add in add_with
]
await after.add_roles(*to_add, reason=f"add with role {r}") await after.add_roles(*to_add, reason=f"add with role {r}")
for r in sym_diff: for r in sym_diff:
@ -119,9 +117,7 @@ class EventMixin(MixinMeta):
await member.add_roles(*to_add) await member.add_roles(*to_add)
@commands.Cog.listener() @commands.Cog.listener()
async def on_raw_reaction_add( async def on_raw_reaction_add(self, payload: discord.raw_models.RawReactionActionEvent):
self, payload: discord.raw_models.RawReactionActionEvent
):
await self.wait_for_ready() await self.wait_for_ready()
if not payload.guild_id: if not payload.guild_id:
return return
@ -180,9 +176,7 @@ class EventMixin(MixinMeta):
await self.update_roles_atomically(who=member, give=[role], remove=remove) await self.update_roles_atomically(who=member, give=[role], remove=remove)
@commands.Cog.listener() @commands.Cog.listener()
async def on_raw_reaction_remove( async def on_raw_reaction_remove(self, payload: discord.raw_models.RawReactionActionEvent):
self, payload: discord.raw_models.RawReactionActionEvent
):
await self.wait_for_ready() await self.wait_for_ready()
if not payload.guild_id: if not payload.guild_id:
return return

View file

@ -221,7 +221,6 @@ class MassManagementMixin(MixinMeta):
chunks = [members[i : (i + chunk_size)] for i in range(0, len(members), chunk_size)] chunks = [members[i : (i + chunk_size)] for i in range(0, len(members), chunk_size)]
for part, chunk in enumerate(chunks, 1): for part, chunk in enumerate(chunks, 1):
csvf = io.StringIO() csvf = io.StringIO()
fieldnames = [ fieldnames = [
"ID", "ID",

View file

@ -5,7 +5,6 @@ from redbot.core import commands
def can_run_command(command_name: str): def can_run_command(command_name: str):
async def predicate(ctx): async def predicate(ctx):
command = ctx.bot.get_command(command_name) command = ctx.bot.get_command(command_name)
if not command: if not command:
return False return False

View file

@ -37,7 +37,6 @@ class Schedule:
@classmethod @classmethod
async def convert(cls, ctx: Context, argument: str): async def convert(cls, ctx: Context, argument: str):
start: datetime start: datetime
command: Optional[str] = None command: Optional[str] = None
recur: Optional[timedelta] = None recur: Optional[timedelta] = None
@ -100,7 +99,6 @@ class TempMute(NamedTuple):
@classmethod @classmethod
async def convert(cls, ctx: Context, argument: str): async def convert(cls, ctx: Context, argument: str):
start: datetime start: datetime
reason: str reason: str

View file

@ -325,7 +325,6 @@ class Scheduler(commands.Cog):
return [t for t in self.tasks if pred(t)] return [t for t in self.tasks if pred(t)]
async def fetch_tasks_by_guild(self, guild: discord.Guild) -> List[Task]: async def fetch_tasks_by_guild(self, guild: discord.Guild) -> List[Task]:
async with self._iter_lock: async with self._iter_lock:
return [t for t in self.tasks if t.channel in guild.text_channels] return [t for t in self.tasks if t.channel in guild.text_channels]
@ -472,7 +471,6 @@ class Scheduler(commands.Cog):
tasks: List[Task], tasks: List[Task],
message: Optional[discord.Message] = None, message: Optional[discord.Message] = None,
): ):
color = await ctx.embed_color() color = await ctx.embed_color()
async def task_killer( async def task_killer(

View file

@ -30,13 +30,11 @@ class Task:
return hash(self.uid) return hash(self.uid)
async def get_message(self, bot): async def get_message(self, bot):
pfx = (await bot.get_prefix(self.channel))[0] pfx = (await bot.get_prefix(self.channel))[0]
content = f"{pfx}{self.content}" content = f"{pfx}{self.content}"
return SchedulerMessage(content=content, author=self.author, channel=self.channel) return SchedulerMessage(content=content, author=self.author, channel=self.channel)
def to_config(self): def to_config(self):
return { return {
self.uid: { self.uid: {
"nicename": self.nicename, "nicename": self.nicename,
@ -51,7 +49,6 @@ class Task:
@classmethod @classmethod
def bulk_from_config(cls, bot: discord.Client, **entries): def bulk_from_config(cls, bot: discord.Client, **entries):
for uid, data in entries.items(): for uid, data in entries.items():
cid = data.pop("channel", 0) cid = data.pop("channel", 0)
aid = data.pop("author", 0) aid = data.pop("author", 0)
@ -80,7 +77,6 @@ class Task:
@property @property
def next_call_delay(self) -> float: def next_call_delay(self) -> float:
now = datetime.now(timezone.utc) now = datetime.now(timezone.utc)
if self.recur and now >= self.initial: if self.recur and now >= self.initial:
@ -90,7 +86,6 @@ class Task:
return (self.initial - now).total_seconds() return (self.initial - now).total_seconds()
def to_embed(self, index: int, page_count: int, color: discord.Color): def to_embed(self, index: int, page_count: int, color: discord.Color):
now = datetime.now(timezone.utc) now = datetime.now(timezone.utc)
next_run_at = now + timedelta(seconds=self.next_call_delay) next_run_at = now + timedelta(seconds=self.next_call_delay)
embed = discord.Embed(color=color, timestamp=next_run_at) embed = discord.Embed(color=color, timestamp=next_run_at)

View file

@ -1,6 +1,7 @@
import inspect import inspect
from pathlib import Path from pathlib import Path
# defines a saysound dictionary # defines a saysound dictionary
def saysound(name: str, added_by: str, cost: int = 0, volume: int = 100, url: str = None, filepath: str = None) -> dict: def saysound(name: str, added_by: str, cost: int = 0, volume: int = 100, url: str = None, filepath: str = None) -> dict:
saysound = {"name": name, "added_by": added_by, "cost": cost, "volume": volume, "url": url, "filepath": filepath} saysound = {"name": name, "added_by": added_by, "cost": cost, "volume": volume, "url": url, "filepath": filepath}

View file

@ -645,7 +645,8 @@ class Suggestion(commands.Cog):
async def setglobal(self, ctx: commands.Context): async def setglobal(self, ctx: commands.Context):
"""Global suggestions settings. """Global suggestions settings.
There is nothing like approved or rejected channels because global suggestions are meant to be for the bot only and will only work if it is sent in a server where normal suggestions are disabled.""" There is nothing like approved or rejected channels because global suggestions are meant to be for the bot only and will only work if it is sent in a server where normal suggestions are disabled.
"""
pass pass
@setglobal.command(name="toggle") @setglobal.command(name="toggle")