black formatting

pull/34/head
bobloy 6 years ago
parent a8efa5eedf
commit da6bbccd3f

@ -24,19 +24,17 @@ class AnnounceDaily(Cog):
def __init__(self, bot: Red):
self.bot = bot
self.path = str(cog_data_path(self)).replace('\\', '/')
self.path = str(cog_data_path(self)).replace("\\", "/")
self.image_path = self.path + "/"
self.config = Config.get_conf(self, identifier=9811198108111121, force_registration=True)
default_global = {
'messages': [],
'images': [],
'time': {'hour': 0, 'minute': 0, 'second': 0}
}
default_guild = {
"channelid": None
"messages": [],
"images": [],
"time": {"hour": 0, "minute": 0, "second": 0},
}
default_guild = {"channelid": None}
self.config.register_global(**default_global)
self.config.register_guild(**default_guild)
@ -44,7 +42,7 @@ class AnnounceDaily(Cog):
async def _get_msgs(self):
return DEFAULT_MESSAGES + await self.config.messages()
@commands.group(name="announcedaily", aliases=['annd'])
@commands.group(name="announcedaily", aliases=["annd"])
@checks.mod_or_permissions(administrator=True)
@commands.guild_only()
async def _ad(self, ctx: commands.Context):
@ -112,7 +110,9 @@ class AnnounceDaily(Cog):
# await att_.save(f)
await att_.save(self.image_path + filename)
except discord.NotFound:
await ctx.send("Did you delete the message? Cause I couldn't download the attachment")
await ctx.send(
"Did you delete the message? Cause I couldn't download the attachment"
)
except discord.HTTPException:
await ctx.send("Failed to download the attachment, please try again")
else:
@ -131,7 +131,9 @@ class AnnounceDaily(Cog):
List all registered announcement messages
"""
messages = await self.config.messages()
for page in pagify("\n".join("{} - {}".format(key, image) for key, image in enumerate(messages))):
for page in pagify(
"\n".join("{} - {}".format(key, image) for key, image in enumerate(messages))
):
await ctx.send(box(page))
await ctx.send("Done!")
@ -187,10 +189,12 @@ class AnnounceDaily(Cog):
h = ann_time.hour
m = ann_time.minute
s = ann_time.second
await self.config.time.set({'hour': h, 'minute': m, 'second': s})
await self.config.time.set({"hour": h, "minute": m, "second": s})
await ctx.send("Announcements time has been set to {}::{}::{} every day\n"
"**Changes will apply after next scheduled announcement or reload**".format(h, m, s))
await ctx.send(
"Announcements time has been set to {}::{}::{} every day\n"
"**Changes will apply after next scheduled announcement or reload**".format(h, m, s)
)
async def send_announcements(self):
messages = await self._get_msgs()
@ -205,7 +209,7 @@ class AnnounceDaily(Cog):
if x >= len(messages):
x -= len(messages)
choice = images[x]
choice = open(self.image_path + choice, 'rb')
choice = open(self.image_path + choice, "rb")
is_image = True
else:
choice = messages[x]
@ -228,9 +232,15 @@ class AnnounceDaily(Cog):
while self is self.bot.get_cog("AnnounceDaily"):
tomorrow = datetime.now() + timedelta(days=1)
time = await self.config.time()
h, m, s = time['hour'], time['minute'], time['second']
midnight = datetime(year=tomorrow.year, month=tomorrow.month,
day=tomorrow.day, hour=h, minute=m, second=s)
h, m, s = time["hour"], time["minute"], time["second"]
midnight = datetime(
year=tomorrow.year,
month=tomorrow.month,
day=tomorrow.day,
hour=h,
minute=m,
second=s,
)
print("Sleeping for {} seconds".format((midnight - datetime.now()).seconds))
await asyncio.sleep((midnight - datetime.now()).seconds)
@ -243,6 +253,7 @@ class AnnounceDaily(Cog):
await asyncio.sleep(3)
# [p]setchannel #channelname - Set the announcement channel per server
# [p]addmsg <message goes here> - Adds a msg to the pool
# [p]addimg http://imgurl.com/image.jpg - Adds an image to the pool

@ -25,13 +25,12 @@ class AudioTrivia(Trivia):
super().__init__()
self.bot = bot
self.audio = None
self.audioconf = Config.get_conf(self, identifier=651171001051118411410511810597, force_registration=True)
self.audioconf.register_guild(
delay=30.0,
repeat=True,
self.audioconf = Config.get_conf(
self, identifier=651171001051118411410511810597, force_registration=True
)
self.audioconf.register_guild(delay=30.0, repeat=True)
@commands.group()
@commands.guild_only()
@checks.mod_or_permissions(administrator=True)
@ -93,15 +92,16 @@ class AudioTrivia(Trivia):
status = await self.audio.config.status()
if status:
await ctx.send("I recommend disabling audio status with `{}audioset status`".format(ctx.prefix))
await ctx.send(
"I recommend disabling audio status with `{}audioset status`".format(ctx.prefix)
)
if not self.audio._player_check(ctx):
try:
if not ctx.author.voice.channel.permissions_for(ctx.me).connect or self.audio._userlimit(
ctx.author.voice.channel
):
return await ctx.send("I don't have permission to connect to your channel."
)
if not ctx.author.voice.channel.permissions_for(
ctx.me
).connect or self.audio._userlimit(ctx.author.voice.channel):
return await ctx.send("I don't have permission to connect to your channel.")
await lavalink.connect(ctx.author.voice.channel)
lavaplayer = lavalink.get_player(ctx.guild.id)
lavaplayer.store("connect", datetime.datetime.utcnow())
@ -114,10 +114,10 @@ class AudioTrivia(Trivia):
await self.audio._data_check(ctx)
if (
not ctx.author.voice or ctx.author.voice.channel != lavaplayer.channel
):
return await ctx.send("You must be in the voice channel to use the audiotrivia command.")
if not ctx.author.voice or ctx.author.voice.channel != lavaplayer.channel:
return await ctx.send(
"You must be in the voice channel to use the audiotrivia command."
)
trivia_dict = {}
authors = []
@ -157,7 +157,9 @@ class AudioTrivia(Trivia):
# Delay in audiosettings overwrites delay in settings
combined_settings = {**settings, **audiosettings}
session = AudioSession.start(ctx=ctx, question_list=trivia_dict, settings=combined_settings, player=lavaplayer)
session = AudioSession.start(
ctx=ctx, question_list=trivia_dict, settings=combined_settings, player=lavaplayer
)
self.trivia_sessions.append(session)
LOG.debug("New audio trivia session; #%s in %d", ctx.channel, ctx.guild.id)

@ -19,10 +19,7 @@ class CCRole(Cog):
def __init__(self, bot):
self.bot = bot
self.config = Config.get_conf(self, identifier=9999114111108101)
default_guild = {
"cmdlist": {},
"settings": {}
}
default_guild = {"cmdlist": {}, "settings": {}}
self.config.register_guild(**default_guild)
@ -54,17 +51,23 @@ class CCRole(Cog):
cmd_list = self.config.guild(guild).cmdlist
if await cmd_list.get_raw(command, default=None):
await ctx.send("This command already exists. Delete it with `{}ccrole delete` first.".format(ctx.prefix))
await ctx.send(
"This command already exists. Delete it with `{}ccrole delete` first.".format(
ctx.prefix
)
)
return
# Roles to add
await ctx.send('What roles should it add? (Must be **comma separated**)\nSay `None` to skip adding roles')
await ctx.send(
"What roles should it add? (Must be **comma separated**)\nSay `None` to skip adding roles"
)
def check(m):
return m.author == author and m.channel == channel
try:
answer = await self.bot.wait_for('message', timeout=120, check=check)
answer = await self.bot.wait_for("message", timeout=120, check=check)
except asyncio.TimeoutError:
await ctx.send("Timed out, canceling")
return
@ -77,9 +80,11 @@ class CCRole(Cog):
return
# Roles to remove
await ctx.send('What roles should it remove? (Must be comma separated)\nSay `None` to skip removing roles')
await ctx.send(
"What roles should it remove? (Must be comma separated)\nSay `None` to skip removing roles"
)
try:
answer = await self.bot.wait_for('message', timeout=120, check=check)
answer = await self.bot.wait_for("message", timeout=120, check=check)
except asyncio.TimeoutError:
await ctx.send("Timed out, canceling")
return
@ -93,10 +98,11 @@ class CCRole(Cog):
# Roles to use
await ctx.send(
'What roles are allowed to use this command? (Must be comma separated)\nSay `None` to allow all roles')
"What roles are allowed to use this command? (Must be comma separated)\nSay `None` to allow all roles"
)
try:
answer = await self.bot.wait_for('message', timeout=120, check=check)
answer = await self.bot.wait_for("message", timeout=120, check=check)
except asyncio.TimeoutError:
await ctx.send("Timed out, canceling")
return
@ -109,10 +115,12 @@ class CCRole(Cog):
return
# Selfrole
await ctx.send('Is this a targeted command?(yes//no)\nNo will make this a selfrole command')
await ctx.send(
"Is this a targeted command?(yes//no)\nNo will make this a selfrole command"
)
try:
answer = await self.bot.wait_for('message', timeout=120, check=check)
answer = await self.bot.wait_for("message", timeout=120, check=check)
except asyncio.TimeoutError:
await ctx.send("Timed out, canceling")
return
@ -126,13 +134,14 @@ class CCRole(Cog):
# Message to send
await ctx.send(
'What message should the bot say when using this command?\n'
'Say `None` to send the default `Success!` message\n'
'Eval Options: `{author}`, `{target}`, `{server}`, `{channel}`, `{message}`\n'
'For example: `Welcome {target.mention} to {server.name}!`')
"What message should the bot say when using this command?\n"
"Say `None` to send the default `Success!` message\n"
"Eval Options: `{author}`, `{target}`, `{server}`, `{channel}`, `{message}`\n"
"For example: `Welcome {target.mention} to {server.name}!`"
)
try:
answer = await self.bot.wait_for('message', timeout=120, check=check)
answer = await self.bot.wait_for("message", timeout=120, check=check)
except asyncio.TimeoutError:
await ctx.send("Timed out, canceling")
return
@ -143,7 +152,13 @@ class CCRole(Cog):
# Save the command
out = {'text': text, 'aroles': arole_list, 'rroles': rrole_list, "proles": prole_list, "targeted": targeted}
out = {
"text": text,
"aroles": arole_list,
"rroles": rrole_list,
"proles": prole_list,
"targeted": targeted,
}
await cmd_list.set_raw(command, value=out)
@ -174,18 +189,24 @@ class CCRole(Cog):
await ctx.send("That command doesn't exist")
return
embed = discord.Embed(title=command,
description="{} custom command".format("Targeted" if cmd['targeted'] else "Non-Targeted"))
embed = discord.Embed(
title=command,
description="{} custom command".format(
"Targeted" if cmd["targeted"] else "Non-Targeted"
),
)
def process_roles(role_list):
if not role_list:
return "None"
return ", ".join([discord.utils.get(ctx.guild.roles, id=roleid).name for roleid in role_list])
return ", ".join(
[discord.utils.get(ctx.guild.roles, id=roleid).name for roleid in role_list]
)
embed.add_field(name="Text", value="```{}```".format(cmd['text']))
embed.add_field(name="Adds Roles", value=process_roles(cmd['aroles']), inline=True)
embed.add_field(name="Removes Roles", value=process_roles(cmd['rroles']), inline=True)
embed.add_field(name="Role Restrictions", value=process_roles(cmd['proles']), inline=True)
embed.add_field(name="Text", value="```{}```".format(cmd["text"]))
embed.add_field(name="Adds Roles", value=process_roles(cmd["aroles"]), inline=True)
embed.add_field(name="Removes Roles", value=process_roles(cmd["rroles"]), inline=True)
embed.add_field(name="Role Restrictions", value=process_roles(cmd["proles"]), inline=True)
await ctx.send(embed=embed)
@ -198,13 +219,17 @@ class CCRole(Cog):
if not cmd_list:
await ctx.send(
"There are no custom commands in this server. Use `{}ccrole add` to start adding some.".format(
ctx.prefix))
ctx.prefix
)
)
return
cmd_list = ", ".join([ctx.prefix + c for c in sorted(cmd_list.keys())])
cmd_list = "Custom commands:\n\n" + cmd_list
if len(cmd_list) < 1500: # I'm allowed to have arbitrary numbers for when it's too much to dm dammit
if (
len(cmd_list) < 1500
): # I'm allowed to have arbitrary numbers for when it's too much to dm dammit
await ctx.send(box(cmd_list))
else:
for page in pagify(cmd_list, delims=[" ", "\n"]):
@ -222,7 +247,7 @@ class CCRole(Cog):
return
cmdlist = self.config.guild(guild).cmdlist
cmd = message.content[len(prefix):].split()[0].lower()
cmd = message.content[len(prefix) :].split()[0].lower()
cmd = await cmdlist.get_raw(cmd, default=None)
if cmd is not None:
@ -231,7 +256,10 @@ class CCRole(Cog):
async def _get_roles_from_content(self, ctx, content):
content_list = content.split(",")
try:
role_list = [discord.utils.get(ctx.guild.roles, name=role.strip(' ')).id for role in content_list]
role_list = [
discord.utils.get(ctx.guild.roles, name=role.strip(" ")).id
for role in content_list
]
except (discord.HTTPException, AttributeError): # None.id is attribute error
return None
else:
@ -249,9 +277,7 @@ class CCRole(Cog):
"""
content = message.content
prefix_list = await self.bot.command_prefix(self.bot, message)
prefixes = sorted(prefix_list,
key=lambda pfx: len(pfx),
reverse=True)
prefixes = sorted(prefix_list, key=lambda pfx: len(pfx), reverse=True)
for p in prefixes:
if content.startswith(p):
return p
@ -259,25 +285,32 @@ class CCRole(Cog):
async def eval_cc(self, cmd, message):
"""Does all the work"""
if cmd['proles'] and not (set(role.id for role in message.author.roles) & set(cmd['proles'])):
if cmd["proles"] and not (
set(role.id for role in message.author.roles) & set(cmd["proles"])
):
return # Not authorized, do nothing
if cmd['targeted']:
if cmd["targeted"]:
try:
target = discord.utils.get(message.guild.members, mention=message.content.split()[1])
target = discord.utils.get(
message.guild.members, mention=message.content.split()[1]
)
except IndexError: # .split() return list of len<2
target = None
if not target:
out_message = "This custom command is targeted! @mention a target\n`{} <target>`".format(
message.content.split()[0])
message.content.split()[0]
)
await message.channel.send(out_message)
return
else:
target = message.author
if cmd['aroles']:
arole_list = [discord.utils.get(message.guild.roles, id=roleid) for roleid in cmd['aroles']]
if cmd["aroles"]:
arole_list = [
discord.utils.get(message.guild.roles, id=roleid) for roleid in cmd["aroles"]
]
# await self.bot.send_message(message.channel, "Adding: "+str([str(arole) for arole in arole_list]))
try:
await target.add_roles(*arole_list)
@ -285,8 +318,10 @@ class CCRole(Cog):
await message.channel.send("Permission error: Unable to add roles")
await asyncio.sleep(1)
if cmd['rroles']:
rrole_list = [discord.utils.get(message.guild.roles, id=roleid) for roleid in cmd['rroles']]
if cmd["rroles"]:
rrole_list = [
discord.utils.get(message.guild.roles, id=roleid) for roleid in cmd["rroles"]
]
# await self.bot.send_message(message.channel, "Removing: "+str([str(rrole) for rrole in rrole_list]))
try:
await target.remove_roles(*rrole_list)
@ -297,7 +332,7 @@ class CCRole(Cog):
await message.channel.send(out_message)
def format_cc(self, cmd, message, target):
out = cmd['text']
out = cmd["text"]
results = re.findall("{([^}]+)\}", out)
for result in results:
param = self.transform_parameter(result, message, target)
@ -316,7 +351,7 @@ class CCRole(Cog):
"channel": message.channel,
"server": message.guild,
"guild": message.guild,
"target": target
"target": target,
}
if result in objects:
return str(objects[result])

@ -25,27 +25,24 @@ class Chatter(Cog):
self.bot = bot
self.config = Config.get_conf(self, identifier=6710497116116101114)
default_global = {}
default_guild = {
"whitelist": None,
"days": 1
}
default_guild = {"whitelist": None, "days": 1}
path: pathlib.Path = cog_data_path(self)
data_path = path / ("database.sqlite3")
self.chatbot = ChatBot(
"ChatterBot",
storage_adapter='chatter.chatterbot.storage.SQLStorageAdapter',
storage_adapter="chatter.chatterbot.storage.SQLStorageAdapter",
database=str(data_path),
statement_comparison_function=levenshtein_distance,
response_selection_method=get_first_response,
logic_adapters=[
'chatter.chatterbot.logic.BestMatch',
"chatter.chatterbot.logic.BestMatch",
{
'import_path': 'chatter.chatterbot.logic.LowConfidenceAdapter',
'threshold': 0.65,
'default_response': ':thinking:'
}
]
"import_path": "chatter.chatterbot.logic.LowConfidenceAdapter",
"threshold": 0.65,
"default_response": ":thinking:",
},
],
)
self.chatbot.set_trainer(ListTrainer)
@ -70,7 +67,9 @@ class Chatter(Cog):
if len(out_in) < 2:
return False
return msg.created_at - sent >= timedelta(hours=3) # This should be configurable perhaps
return msg.created_at - sent >= timedelta(
hours=3
) # This should be configurable perhaps
for channel in ctx.guild.text_channels:
if in_channel:
@ -138,8 +137,9 @@ class Chatter(Cog):
Backup your training data to a json for later use
"""
await ctx.send("Backing up data, this may take a while")
future = await self.loop.run_in_executor(None, self.chatbot.trainer.export_for_training,
'./{}.json'.format(backupname))
future = await self.loop.run_in_executor(
None, self.chatbot.trainer.export_for_training, "./{}.json".format(backupname)
)
if future:
await ctx.send("Backup successful!")
@ -158,7 +158,9 @@ class Chatter(Cog):
await ctx.send("Failed to gather training data")
return
await ctx.send("Gather successful! Training begins now\n(**This will take a long time, be patient**)")
await ctx.send(
"Gather successful! Training begins now\n(**This will take a long time, be patient**)"
)
embed = discord.Embed(title="Loading")
embed.set_image(url="http://www.loop.universaleverything.com/animations/1295.gif")
temp_message = await ctx.send(embed=embed)
@ -199,4 +201,4 @@ class Chatter(Cog):
if future and str(future):
await channel.send(str(future))
else:
await channel.send(':thinking:')
await channel.send(":thinking:")

@ -17,12 +17,10 @@ class CogLint(Cog):
def __init__(self, bot: Red):
self.bot = bot
self.config = Config.get_conf(self, identifier=9811198108111121, force_registration=True)
default_global = {
"lint": True
}
default_global = {"lint": True}
default_guild = {}
self.path = str(cog_data_path(self)).replace('\\', '/')
self.path = str(cog_data_path(self)).replace("\\", "/")
self.do_lint = None
self.counter = 0
@ -53,10 +51,10 @@ class CogLint(Cog):
async def lint_code(self, code):
self.counter += 1
path = self.path + "/{}.py".format(self.counter)
with open(path, 'w') as codefile:
with open(path, "w") as codefile:
codefile.write(code)
future = await self.bot.loop.run_in_executor(None, lint.py_run, path, 'return_std=True')
future = await self.bot.loop.run_in_executor(None, lint.py_run, path, "return_std=True")
if future:
(pylint_stdout, pylint_stderr) = future
@ -73,11 +71,11 @@ class CogLint(Cog):
self.do_lint = await self.config.lint()
if not self.do_lint:
return
code_blocks = message.content.split('```')[1::2]
code_blocks = message.content.split("```")[1::2]
for c in code_blocks:
is_python, code = c.split(None, 1)
is_python = is_python.lower() == 'python'
is_python = is_python.lower() == "python"
if is_python: # Then we're in business
linted, errors = await self.lint_code(code)
linted = linted.getvalue()

@ -28,11 +28,7 @@ class Dad(Cog):
self.bot = bot
self.config = Config.get_conf(self, identifier=6897100, force_registration=True)
default_guild = {
"enabled": False,
"nickname": False,
"cooldown": 240
}
default_guild = {"enabled": False, "nickname": False, "cooldown": 240}
self.config.register_guild(**default_guild)
@ -40,14 +36,16 @@ class Dad(Cog):
@commands.command()
async def dadjoke(self, ctx: commands.Context):
headers = {"User-Agent": "FoxV3 (https://github.com/bobloy/Fox-V3)",
"Accept": "application/json"}
headers = {
"User-Agent": "FoxV3 (https://github.com/bobloy/Fox-V3)",
"Accept": "application/json",
}
async with aiohttp.ClientSession(headers=headers) as session:
joke = await fetch_url(session, 'https://icanhazdadjoke.com/')
joke = await fetch_url(session, "https://icanhazdadjoke.com/")
em = discord.Embed()
em.set_image(url="https://icanhazdadjoke.com/j/{}.png".format(joke['id']))
em.set_image(url="https://icanhazdadjoke.com/j/{}.png".format(joke["id"]))
await ctx.send(embed=em)
@ -57,21 +55,21 @@ class Dad(Cog):
"""Dad joke superhub"""
pass
@dad.command(name='toggle')
@dad.command(name="toggle")
async def dad_toggle(self, ctx: commands.Context):
"""Toggle automatic dad jokes on or off"""
is_on = await self.config.guild(ctx.guild).enabled()
await self.config.guild(ctx.guild).enabled.set(not is_on)
await ctx.send("Auto dad jokes are now set to {}".format(not is_on))
@dad.command(name='nickname')
@dad.command(name="nickname")
async def dad_nickname(self, ctx: commands.Context):
"""Toggle nicknaming"""
is_on = await self.config.guild(ctx.guild).nickname()
await self.config.guild(ctx.guild).nickname.set(not is_on)
await ctx.send("Nicknaming is now set to {}".format(not is_on))
@dad.command(name='cooldown')
@dad.command(name="cooldown")
async def dad_cooldown(self, ctx: commands.Context, cooldown: int):
"""Set the auto-joke cooldown"""
@ -93,7 +91,7 @@ class Dad(Cog):
lower = message.clean_content.lower()
lower_split = lower.split()
if len(lower_split)==0:
if len(lower_split) == 0:
return
if lower_split[0] == "i'm" and len(lower_split) >= 2:
@ -109,4 +107,6 @@ class Dad(Cog):
await message.channel.send("Hi {}, I'm {}!".format(out, guild.me.display_name))
self.cooldown[guild.id] = datetime.now() + timedelta(seconds=(await guild_config.cooldown()))
self.cooldown[guild.id] = datetime.now() + timedelta(
seconds=(await guild_config.cooldown())
)

@ -16,9 +16,7 @@ class ExclusiveRole(Cog):
def __init__(self, bot):
self.bot = bot
self.config = Config.get_conf(self, identifier=9999114111108101)
default_guild = {
"role_list": []
}
default_guild = {"role_list": []}
self.config.register_guild(**default_guild)

@ -18,11 +18,7 @@ class Flag(Cog):
self.bot = bot
self.config = Config.get_conf(self, identifier=9811198108111121, force_registration=True)
default_global = {}
default_guild = {
"days": 31,
"dm": True,
"flags": {}
}
default_guild = {"days": 31, "dm": True, "flags": {}}
self.config.register_global(**default_global)
self.config.register_guild(**default_guild)
@ -67,12 +63,7 @@ class Flag(Cog):
@staticmethod
def _flag_template():
return {
'reason': "",
'expireyear': 0,
'expiremonth': 0,
'expireday': 0
}
return {"reason": "", "expireyear": 0, "expiremonth": 0, "expireday": 0}
@commands.guild_only()
@checks.mod_or_permissions(manage_roles=True)
@ -90,10 +81,10 @@ class Flag(Cog):
expiredate = date.today()
expiredate += timedelta(days=await self.config.guild(guild).days())
flag['reason'] = reason
flag['expireyear'] = expiredate.year
flag['expiremonth'] = expiredate.month
flag['expireday'] = expiredate.day
flag["reason"] = reason
flag["expireyear"] = expiredate.year
flag["expiremonth"] = expiredate.month
flag["expireday"] = expiredate.day
# flags = await self.config.guild(guild).flags.get_raw(str(member.id), default=[])
# flags.append(flag)
@ -113,7 +104,7 @@ class Flag(Cog):
@commands.guild_only()
@checks.mod_or_permissions(manage_roles=True)
@commands.command(aliases=['flagclear'])
@commands.command(aliases=["flagclear"])
async def clearflag(self, ctx: commands.Context, member: discord.Member):
"""Clears flags for a member"""
guild = ctx.guild
@ -124,7 +115,7 @@ class Flag(Cog):
await ctx.send("Success!")
@commands.guild_only()
@commands.command(aliases=['flaglist'])
@commands.command(aliases=["flaglist"])
async def listflag(self, ctx: commands.Context, member: discord.Member):
"""Lists flags for a member"""
server = ctx.guild
@ -138,7 +129,7 @@ class Flag(Cog):
await ctx.send("This member has no flags!")
@commands.guild_only()
@commands.command(aliases=['flagall'])
@commands.command(aliases=["flagall"])
async def allflag(self, ctx: commands.Context):
"""Lists all flags for the server"""
guild = ctx.guild
@ -162,12 +153,18 @@ class Flag(Cog):
"""Returns a pretty embed of flags on a member"""
flags = await self.config.guild(member.guild).flags.get_raw(str(member.id), default=[])
embed = discord.Embed(title="Flags for " + member.display_name,
description="User has {} active flags".format(len(flags)), color=0x804040)
embed = discord.Embed(
title="Flags for " + member.display_name,
description="User has {} active flags".format(len(flags)),
color=0x804040,
)
for flag in flags:
embed.add_field(name="Reason: " + flag['reason'],
value="Expires on " + str(date(flag['expireyear'], flag['expiremonth'], flag['expireday'])),
inline=True)
embed.add_field(
name="Reason: " + flag["reason"],
value="Expires on "
+ str(date(flag["expireyear"], flag["expiremonth"], flag["expireday"])),
inline=True,
)
embed.set_thumbnail(url=member.avatar_url)
@ -183,7 +180,9 @@ class Flag(Cog):
x = 0
while x < len(flags):
flag = flags[x]
if date.today() >= date(flag['expireyear'], flag['expiremonth'], flag['expireday']):
if date.today() >= date(
flag["expireyear"], flag["expiremonth"], flag["expireday"]
):
del flags[x]
else:
x += 1

@ -24,7 +24,7 @@ class ForceMention(Cog):
@checks.admin_or_permissions(manage_roles=True)
@commands.command()
async def forcemention(self, ctx: commands.Context, role: str, *, message=''):
async def forcemention(self, ctx: commands.Context, role: str, *, message=""):
"""
Mentions that role, regardless if it's unmentionable
"""

@ -11,22 +11,27 @@ Cog: Any = getattr(commands, "Cog", object)
class Hangman(Cog):
"""Lets anyone play a game of hangman with custom phrases"""
navigate = "🔼🔽"
letters = "🇦🇧🇨🇩🇪🇫🇬🇭🇮🇯🇰🇱🇲🇳🇴🇵🇶🇷🇸🇹🇺🇻🇼🇽🇾🇿"
def __init__(self, bot):
self.bot = bot
self.config = Config.get_conf(self, identifier=1049711010310997110)
default_guild = {
"theface": ':thinking:',
"emojis": True,
}
default_guild = {"theface": ":thinking:", "emojis": True}
self.config.register_guild(**default_guild)
self.the_data = defaultdict(
lambda: {"running": False, "hangman": 0, "guesses": [], "trackmessage": False, "answer": ''})
self.path = str(cog_data_path(self)).replace('\\', '/')
lambda: {
"running": False,
"hangman": 0,
"guesses": [],
"trackmessage": False,
"answer": "",
}
)
self.path = str(cog_data_path(self)).replace("\\", "/")
self.answer_path = self.path + "/bundled_data/hanganswers.txt"
@ -48,7 +53,6 @@ class Hangman(Cog):
|
|\___
""",
""">
\_________
|/ |
@ -59,74 +63,81 @@ class Hangman(Cog):
|
|\___
H""",
""">
\_________
|/ |
| """ + theface + """
| """
+ theface
+ """
|
|
|
|
|\___
HA""",
""">
\________
|/ |
| """ + theface + """
| """
+ theface
+ """
| |
| |
|
|
|\___
HAN""",
""">
\_________
|/ |
| """ + theface + """
| """
+ theface
+ """
| /|
| |
|
|
|\___
HANG""",
""">
\_________
|/ |
| """ + theface + """
| """
+ theface
+ """
| /|\
| |
|
|
|\___
HANGM""",
""">
\________
|/ |
| """ + theface + """
| """
+ theface
+ """
| /|\
| |
| /
|
|\___
HANGMA""",
""">
\________
|/ |
| """ + theface + """
| """
+ theface
+ """
| /|\
| |
| / \
|
|\___
HANGMAN""")
HANGMAN""",
)
@commands.group(aliases=['sethang'], pass_context=True)
@commands.group(aliases=["sethang"], pass_context=True)
@checks.mod_or_permissions(administrator=True)
async def hangset(self, ctx):
"""Adjust hangman settings"""
@ -140,7 +151,7 @@ class Hangman(Cog):
# Borrowing FlapJack's emoji validation
# (https://github.com/flapjax/FlapJack-Cogs/blob/master/smartreact/smartreact.py)
if theface[:2] == "<:":
theface = [r for r in self.bot.emojis if r.id == theface.split(':')[2][:-1]][0]
theface = [r for r in self.bot.emojis if r.id == theface.split(":")[2][:-1]][0]
try:
# Use the face as reaction to see if it's valid (THANKS FLAPJACK <3)
@ -161,7 +172,7 @@ class Hangman(Cog):
await self.config.guild(ctx.guild).emojis.set(not current)
await ctx.send("Emoji Letter reactions have been set to {}".format(not current))
@commands.command(aliases=['hang'], pass_context=True)
@commands.command(aliases=["hang"], pass_context=True)
async def hangman(self, ctx, guess: str = None):
"""Play a game of hangman against the bot!"""
if guess is None:
@ -200,14 +211,16 @@ class Hangman(Cog):
await channel.send("You Win!")
self._stopgame(channel.guild)
elif self.the_data[channel.guild]["hangman"] >= 7:
await channel.send("You Lose!\nThe Answer was: **" + self.the_data[channel.guild]["answer"] + "**")
await channel.send(
"You Lose!\nThe Answer was: **" + self.the_data[channel.guild]["answer"] + "**"
)
self._stopgame(channel.guild)
def _getphrase(self):
"""Get a new phrase for the game and returns it"""
with open(self.answer_path, 'r') as phrasefile:
with open(self.answer_path, "r") as phrasefile:
phrases = phrasefile.readlines()
outphrase = ""
@ -305,7 +318,9 @@ class Hangman(Cog):
await self._try_clear_reactions(message)
for x in range(len(self.letters)):
if x in [i for i, b in enumerate("ABCDEFGHIJKLM") if b not in self._guesslist(message.guild)]:
if x in [
i for i, b in enumerate("ABCDEFGHIJKLM") if b not in self._guesslist(message.guild)
]:
await message.add_reaction(self.letters[x])
await message.add_reaction(self.navigate[-1])
@ -317,7 +332,9 @@ class Hangman(Cog):
await self._try_clear_reactions(message)
for x in range(len(self.letters)):
if x in [i for i, b in enumerate("NOPQRSTUVWXYZ") if b not in self._guesslist(message.guild)]:
if x in [
i for i, b in enumerate("NOPQRSTUVWXYZ") if b not in self._guesslist(message.guild)
]:
await message.add_reaction(self.letters[x + 13])
await message.add_reaction(self.navigate[0])

@ -15,13 +15,11 @@ class Leaver(Cog):
def __init__(self, bot):
self.bot = bot
self.config = Config.get_conf(self, identifier=9811198108111121, force_registration=True)
default_guild = {
"channel": ''
}
default_guild = {"channel": ""}
self.config.register_guild(**default_guild)
@commands.group(aliases=['setleaver'])
@commands.group(aliases=["setleaver"])
@checks.mod_or_permissions(administrator=True)
async def leaverset(self, ctx):
"""Adjust leaver settings"""
@ -38,7 +36,7 @@ class Leaver(Cog):
guild = member.guild
channel = await self.config.guild(guild).channel()
if channel != '':
if channel != "":
channel = guild.get_channel(channel)
await channel.send(str(member) + "(*" + str(member.nick) + "*) has left the server!")
else:

@ -13,35 +13,40 @@ class LoveCalculator(Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=['lovecalc'])
async def lovecalculator(self, ctx: commands.Context, lover: discord.Member, loved: discord.Member):
@commands.command(aliases=["lovecalc"])
async def lovecalculator(
self, ctx: commands.Context, lover: discord.Member, loved: discord.Member
):
"""Calculate the love percentage!"""
x = lover.display_name
y = loved.display_name
url = 'https://www.lovecalculator.com/love.php?name1={}&name2={}'.format(x.replace(" ", "+"),
y.replace(" ", "+"))
url = "https://www.lovecalculator.com/love.php?name1={}&name2={}".format(
x.replace(" ", "+"), y.replace(" ", "+")
)
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
soup_object = BeautifulSoup(await response.text(), "html.parser")
try:
description = soup_object.find('div', attrs={'class': 'result score'}).get_text().strip()
description = (
soup_object.find("div", attrs={"class": "result score"}).get_text().strip()
)
except:
description = 'Dr. Love is busy right now'
description = "Dr. Love is busy right now"
try:
z = description[:2]
z = int(z)
if z > 50:
emoji = ''
emoji = ""
else:
emoji = '💔'
title = 'Dr. Love says that the love percentage for {} and {} is:'.format(x, y)
emoji = "💔"
title = "Dr. Love says that the love percentage for {} and {} is:".format(x, y)
except:
emoji = ''
title = 'Dr. Love has left a note for you.'
emoji = ""
title = "Dr. Love has left a note for you."
description = emoji + ' ' + description + ' ' + emoji
description = emoji + " " + description + " " + emoji
em = discord.Embed(title=title, description=description, color=discord.Color.red())
await ctx.send(embed=em)

@ -24,12 +24,8 @@ class LastSeen(Cog):
self.bot = bot
self.config = Config.get_conf(self, identifier=9811198108111121, force_registration=True)
default_global = {}
default_guild = {
"enabled": True
}
default_member = {
"seen": None
}
default_guild = {"enabled": True}
default_member = {"seen": None}
self.config.register_global(**default_global)
self.config.register_guild(**default_guild)
@ -40,7 +36,7 @@ class LastSeen(Cog):
d = dateutil.parser.parse(s)
return d
@commands.group(aliases=['setlseen'], name='lseenset')
@commands.group(aliases=["setlseen"], name="lseenset")
async def lset(self, ctx: commands.Context):
"""Change settings for lseen"""
if ctx.invoked_subcommand is None:
@ -50,14 +46,13 @@ class LastSeen(Cog):
async def lset_toggle(self, ctx: commands.Context):
"""Toggles tracking seen for this server"""
enabled = not await self.config.guild(ctx.guild).enabled()
await self.config.guild(ctx.guild).enabled.set(
enabled)
await self.config.guild(ctx.guild).enabled.set(enabled)
await ctx.send(
"Seen for this server is now {}".format(
"Enabled" if enabled else "Disabled"))
"Seen for this server is now {}".format("Enabled" if enabled else "Disabled")
)
@commands.command(aliases=['lastseen'])
@commands.command(aliases=["lastseen"])
async def lseen(self, ctx: commands.Context, member: discord.Member):
"""
Just says the time the user was last seen

@ -1057,7 +1057,6 @@ class PlantTycoon(Cog):
elif month == 12:
plant_options.append(self.plants["event"]["December"])
#
# Event Plant Check end
#

@ -27,7 +27,13 @@ class QRInvite(Cog):
self.config.register_guild(**default_guild)
@commands.command()
async def qrinvite(self, ctx: commands.Context, invite: str = None, colorized: bool = False, image_url: str = None):
async def qrinvite(
self,
ctx: commands.Context,
invite: str = None,
colorized: bool = False,
image_url: str = None,
):
"""
Create a custom QR code invite for this server
"""
@ -48,10 +54,13 @@ class QRInvite(Cog):
if image_url == "": # Still
await ctx.send(
"Could not get an image, please provide one. *(`{}help qrinvite` for details)*".format(ctx.prefix))
"Could not get an image, please provide one. *(`{}help qrinvite` for details)*".format(
ctx.prefix
)
)
return
extension = pathlib.Path(image_url).parts[-1].replace('.', '?').split('?')[1]
extension = pathlib.Path(image_url).parts[-1].replace(".", "?").split("?")[1]
path: pathlib.Path = cog_data_path(self)
image_path = path / (ctx.guild.icon + "." + extension)
@ -67,8 +76,13 @@ class QRInvite(Cog):
else:
new_path = str(image_path)
myqr.run(invite, picture=new_path, save_name=ctx.guild.icon + "_qrcode.png",
save_dir=str(cog_data_path(self)), colorized=colorized, )
myqr.run(
invite,
picture=new_path,
save_name=ctx.guild.icon + "_qrcode.png",
save_dir=str(cog_data_path(self)),
colorized=colorized,
)
png_path: pathlib.Path = path / (ctx.guild.icon + "_qrcode.png")
with png_path.open("rb") as png_fp:
@ -79,7 +93,7 @@ def convert_png(path):
im = Image.open(path)
im.load()
alpha = im.split()[-1]
im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)
im = im.convert("RGB").convert("P", palette=Image.ADAPTIVE, colors=255)
mask = Image.eval(alpha, lambda a: 255 if a <= 128 else 0)
im.paste(255, mask)
new_path = path.replace(".webp", ".png")

@ -15,23 +15,14 @@ class ReactRestrictCombo:
self.role_id = role_id
def __eq__(self, other: "ReactRestrictCombo"):
return (
self.message_id == other.message_id and
self.role_id == other.role_id
)
return self.message_id == other.message_id and self.role_id == other.role_id
def to_json(self):
return {
'message_id': self.message_id,
'role_id': self.role_id
}
return {"message_id": self.message_id, "role_id": self.role_id}
@classmethod
def from_json(cls, data):
return cls(
data['message_id'],
data['role_id']
)
return cls(data["message_id"], data["role_id"])
class ReactRestrict(Cog):
@ -41,11 +32,10 @@ class ReactRestrict(Cog):
def __init__(self, red: Red):
self.bot = red
self.config = Config.get_conf(self, 8210197991168210111511611410599116,
force_registration=True)
self.config.register_global(
registered_combos=[]
self.config = Config.get_conf(
self, 8210197991168210111511611410599116, force_registration=True
)
self.config.register_global(registered_combos=[])
async def combo_list(self) -> List[ReactRestrictCombo]:
"""
@ -74,8 +64,7 @@ class ReactRestrict(Cog):
:param message_id:
:return:
"""
return any(message_id == combo.message_id
for combo in await self.combo_list())
return any(message_id == combo.message_id for combo in await self.combo_list())
async def add_reactrestrict(self, message_id: int, role: discord.Role):
"""
@ -103,14 +92,14 @@ class ReactRestrict(Cog):
"""
current_combos = await self.combo_list()
to_keep = [c for c in current_combos
if not (c.message_id == message_id and c.role_id == role.id)]
to_keep = [
c for c in current_combos if not (c.message_id == message_id and c.role_id == role.id)
]
if to_keep != current_combos:
await self.set_combo_list(to_keep)
async def has_reactrestrict_combo(self, message_id: int) \
-> (bool, List[ReactRestrictCombo]):
async def has_reactrestrict_combo(self, message_id: int) -> (bool, List[ReactRestrictCombo]):
"""
Determines if there is an existing role combo for a given message
and emoji ID.
@ -123,8 +112,7 @@ class ReactRestrict(Cog):
combos = await self.combo_list()
ret = [c for c in combos
if c.message_id == message_id]
ret = [c for c in combos if c.message_id == message_id]
return len(ret) > 0, ret
@ -169,8 +157,9 @@ class ReactRestrict(Cog):
return role
async def _get_message_from_channel(self, channel_id: int, message_id: int) \
-> Union[discord.Message, None]:
async def _get_message_from_channel(
self, channel_id: int, message_id: int
) -> Union[discord.Message, None]:
"""
Tries to find a message by ID in the current guild context.
"""
@ -184,8 +173,9 @@ class ReactRestrict(Cog):
return None
async def _get_message(self, ctx: commands.Context, message_id: int) \
-> Union[discord.Message, None]:
async def _get_message(
self, ctx: commands.Context, message_id: int
) -> Union[discord.Message, None]:
"""
Tries to find a message by ID in the current guild context.
@ -258,8 +248,9 @@ class ReactRestrict(Cog):
await ctx.send("Reaction removed.")
async def on_raw_reaction_add(self, emoji: discord.PartialEmoji,
message_id: int, channel_id: int, user_id: int):
async def on_raw_reaction_add(
self, emoji: discord.PartialEmoji, message_id: int, channel_id: int, user_id: int
):
"""
Event handler for long term reaction watching.

@ -15,7 +15,7 @@ class RecyclingPlant(Cog):
def __init__(self, bot):
self.bot = bot
self.path = str(cog_data_path(self)).replace('\\', '/')
self.path = str(cog_data_path(self)).replace("\\", "/")
self.junk_path = self.path + "/bundled_data/junk.json"
with open(self.junk_path) as json_data:
@ -27,44 +27,63 @@ class RecyclingPlant(Cog):
x = 0
reward = 0
await ctx.send(
'{0} has signed up for a shift at the Recycling Plant! Type ``exit`` to terminate it early.'.format(
ctx.author.display_name))
"{0} has signed up for a shift at the Recycling Plant! Type ``exit`` to terminate it early.".format(
ctx.author.display_name
)
)
while x in range(0, 10):
used = random.choice(self.junk['can'])
if used['action'] == 'trash':
opp = 'recycle'
used = random.choice(self.junk["can"])
if used["action"] == "trash":
opp = "recycle"
else:
opp = 'trash'
await ctx.send('``{}``! Will {} ``trash`` it or ``recycle`` it?'.format(used['object'],
ctx.author.display_name))
opp = "trash"
await ctx.send(
"``{}``! Will {} ``trash`` it or ``recycle`` it?".format(
used["object"], ctx.author.display_name
)
)
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
try:
answer = await self.bot.wait_for('message', timeout=120, check=check)
answer = await self.bot.wait_for("message", timeout=120, check=check)
except asyncio.TimeoutError:
answer = None
if answer is None:
await ctx.send('``{}`` fell down the conveyor belt to be sorted again!'.format(used['object']))
elif answer.content.lower().strip() == used['action']:
await ctx.send(
'Congratulations! You put ``{}`` down the correct chute! (**+50**)'.format(used['object']))
"``{}`` fell down the conveyor belt to be sorted again!".format(used["object"])
)
elif answer.content.lower().strip() == used["action"]:
await ctx.send(
"Congratulations! You put ``{}`` down the correct chute! (**+50**)".format(
used["object"]
)
)
reward = reward + 50
x += 1
elif answer.content.lower().strip() == opp:
await ctx.send('{}, you little brute, you put it down the wrong chute! (**-50**)'.format(
ctx.author.display_name))
await ctx.send(
"{}, you little brute, you put it down the wrong chute! (**-50**)".format(
ctx.author.display_name
)
)
reward = reward - 50
elif answer.content.lower().strip() == 'exit':
await ctx.send('{} has been relived of their duty.'.format(ctx.author.display_name))
elif answer.content.lower().strip() == "exit":
await ctx.send(
"{} has been relived of their duty.".format(ctx.author.display_name)
)
break
else:
await ctx.send('``{}`` fell down the conveyor belt to be sorted again!'.format(used['object']))
await ctx.send(
"``{}`` fell down the conveyor belt to be sorted again!".format(used["object"])
)
else:
if reward > 0:
bank.deposit_credits(ctx.author, reward)
await ctx.send(
'{} been given **{} {}s** for your services.'.format(ctx.author.display_name, reward,
bank.get_currency_name(ctx.guild)))
"{} been given **{} {}s** for your services.".format(
ctx.author.display_name, reward, bank.get_currency_name(ctx.guild)
)
)

@ -12,26 +12,11 @@ class RPSLS(Cog):
"""Play Rock Paper Scissors Lizard Spock."""
weaknesses = {
"rock": [
"paper",
"spock"
],
"paper": [
"scissors",
"lizard"
],
"scissors": [
"spock",
"rock"
],
"lizard": [
"scissors",
"rock"
],
"spock": [
"paper",
"lizard"
]
"rock": ["paper", "spock"],
"paper": ["scissors", "lizard"],
"scissors": ["spock", "rock"],
"lizard": ["scissors", "rock"],
"spock": ["paper", "lizard"],
}
def __init__(self, bot):
@ -63,31 +48,31 @@ class RPSLS(Cog):
bot_choice = random.choice(list(self.weaknesses.keys()))
bot_emote = self.get_emote(bot_choice)
message = '{} vs. {}, who will win?'.format(player_emote, bot_emote)
message = "{} vs. {}, who will win?".format(player_emote, bot_emote)
em = discord.Embed(description=message, color=discord.Color.blue())
await ctx.send(embed=em)
await asyncio.sleep(2)
if player_choice in self.weaknesses[bot_choice]:
message = 'You win! :sob:'
message = "You win! :sob:"
em_color = discord.Color.green()
elif bot_choice in self.weaknesses[player_choice]:
message = 'I win! :smile:'
message = "I win! :smile:"
em_color = discord.Color.red()
else:
message = 'It\'s a draw! :neutral_face:'
message = "It's a draw! :neutral_face:"
em_color = discord.Color.blue()
em = discord.Embed(description=message, color=em_color)
await ctx.send(embed=em)
def get_emote(self, choice):
if choice == 'rock':
emote = ':moyai:'
elif choice == 'spock':
emote = ':vulcan:'
elif choice == 'paper':
emote = ':page_facing_up:'
elif choice in ['scissors', 'lizard']:
emote = ':{}:'.format(choice)
if choice == "rock":
emote = ":moyai:"
elif choice == "spock":
emote = ":vulcan:"
elif choice == "paper":
emote = ":page_facing_up:"
elif choice in ["scissors", "lizard"]:
emote = ":{}:".format(choice)
else:
emote = None
return emote

@ -48,7 +48,7 @@ class SayUrl(Cog):
h.single_line_break = True
h.mark_code = True
h.wrap_links = True
h.ul_item_mark = '-'
h.ul_item_mark = "-"
async with aiohttp.ClientSession() as session:
site = await fetch_url(session, url)

@ -50,9 +50,39 @@ class SCP(Cog):
Warning: Some of them may be too creepy or gruesome."""
valid_archive = (
13, 48, 51, 89, 91, 112, 132, 138, 157, 186, 232, 234,
244, 252, 257, 338, 356, 361, 400, 406, 503, 515, 517,
578, 728, 744, 776, 784, 837, 922, 987, 1023)
13,
48,
51,
89,
91,
112,
132,
138,
157,
186,
232,
234,
244,
252,
257,
338,
356,
361,
400,
406,
503,
515,
517,
578,
728,
744,
776,
784,
837,
922,
987,
1023,
)
if num in valid_archive:
msg = "http://www.scp-wiki.net/scp-{:03}-arc".format(num)
c = discord.Color.green()

@ -10,10 +10,9 @@ Cog: Any = getattr(commands, "Cog", object)
async def fetch_img(session, url):
with aiohttp.Timeout(10):
async with session.get(url) as response:
assert response.status == 200
return await response.read()
async with session.get(url) as response:
assert response.status == 200
return await response.read()
class StealEmoji(Cog):
@ -28,17 +27,13 @@ class StealEmoji(Cog):
"managed": False,
"guild_id": None,
"url": None,
"animated": False
"animated": False,
}
def __init__(self, red: Red):
self.bot = red
self.config = Config.get_conf(self, identifier=11511610197108101109111106105)
default_global = {
"stolemoji": {},
"guildbanks": [],
"on": False
}
default_global = {"stolemoji": {}, "guildbanks": [], "on": False}
self.config.register_global(**default_global)
@ -60,13 +55,19 @@ class StealEmoji(Cog):
@stealemoji.command(name="bank")
async def se_bank(self, ctx):
"""Add current server as emoji bank"""
await ctx.send("This will upload custom emojis to this server\n"
"Are you sure you want to make the current server an emoji bank? (y//n)")
await ctx.send(
"This will upload custom emojis to this server\n"
"Are you sure you want to make the current server an emoji bank? (y//n)"
)
def check(m):
return m.content.upper() in ["Y", "YES", "N", "NO"] and m.channel == ctx.channel and m.author == ctx.author
return (
m.content.upper() in ["Y", "YES", "N", "NO"]
and m.channel == ctx.channel
and m.author == ctx.author
)
msg = await self.bot.wait_for('message', check=check)
msg = await self.bot.wait_for("message", check=check)
if msg.content in ["N", "NO"]:
await ctx.send("Cancelled")
@ -130,7 +131,9 @@ class StealEmoji(Cog):
# urllib.urlretrieve(emoji.url, emoji.name+ext)
try:
await guildbank.create_custom_emoji(name=emoji.name, image=img, reason="Stole from " + str(user))
await guildbank.create_custom_emoji(
name=emoji.name, image=img, reason="Stole from " + str(user)
)
except discord.Forbidden as e:
print("PermissionError - no permission to add emojis")
raise PermissionError("No permission to add emojis") from e

@ -17,10 +17,7 @@ class Timerole(Cog):
self.bot = bot
self.config = Config.get_conf(self, identifier=9811198108111121, force_registration=True)
default_global = {}
default_guild = {
'announce': None,
'roles': {}
}
default_guild = {"announce": None, "roles": {}}
self.config.register_global(**default_global)
self.config.register_guild(**default_guild)
@ -43,13 +40,15 @@ class Timerole(Cog):
pass
@timerole.command()
async def addrole(self, ctx: commands.Context, role: discord.Role, days: int, *requiredroles: discord.Role):
async def addrole(
self, ctx: commands.Context, role: discord.Role, days: int, *requiredroles: discord.Role
):
"""Add a role to be added after specified time on server"""
guild = ctx.guild
to_set = {'days': days}
to_set = {"days": days}
if requiredroles:
to_set['required'] = [r.id for r in requiredroles]
to_set["required"] = [r.id for r in requiredroles]
await self.config.guild(guild).roles.set_raw(role.id, value=to_set)
await ctx.send("Time Role for {0} set to {1} days".format(role.name, days))
@ -83,9 +82,12 @@ class Timerole(Cog):
r_roles = []
if role is None:
role = r_id
if 'required' in r_data:
r_roles = [str(discord.utils.get(guild.roles, id=int(new_id))) for new_id in r_data['required']]
out += "{} || {} days || requires: {}\n".format(str(role), r_data['days'], r_roles)
if "required" in r_data:
r_roles = [
str(discord.utils.get(guild.roles, id=int(new_id)))
for new_id in r_data["required"]
]
out += "{} || {} days || requires: {}\n".format(str(role), r_data["days"], r_roles)
await ctx.maybe_send_embed(out)
async def timerole_update(self):
@ -105,13 +107,15 @@ class Timerole(Cog):
for role_id in check_roles:
# Check for required role
if 'required' in role_dict[str(role_id)]:
if not set(role_dict[str(role_id)]['required']) & set(has_roles):
if "required" in role_dict[str(role_id)]:
if not set(role_dict[str(role_id)]["required"]) & set(has_roles):
# Doesn't have required role
continue
if member.joined_at + timedelta(
days=role_dict[str(role_id)]['days']) <= datetime.today():
if (
member.joined_at + timedelta(days=role_dict[str(role_id)]["days"])
<= datetime.today()
):
# Qualifies
addlist.append((member, role_id))
@ -128,15 +132,20 @@ class Timerole(Cog):
if channel is not None and results:
await channel.send(title)
for page in pagify(
results, shorten_by=50):
for page in pagify(results, shorten_by=50):
await channel.send(page)
async def check_day(self):
while self is self.bot.get_cog("Timerole"):
tomorrow = datetime.now() + timedelta(days=1)
midnight = datetime(year=tomorrow.year, month=tomorrow.month,
day=tomorrow.day, hour=0, minute=0, second=0)
midnight = datetime(
year=tomorrow.year,
month=tomorrow.month,
day=tomorrow.day,
hour=0,
minute=0,
second=0,
)
await asyncio.sleep((midnight - datetime.now()).seconds)

@ -30,6 +30,6 @@ class TTS(Cog):
Send Text to speech messages as an mp3
"""
mp3_fp = io.BytesIO()
tts = gTTS(text, 'en')
tts = gTTS(text, "en")
tts.write_to_fp(mp3_fp)
await ctx.send(file=discord.File(mp3_fp.getvalue(), "text.mp3"))

@ -13,7 +13,7 @@ class Unicode(Cog):
def __init__(self, bot):
self.bot = bot
@commands.group(name='unicode', pass_context=True)
@commands.group(name="unicode", pass_context=True)
async def unicode(self, ctx):
"""Encode/Decode a Unicode character."""
if ctx.invoked_subcommand is None:
@ -23,30 +23,30 @@ class Unicode(Cog):
async def decode(self, ctx: commands.Context, character):
"""Decode a Unicode character."""
try:
data = 'U+{:04X}'.format(ord(character[0]))
data = "U+{:04X}".format(ord(character[0]))
color = discord.Color.green()
except ValueError:
data = '<unknown>'
data = "<unknown>"
color = discord.Color.red()
em = discord.Embed(title=character, description=data, color=color)
await ctx.send(embed=em)
@unicode.command()
async def encode(self, ctx:commands.Context, character):
async def encode(self, ctx: commands.Context, character):
"""Encode an Unicode character."""
try:
if character[:2] == '\\u':
data = repr(c.decode(character, 'unicode-escape'))
if character[:2] == "\\u":
data = repr(c.decode(character, "unicode-escape"))
data = data.strip("'")
color = discord.Color.green()
elif character[:2] == 'U+':
data = chr(int(character.lstrip('U+'), 16))
elif character[:2] == "U+":
data = chr(int(character.lstrip("U+"), 16))
color = discord.Color.green()
else:
data = '<unknown>'
data = "<unknown>"
color = discord.Color.red()
except ValueError:
data = '<unknown>'
data = "<unknown>"
color = discord.Color.red()
em = discord.Embed(title=character, description=data, color=color)
await ctx.send(embed=em)

Loading…
Cancel
Save