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): def __init__(self, bot: Red):
self.bot = bot 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.image_path = self.path + "/"
self.config = Config.get_conf(self, identifier=9811198108111121, force_registration=True) self.config = Config.get_conf(self, identifier=9811198108111121, force_registration=True)
default_global = { default_global = {
'messages': [], "messages": [],
'images': [], "images": [],
'time': {'hour': 0, 'minute': 0, 'second': 0} "time": {"hour": 0, "minute": 0, "second": 0},
}
default_guild = {
"channelid": None
} }
default_guild = {"channelid": None}
self.config.register_global(**default_global) self.config.register_global(**default_global)
self.config.register_guild(**default_guild) self.config.register_guild(**default_guild)
@ -44,7 +42,7 @@ class AnnounceDaily(Cog):
async def _get_msgs(self): async def _get_msgs(self):
return DEFAULT_MESSAGES + await self.config.messages() 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) @checks.mod_or_permissions(administrator=True)
@commands.guild_only() @commands.guild_only()
async def _ad(self, ctx: commands.Context): async def _ad(self, ctx: commands.Context):
@ -112,7 +110,9 @@ class AnnounceDaily(Cog):
# await att_.save(f) # await att_.save(f)
await att_.save(self.image_path + filename) await att_.save(self.image_path + filename)
except discord.NotFound: 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: except discord.HTTPException:
await ctx.send("Failed to download the attachment, please try again") await ctx.send("Failed to download the attachment, please try again")
else: else:
@ -131,7 +131,9 @@ class AnnounceDaily(Cog):
List all registered announcement messages List all registered announcement messages
""" """
messages = await self.config.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(box(page))
await ctx.send("Done!") await ctx.send("Done!")
@ -187,10 +189,12 @@ class AnnounceDaily(Cog):
h = ann_time.hour h = ann_time.hour
m = ann_time.minute m = ann_time.minute
s = ann_time.second 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" await ctx.send(
"**Changes will apply after next scheduled announcement or reload**".format(h, m, s)) "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): async def send_announcements(self):
messages = await self._get_msgs() messages = await self._get_msgs()
@ -205,7 +209,7 @@ class AnnounceDaily(Cog):
if x >= len(messages): if x >= len(messages):
x -= len(messages) x -= len(messages)
choice = images[x] choice = images[x]
choice = open(self.image_path + choice, 'rb') choice = open(self.image_path + choice, "rb")
is_image = True is_image = True
else: else:
choice = messages[x] choice = messages[x]
@ -228,9 +232,15 @@ class AnnounceDaily(Cog):
while self is self.bot.get_cog("AnnounceDaily"): while self is self.bot.get_cog("AnnounceDaily"):
tomorrow = datetime.now() + timedelta(days=1) tomorrow = datetime.now() + timedelta(days=1)
time = await self.config.time() time = await self.config.time()
h, m, s = time['hour'], time['minute'], time['second'] h, m, s = time["hour"], time["minute"], time["second"]
midnight = datetime(year=tomorrow.year, month=tomorrow.month, midnight = datetime(
day=tomorrow.day, hour=h, minute=m, second=s) year=tomorrow.year,
month=tomorrow.month,
day=tomorrow.day,
hour=h,
minute=m,
second=s,
)
print("Sleeping for {} seconds".format((midnight - datetime.now()).seconds)) print("Sleeping for {} seconds".format((midnight - datetime.now()).seconds))
await asyncio.sleep((midnight - datetime.now()).seconds) await asyncio.sleep((midnight - datetime.now()).seconds)
@ -243,6 +253,7 @@ class AnnounceDaily(Cog):
await asyncio.sleep(3) await asyncio.sleep(3)
# [p]setchannel #channelname - Set the announcement channel per server # [p]setchannel #channelname - Set the announcement channel per server
# [p]addmsg <message goes here> - Adds a msg to the pool # [p]addmsg <message goes here> - Adds a msg to the pool
# [p]addimg http://imgurl.com/image.jpg - Adds an image 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__() super().__init__()
self.bot = bot self.bot = bot
self.audio = None self.audio = None
self.audioconf = Config.get_conf(self, identifier=651171001051118411410511810597, force_registration=True) self.audioconf = Config.get_conf(
self, identifier=651171001051118411410511810597, force_registration=True
self.audioconf.register_guild(
delay=30.0,
repeat=True,
) )
self.audioconf.register_guild(delay=30.0, repeat=True)
@commands.group() @commands.group()
@commands.guild_only() @commands.guild_only()
@checks.mod_or_permissions(administrator=True) @checks.mod_or_permissions(administrator=True)
@ -93,15 +92,16 @@ class AudioTrivia(Trivia):
status = await self.audio.config.status() status = await self.audio.config.status()
if 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): if not self.audio._player_check(ctx):
try: try:
if not ctx.author.voice.channel.permissions_for(ctx.me).connect or self.audio._userlimit( if not ctx.author.voice.channel.permissions_for(
ctx.author.voice.channel 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." return await ctx.send("I don't have permission to connect to your channel.")
)
await lavalink.connect(ctx.author.voice.channel) await lavalink.connect(ctx.author.voice.channel)
lavaplayer = lavalink.get_player(ctx.guild.id) lavaplayer = lavalink.get_player(ctx.guild.id)
lavaplayer.store("connect", datetime.datetime.utcnow()) lavaplayer.store("connect", datetime.datetime.utcnow())
@ -114,10 +114,10 @@ class AudioTrivia(Trivia):
await self.audio._data_check(ctx) await self.audio._data_check(ctx)
if ( if not ctx.author.voice or ctx.author.voice.channel != lavaplayer.channel:
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."
return await ctx.send("You must be in the voice channel to use the audiotrivia command.") )
trivia_dict = {} trivia_dict = {}
authors = [] authors = []
@ -157,7 +157,9 @@ class AudioTrivia(Trivia):
# Delay in audiosettings overwrites delay in settings # Delay in audiosettings overwrites delay in settings
combined_settings = {**settings, **audiosettings} 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) self.trivia_sessions.append(session)
LOG.debug("New audio trivia session; #%s in %d", ctx.channel, ctx.guild.id) 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): def __init__(self, bot):
self.bot = bot self.bot = bot
self.config = Config.get_conf(self, identifier=9999114111108101) self.config = Config.get_conf(self, identifier=9999114111108101)
default_guild = { default_guild = {"cmdlist": {}, "settings": {}}
"cmdlist": {},
"settings": {}
}
self.config.register_guild(**default_guild) self.config.register_guild(**default_guild)
@ -54,17 +51,23 @@ class CCRole(Cog):
cmd_list = self.config.guild(guild).cmdlist cmd_list = self.config.guild(guild).cmdlist
if await cmd_list.get_raw(command, default=None): 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 return
# Roles to add # 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): def check(m):
return m.author == author and m.channel == channel return m.author == author and m.channel == channel
try: 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: except asyncio.TimeoutError:
await ctx.send("Timed out, canceling") await ctx.send("Timed out, canceling")
return return
@ -77,9 +80,11 @@ class CCRole(Cog):
return return
# Roles to remove # 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: 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: except asyncio.TimeoutError:
await ctx.send("Timed out, canceling") await ctx.send("Timed out, canceling")
return return
@ -93,10 +98,11 @@ class CCRole(Cog):
# Roles to use # Roles to use
await ctx.send( 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: 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: except asyncio.TimeoutError:
await ctx.send("Timed out, canceling") await ctx.send("Timed out, canceling")
return return
@ -109,10 +115,12 @@ class CCRole(Cog):
return return
# Selfrole # 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: 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: except asyncio.TimeoutError:
await ctx.send("Timed out, canceling") await ctx.send("Timed out, canceling")
return return
@ -126,13 +134,14 @@ class CCRole(Cog):
# Message to send # Message to send
await ctx.send( await ctx.send(
'What message should the bot say when using this command?\n' "What message should the bot say when using this command?\n"
'Say `None` to send the default `Success!` message\n' "Say `None` to send the default `Success!` message\n"
'Eval Options: `{author}`, `{target}`, `{server}`, `{channel}`, `{message}`\n' "Eval Options: `{author}`, `{target}`, `{server}`, `{channel}`, `{message}`\n"
'For example: `Welcome {target.mention} to {server.name}!`') "For example: `Welcome {target.mention} to {server.name}!`"
)
try: 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: except asyncio.TimeoutError:
await ctx.send("Timed out, canceling") await ctx.send("Timed out, canceling")
return return
@ -143,7 +152,13 @@ class CCRole(Cog):
# Save the command # 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) await cmd_list.set_raw(command, value=out)
@ -174,18 +189,24 @@ class CCRole(Cog):
await ctx.send("That command doesn't exist") await ctx.send("That command doesn't exist")
return return
embed = discord.Embed(title=command, embed = discord.Embed(
description="{} custom command".format("Targeted" if cmd['targeted'] else "Non-Targeted")) title=command,
description="{} custom command".format(
"Targeted" if cmd["targeted"] else "Non-Targeted"
),
)
def process_roles(role_list): def process_roles(role_list):
if not role_list: if not role_list:
return "None" 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="Text", value="```{}```".format(cmd["text"]))
embed.add_field(name="Adds Roles", value=process_roles(cmd['aroles']), inline=True) 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="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="Role Restrictions", value=process_roles(cmd["proles"]), inline=True)
await ctx.send(embed=embed) await ctx.send(embed=embed)
@ -198,13 +219,17 @@ class CCRole(Cog):
if not cmd_list: if not cmd_list:
await ctx.send( await ctx.send(
"There are no custom commands in this server. Use `{}ccrole add` to start adding some.".format( "There are no custom commands in this server. Use `{}ccrole add` to start adding some.".format(
ctx.prefix)) ctx.prefix
)
)
return return
cmd_list = ", ".join([ctx.prefix + c for c in sorted(cmd_list.keys())]) cmd_list = ", ".join([ctx.prefix + c for c in sorted(cmd_list.keys())])
cmd_list = "Custom commands:\n\n" + cmd_list 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)) await ctx.send(box(cmd_list))
else: else:
for page in pagify(cmd_list, delims=[" ", "\n"]): for page in pagify(cmd_list, delims=[" ", "\n"]):
@ -231,7 +256,10 @@ class CCRole(Cog):
async def _get_roles_from_content(self, ctx, content): async def _get_roles_from_content(self, ctx, content):
content_list = content.split(",") content_list = content.split(",")
try: 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 except (discord.HTTPException, AttributeError): # None.id is attribute error
return None return None
else: else:
@ -249,9 +277,7 @@ class CCRole(Cog):
""" """
content = message.content content = message.content
prefix_list = await self.bot.command_prefix(self.bot, message) prefix_list = await self.bot.command_prefix(self.bot, message)
prefixes = sorted(prefix_list, prefixes = sorted(prefix_list, key=lambda pfx: len(pfx), reverse=True)
key=lambda pfx: len(pfx),
reverse=True)
for p in prefixes: for p in prefixes:
if content.startswith(p): if content.startswith(p):
return p return p
@ -259,25 +285,32 @@ class CCRole(Cog):
async def eval_cc(self, cmd, message): async def eval_cc(self, cmd, message):
"""Does all the work""" """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 return # Not authorized, do nothing
if cmd['targeted']: if cmd["targeted"]:
try: 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 except IndexError: # .split() return list of len<2
target = None target = None
if not target: if not target:
out_message = "This custom command is targeted! @mention a target\n`{} <target>`".format( 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) await message.channel.send(out_message)
return return
else: else:
target = message.author target = message.author
if cmd['aroles']: if cmd["aroles"]:
arole_list = [discord.utils.get(message.guild.roles, id=roleid) for roleid in 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])) # await self.bot.send_message(message.channel, "Adding: "+str([str(arole) for arole in arole_list]))
try: try:
await target.add_roles(*arole_list) await target.add_roles(*arole_list)
@ -285,8 +318,10 @@ class CCRole(Cog):
await message.channel.send("Permission error: Unable to add roles") await message.channel.send("Permission error: Unable to add roles")
await asyncio.sleep(1) await asyncio.sleep(1)
if cmd['rroles']: if cmd["rroles"]:
rrole_list = [discord.utils.get(message.guild.roles, id=roleid) for roleid in 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])) # await self.bot.send_message(message.channel, "Removing: "+str([str(rrole) for rrole in rrole_list]))
try: try:
await target.remove_roles(*rrole_list) await target.remove_roles(*rrole_list)
@ -297,7 +332,7 @@ class CCRole(Cog):
await message.channel.send(out_message) await message.channel.send(out_message)
def format_cc(self, cmd, message, target): def format_cc(self, cmd, message, target):
out = cmd['text'] out = cmd["text"]
results = re.findall("{([^}]+)\}", out) results = re.findall("{([^}]+)\}", out)
for result in results: for result in results:
param = self.transform_parameter(result, message, target) param = self.transform_parameter(result, message, target)
@ -316,7 +351,7 @@ class CCRole(Cog):
"channel": message.channel, "channel": message.channel,
"server": message.guild, "server": message.guild,
"guild": message.guild, "guild": message.guild,
"target": target "target": target,
} }
if result in objects: if result in objects:
return str(objects[result]) return str(objects[result])

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

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

@ -28,11 +28,7 @@ class Dad(Cog):
self.bot = bot self.bot = bot
self.config = Config.get_conf(self, identifier=6897100, force_registration=True) self.config = Config.get_conf(self, identifier=6897100, force_registration=True)
default_guild = { default_guild = {"enabled": False, "nickname": False, "cooldown": 240}
"enabled": False,
"nickname": False,
"cooldown": 240
}
self.config.register_guild(**default_guild) self.config.register_guild(**default_guild)
@ -40,14 +36,16 @@ class Dad(Cog):
@commands.command() @commands.command()
async def dadjoke(self, ctx: commands.Context): async def dadjoke(self, ctx: commands.Context):
headers = {"User-Agent": "FoxV3 (https://github.com/bobloy/Fox-V3)", headers = {
"Accept": "application/json"} "User-Agent": "FoxV3 (https://github.com/bobloy/Fox-V3)",
"Accept": "application/json",
}
async with aiohttp.ClientSession(headers=headers) as session: 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 = 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) await ctx.send(embed=em)
@ -57,21 +55,21 @@ class Dad(Cog):
"""Dad joke superhub""" """Dad joke superhub"""
pass pass
@dad.command(name='toggle') @dad.command(name="toggle")
async def dad_toggle(self, ctx: commands.Context): async def dad_toggle(self, ctx: commands.Context):
"""Toggle automatic dad jokes on or off""" """Toggle automatic dad jokes on or off"""
is_on = await self.config.guild(ctx.guild).enabled() is_on = await self.config.guild(ctx.guild).enabled()
await self.config.guild(ctx.guild).enabled.set(not is_on) 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)) 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): async def dad_nickname(self, ctx: commands.Context):
"""Toggle nicknaming""" """Toggle nicknaming"""
is_on = await self.config.guild(ctx.guild).nickname() is_on = await self.config.guild(ctx.guild).nickname()
await self.config.guild(ctx.guild).nickname.set(not is_on) await self.config.guild(ctx.guild).nickname.set(not is_on)
await ctx.send("Nicknaming is now set to {}".format(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): async def dad_cooldown(self, ctx: commands.Context, cooldown: int):
"""Set the auto-joke cooldown""" """Set the auto-joke cooldown"""
@ -109,4 +107,6 @@ class Dad(Cog):
await message.channel.send("Hi {}, I'm {}!".format(out, guild.me.display_name)) 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): def __init__(self, bot):
self.bot = bot self.bot = bot
self.config = Config.get_conf(self, identifier=9999114111108101) self.config = Config.get_conf(self, identifier=9999114111108101)
default_guild = { default_guild = {"role_list": []}
"role_list": []
}
self.config.register_guild(**default_guild) self.config.register_guild(**default_guild)

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

@ -24,7 +24,7 @@ class ForceMention(Cog):
@checks.admin_or_permissions(manage_roles=True) @checks.admin_or_permissions(manage_roles=True)
@commands.command() @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 Mentions that role, regardless if it's unmentionable
""" """

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

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

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

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

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

@ -27,7 +27,13 @@ class QRInvite(Cog):
self.config.register_guild(**default_guild) self.config.register_guild(**default_guild)
@commands.command() @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 Create a custom QR code invite for this server
""" """
@ -48,10 +54,13 @@ class QRInvite(Cog):
if image_url == "": # Still if image_url == "": # Still
await ctx.send( 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 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) path: pathlib.Path = cog_data_path(self)
image_path = path / (ctx.guild.icon + "." + extension) image_path = path / (ctx.guild.icon + "." + extension)
@ -67,8 +76,13 @@ class QRInvite(Cog):
else: else:
new_path = str(image_path) new_path = str(image_path)
myqr.run(invite, picture=new_path, save_name=ctx.guild.icon + "_qrcode.png", myqr.run(
save_dir=str(cog_data_path(self)), colorized=colorized, ) 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") png_path: pathlib.Path = path / (ctx.guild.icon + "_qrcode.png")
with png_path.open("rb") as png_fp: with png_path.open("rb") as png_fp:
@ -79,7 +93,7 @@ def convert_png(path):
im = Image.open(path) im = Image.open(path)
im.load() im.load()
alpha = im.split()[-1] 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) mask = Image.eval(alpha, lambda a: 255 if a <= 128 else 0)
im.paste(255, mask) im.paste(255, mask)
new_path = path.replace(".webp", ".png") new_path = path.replace(".webp", ".png")

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

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

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

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

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

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

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

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

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

Loading…
Cancel
Save