Skip to content

Commit 5ea09b2

Browse files
committedMar 6, 2021
fix pep 8
1 parent e546df1 commit 5ea09b2

File tree

9 files changed

+701
-354
lines changed

9 files changed

+701
-354
lines changed
 

‎.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,4 +139,5 @@ cython_debug/
139139

140140
# Custom
141141
storage/
142-
.vscode/
142+
.vscode/
143+
.history/

‎bot.py

Lines changed: 156 additions & 81 deletions
Large diffs are not rendered by default.

‎cogs/config.py

Lines changed: 182 additions & 81 deletions
Large diffs are not rendered by default.

‎cogs/general.py

Lines changed: 93 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,16 @@
33
~~~~~~~~~~~~~~~~~~
44
This file contains elements that are under the following licenses:
55
Copyright (c) 2015 Rapptz
6-
license MIT, see https://github.com/Rapptz/RoboDanny/blob/e1c3c28fe20eb192463f7fc224a399141f0d915d/LICENSE.txt for more details.
6+
license MIT, see
7+
https://github.com/Rapptz/RoboDanny/blob/e1c3c28fe20eb192463f7fc224a399141f0d915d/LICENSE.txt
8+
for more details.
79
"""
810

911
import discord
1012
import time
1113
import asyncio
1214
import re
15+
import asyncpg
1316
import os
1417
import url_parser
1518
import inspect
@@ -22,45 +25,50 @@ async def filter_links(bot, message):
2225
return
2326
if message.author.permissions_in(message.channel).manage_messages:
2427
return
25-
regex = r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
28+
regex = (r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|'
29+
r'(?:%[0-9a-fA-F][0-9a-fA-F]))+')
2630

2731
matches = re.findall(regex, message.content, re.MULTILINE)
2832
urls = []
2933
for link in matches:
3034
try:
31-
urls = [] #[url_parser.get_url(link)] #[''.join(url_parser.get_base_url(str(link)).split('//')[1:])]
35+
urls = []
3236
async with bot.http._HTTPClient__session.get(link) as resp:
3337
urls.append(url_parser.get_url(link)._asdict())
3438
for redirect in resp.history:
35-
urls.append(url_parser.get_url(redirect.real_url)._asdict())
36-
#str(''.join(url_parser.get_base_url(str(resp.real_url)).split('//')[1:])))
39+
urls.append(
40+
url_parser.get_url(redirect.real_url)._asdict())
3741
for url in urls:
38-
for blocked in [ # "*" means any
39-
# [http[s]://][sub.]<name>.<domain>[/path] # Reason
40-
########################################################################
41-
42-
'*.grabify.link/*', # Ip Grabber
43-
'*.pornhub.com/*', # Porn
42+
for blocked in [ # "*" means any
43+
# [http[s]://][sub.]<name>.<domain>[/path] # Reason
44+
###########################################################
45+
46+
'*.grabify.link/*', # Ip Grabber
47+
'*.pornhub.com/*', # Porn
4448
]:
45-
parsed_blocked = url_parser.get_url(blocked.replace('*','-'))._asdict()
49+
parsed_blocked = url_parser.get_url(
50+
blocked.replace('*', '-'))._asdict()
4651
for k, v in parsed_blocked.items():
47-
if k in ['protocol', 'www', 'dir', 'file', 'fragment', 'query']:
52+
if k in ['protocol', 'www', 'dir', 'file', 'fragment',
53+
'query']:
4854
continue
4955
if v == url[k]:
5056
continue
5157
if isinstance(v, str):
52-
if v.replace('.','') == '-':
58+
if v.replace('.', '') == '-':
5359
continue
5460
if k == 'path':
5561
if v[1:] == '-':
5662
continue
57-
return
63+
return
5864
await message.delete()
59-
await message.channel.send(f':warning: {message.author.mention} That link is not allowed :warning:', delete_after=15)
65+
await message.channel.send((
66+
f':warning: {message.author.mention} That link is not '
67+
'allowed :warning:'), delete_after=15)
6068
return
6169
except Exception as e:
6270
print(e)
63-
71+
6472

6573
async def filter_invite(bot, message, content=None):
6674
if message.author.permissions_in(message.channel).manage_messages:
@@ -70,34 +78,40 @@ async def filter_invite(bot, message, content=None):
7078
801641781028454420
7179
]:
7280
return
73-
pattern = r"discord(?:(?:(?:app)?\.com)\/invite|\.gg)/([a-zA-z0-9\-]{2,})(?!\S)"
74-
matches = re.findall(pattern,message.content, re.MULTILINE)
81+
pattern = (
82+
r'discord(?:(?:(?:app)?\.com)\/invite|\.gg)/([a-zA-z0-9\-]{2,})(?!\S)')
83+
matches = re.findall(pattern, message.content, re.MULTILINE)
7584
if len(matches) > 5:
7685
await message.delete()
77-
await message.channel.send(f':warning: {message.author.mention} Invite links are not allowed :warning:', delete_after=15)
86+
await message.channel.send((
87+
f':warning: {message.author.mention} Invite links are not allowed '
88+
':warning:'), delete_after=15)
7889
return True
7990
for code in matches:
8091
try:
8192
invite = await bot.fetch_invite(code)
8293
except discord.errors.NotFound:
83-
invite = None # invite is fine
94+
invite = None # invite is fine
8495
if invite:
85-
if not invite.guild.id in [message.guild.id, 681882711945641997, 782903894468198450]:
96+
if invite.guild.id not in [message.guild.id, 681882711945641997,
97+
782903894468198450]:
8698
await message.delete()
87-
await message.channel.send(f':warning: {message.author.mention} Invite links are not allowed :warning:', delete_after=15)
99+
await message.channel.send((
100+
f':warning: {message.author.mention} Invite links are not '
101+
'allowed :warning:'), delete_after=15)
88102
return True
89-
103+
90104

91105
class General(commands.Cog):
92106

93107
def __init__(self, bot):
94108
self.bot = bot
95109

96-
97110
@commands.Cog.listener()
98111
async def on_message_edit(self, before, after):
99-
if before.content != after.content: # invoke the command again if it is edited
100-
ctx = await self.bot.get_context(after, cls=self.bot.helpers.Context)
112+
if before.content != after.content: # invoke the command again on edit
113+
ctx = await self.bot.get_context(after,
114+
cls=self.bot.helpers.Context)
101115
await self.bot.invoke(ctx)
102116
if after.guild:
103117
if after.guild.id == 681882711945641997:
@@ -112,7 +126,7 @@ async def on_message(self, message):
112126
invite = await filter_invite(self.bot, message)
113127
if not invite:
114128
await filter_links(self.bot, message)
115-
129+
116130
@commands.command(name="source", aliases=["github", "code"])
117131
@commands.cooldown(1, 1, commands.BucketType.channel)
118132
async def _source(self, ctx, *, command: str = None):
@@ -135,8 +149,6 @@ async def _source(self, ctx, *, command: str = None):
135149
if obj is None:
136150
return await ctx.send('Could not find command.')
137151

138-
# since we found the command we're looking for, presumably anyway, let's
139-
# try to access the code itself
140152
src = obj.callback.__code__
141153
module = obj.callback.__module__
142154
filename = src.co_filename
@@ -150,67 +162,96 @@ async def _source(self, ctx, *, command: str = None):
150162
source_url = 'https://github.com/Rapptz/discord.py'
151163
branch = 'master'
152164

153-
final_url = f'<{source_url}/blob/{branch}/{location}#L{firstlineno}-L{firstlineno + len(lines) - 1}>'
154-
embed = ctx.embed(title='<:githubwhite:804344724621230091> GitHub <:githubwhite:804344724621230091>', description=f'[Click Here]({final_url})')
165+
final_url = (f'<{source_url}/blob/{branch}/{location}#L{firstlineno}-L'
166+
f'{firstlineno + len(lines) - 1}>')
167+
github = '<:githubwhite:804344724621230091>'
168+
embed = ctx.embed(title=f'{github} GitHub {github}',
169+
description=f'[Click Here]({final_url})')
155170
await ctx.send(embed=embed)
156171

157-
@commands.command(name="mystbin",aliases=["mb"])
172+
@commands.command(name="mystbin", aliases=["mb"])
158173
@commands.cooldown(1, 1, commands.BucketType.channel)
159174
async def _mystbin(self, ctx, *, code: codeblock_converter = None):
160-
"""Send your code to Mystb.in. You may use codeblocks, no codeblocks, or inside a file."""
175+
"""Send your code to Mystb.in. You may use codeblocks if you want,
176+
or use code from inside a file."""
161177
code = code.content if code else None
162178
attachments = None
163179

164180
if len(ctx.message.attachments) != 0:
165181
attachments = ctx.message.attachments
166182
elif ctx.message.reference:
167-
message = await ctx.channel.fetch_message(ctx.message.reference.message_id)
183+
message = await ctx.channel.fetch_message(
184+
ctx.message.reference.message_id)
168185
attachments = message.attachments
169186
if attachments:
170187
for attachment in attachments:
171188
code = await attachment.read()
172189

173190
if not code:
174-
return await ctx.send(embed=ctx.error('Please either provide code in the command, attach a file, or react to a message that contains a file.'))
175-
async with self.bot.http._HTTPClient__session.post('https://mystb.in/documents', data=code) as r:
191+
return await ctx.send(embed=ctx.error((
192+
'Please either provide code in the command, attach a file, or '
193+
'react to a message that contains a file.')))
194+
async with self.bot.http._HTTPClient__session.post(
195+
'https://mystb.in/documents', data=code) as r:
176196
res = await r.json()
177197
key = res["key"]
178-
embed = ctx.embed(title="Mystb.in Link", description='I pasted your code into a bin, click on the title access it!', url=f'https://mystb.in/{key}').set_thumbnail(url='https://cdn.discordapp.com/avatars/569566608817782824/14f120e096fb515d770eea38f9cddd88.png')
198+
embed = ctx.embed(title="Mystb.in Link", description=(
199+
'I pasted your code into a bin, click on the title access it!'),
200+
url=f'https://mystb.in/{key}')
201+
embed.set_thumbnail(url=(
202+
'https://cdn.discordapp.com/avatars/569566608817782824/'
203+
'14f120e096fb515d770eea38f9cddd88.png'))
179204
await ctx.send(embed=embed)
180205

181206
@commands.command(name='ping')
182207
async def _ping(self, ctx):
183-
embed = ctx.embed(title='PONG! :ping_pong:',description=f'**<a:DiscordSpin:795546311319355393> Websocket:** {(self.bot.latency * 1000):.2f}ms\n**:repeat: Round-Trip:** Calculating...\n**:elephant: Database:** Calculating...')
208+
loading = '<a:DiscordSpin:795546311319355393>'
209+
embed = ctx.embed(title='PONG! :ping_pong:', description=(
210+
f'**<{loading} Websocket:** {(self.bot.latency * 1000):.2f}ms\n**'
211+
':repeat: Round-Trip:** Calculating...\n**:elephant: Database:** '
212+
'Calculating...'))
184213
start = time.perf_counter()
185214
message = await ctx.send(embed=embed)
186215
await asyncio.sleep(0.5)
187216
end = time.perf_counter()
188217
trip = end - start
189-
embed.description = f'**<a:DiscordSpin:795546311319355393> Websocket:** {(self.bot.latency * 1000):.2f}ms\n**:repeat: Round-Trip:** {(trip * 1000):.2f}ms\n**:elephant: Database:** Calcuating...'
218+
embed.description = (
219+
f'**{loading} Websocket:** {(self.bot.latency * 1000):.2f}ms\n**'
220+
f':repeat: Round-Trip:** {(trip * 1000):.2f}ms\n**:elephant: '
221+
'Database:** Calculating...')
190222
await message.edit(embed=embed)
191223
await asyncio.sleep(0.5)
192224
start = time.perf_counter()
193225
try:
194226
async with self.bot.pools.config.acquire() as connection:
195-
await connection.fetchval('SELECT prefixes FROM serverconf WHERE id = 0')
227+
await connection.fetchval(
228+
'SELECT prefixes FROM serverconf WHERE id = 0')
196229
end = time.perf_counter()
197230
database = end - start
198-
embed.description = f'**<a:DiscordSpin:795546311319355393> Websocket:** {(self.bot.latency * 1000):.2f}ms\n**:repeat: Round-Trip:** {(trip * 1000):.2f}ms\n**:elephant: Database:** {(database * 1000):.2f}ms'
199-
except:
200-
embed.description = f'**<a:DiscordSpin:795546311319355393> Websocket:** {(self.bot.latency * 1000):.2f}ms\n**:repeat: Round-Trip:** {(trip * 1000):.2f}ms\n**:elephant: Database:** *Did not respond!*'
231+
embed.description = (
232+
f'**{loading} Websocket:** {(self.bot.latency * 1000):.2f}ms\n'
233+
f'**:repeat: Round-Trip:** {(trip * 1000):.2f}ms\n**:elephant:'
234+
f' Database:** {(database * 1000):.2f}ms')
235+
except asyncpg.exceptions._base.InterfaceError:
236+
embed.description = (
237+
f'**<{loading} Websocket:** {(self.bot.latency * 1000):.2f}ms'
238+
f'\n**:repeat: Round-Trip:** {(trip * 1000):.2f}ms\n**'
239+
':elephant: Database:** *Did not respond!*')
201240
await message.edit(embed=embed)
202-
203-
@commands.command(name='revive', aliases=['revivechat', 'chatrevive', 'revchat', 'chatrev'])
241+
242+
@commands.command(name='revive', aliases=['revivechat', 'chatrevive',
243+
'revchat', 'chatrev'])
204244
@commands.guild_only()
205245
@commands.cooldown(1, 1800, commands.BucketType.guild)
206-
@commands.has_any_role(729530191109554237, 795136568805294097, 725899526350831616)
246+
@commands.has_any_role(729530191109554237, 795136568805294097,
247+
725899526350831616) # Senior Mod +
207248
async def _revive(self, ctx):
208-
try:
209-
mention = ctx.guild.get_role(759219083639783448).mention
210-
except:
211-
mention = f'<@&759219083639783448>'
212-
embed = ctx.embed(title='Revive Chat Ping!', description='Come back to chat and make it alive again!')
249+
mention = ctx.guild.get_role(759219083639783448).mention
250+
embed = ctx.embed(
251+
title='Revive Chat Ping!',
252+
description='Come back to chat and make it alive again!')
213253
await ctx.send(content=mention, embed=embed)
214254

255+
215256
def setup(bot):
216257
bot.add_cog(General(bot))

‎cogs/help.py

Lines changed: 130 additions & 70 deletions
Large diffs are not rendered by default.

‎cogs/owner.py

Lines changed: 63 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from discord.ext import commands
88
from jishaku.codeblocks import codeblock_converter
99

10+
1011
class Owner(commands.Cog):
1112

1213
def __init__(self, bot):
@@ -17,42 +18,59 @@ async def _eval(self, ctx, *, code: codeblock_converter):
1718
"""Eval some code"""
1819
cog = self.bot.get_cog("Jishaku")
1920
await cog.jsk_python(ctx, argument=code)
20-
21+
2122
@commands.command(name='refresh')
2223
async def _refresh(self, ctx):
2324
"""Refresh the bot by invoking `jsk git pull` and `restart`"""
2425
cog = self.bot.get_cog("Jishaku")
2526
await cog.jsk_git(ctx, argument=codeblock_converter('pull'))
26-
await asyncio.sleep(2) # allow jsk git pull to finish before restarting
27+
await asyncio.sleep(2) # allow jsk git pull to finish
2728
restart = self.bot.get_command('restart')
2829
await ctx.invoke(restart)
2930

3031
@commands.command(name='restart')
3132
async def _restart(self, ctx, flag=None):
3233
"""
33-
Restart the bot. Will wait for any running commands to stop. Use --force to ignore any running commands and proceed with the restart
34+
Restart the bot. Will wait for any running commands to stop (if
35+
--force is not used).
3436
"""
3537
if not (flag == '--force' or flag == '-f'):
3638
if self.bot.processing_commands > 1:
37-
embed = discord.Embed(title='Commands in progress...', description=f'Retrying in 30 seconds. Use `{ctx.prefix}restart --force` to force restart.', timestamp=ctx.message.created_at)
38-
embed.set_footer(text=f'{self.bot.processing_commands - 1} commands currently in progess')
39+
embed = discord.Embed(
40+
title='Commands in progress...',
41+
description=(f'Retrying in 30 seconds. Use `{ctx.prefix}'
42+
'restart --force` to force restart.'),
43+
timestamp=ctx.message.created_at)
44+
embed.set_footer(text=(f'{self.bot.processing_commands - 1} '
45+
'commands currently in progess'))
3946
await ctx.send(embed=embed)
4047
for i in range(10):
4148
await asyncio.sleep(30)
4249
if self.bot.processing_commands > 1:
43-
embed = discord.Embed(title='Commands in progress...', description=f'Retrying in 30 seconds. Use `{ctx.prefix}restart --force` to force restart.', timestamp=ctx.message.created_at)
44-
embed.set_footer(text=f'{self.bot.processing_commands - 1} commands currently in progess')
50+
embed = discord.Embed(
51+
title='Commands in progress...',
52+
description=('Retrying in 30 seconds. Use `'
53+
f'{ctx.prefix}restart --force` to '
54+
'force restart.'),
55+
timestamp=ctx.message.created_at)
56+
embed.set_footer(
57+
text=(f'{self.bot.processing_commands - 1} '
58+
'commands currently in progess')
59+
)
4560
await ctx.send(embed=embed)
4661
else:
4762
break
4863
if self.bot.processing_commands > 1:
49-
embed = discord.Embed(title='Restart Failed', description=f'{self.bot.processing_commands - 1} commands currently in progess. Use `{ctx.prefix}restart --force` to force restart.', timestamp=ctx.message.created_at)
64+
embed = discord.Embed(title='Restart Failed', description=(
65+
f'{self.bot.processing_commands - 1} commands '
66+
f'currently in progess. Use `{ctx.prefix}restart '
67+
'--force` to force restart.'),
68+
timestamp=ctx.message.created_at)
5069
return await ctx.send(embed=embed)
5170
embed = discord.Embed(title="Be right back!")
5271
await ctx.send(embed=embed)
5372
self.bot.helpers.storage(self.bot, 'restart_channel', ctx.channel.id)
54-
if sys.stdin.isatty(): # if the bot was run from the command line instead of from systemctl
55-
# os.execv('sudo python', sys.argv) os.path.abspath(__file__)
73+
if sys.stdin.isatty(): # if the bot was run from the command line
5674
try:
5775
p = psutil.Process(os.getpid())
5876
for handler in p.open_files() + p.connections():
@@ -65,18 +83,28 @@ async def _restart(self, ctx, flag=None):
6583
embed = ctx.error('Failed to restart')
6684
await ctx.send(embed=embed)
6785

68-
@commands.command(name='shutdown',aliases=['off','die','shut','kill'])
86+
@commands.command(name='shutdown', aliases=['off', 'die', 'shut', 'kill'])
6987
async def _shutdown(self, ctx, flag=None):
7088
if flag == '--wait' or flag == '-w':
7189
if self.bot.processing_commands > 1:
72-
embed = discord.Embed(title='Commands in progress...', description=f'Retrying in 30 seconds.', timestamp=ctx.message.created_at)
73-
embed.set_footer(text=f'{self.bot.processing_commands - 1} commands currently in progess')
90+
embed = discord.Embed(title='Commands in progress...',
91+
description='Retrying in 30 seconds.',
92+
timestamp=ctx.message.created_at)
93+
embed.set_footer(text=(
94+
f'{self.bot.processing_commands - 1} commands currently '
95+
'in progess'))
7496
await ctx.send(embed=embed)
7597
for i in range(10):
7698
await asyncio.sleep(30)
7799
if self.bot.processing_commands > 1:
78-
embed = discord.Embed(title='Commands in progress...', description=f'Retrying in 30 seconds.', timestamp=ctx.message.created_at)
79-
embed.set_footer(text=f'{self.bot.processing_commands - 1} commands currently in progess')
100+
embed = discord.Embed(
101+
title='Commands in progress...',
102+
description='Retrying in 30 seconds.',
103+
timestamp=ctx.message.created_at
104+
)
105+
embed.set_footer(
106+
text=(f'{self.bot.processing_commands - 1} '
107+
'commands currently in progess'))
80108
await ctx.send(embed=embed)
81109
else:
82110
break
@@ -85,27 +113,40 @@ async def _shutdown(self, ctx, flag=None):
85113
await self.bot.logout()
86114
else:
87115
if len(sys.argv) > 1:
88-
os.system(f"sudo {'stoprewrite' if sys.argv[1] == 'rewrite' else 'stopmain'}")
116+
if sys.argv[1] == 'rewrite':
117+
query = 'stoprewrite'
118+
else:
119+
query = 'stopmain'
120+
os.system(f"sudo {query}")
89121
await asyncio.sleep(1)
90-
await ctx.send(embed=ctx.error('Failed to stop systemd service, attempting to shut down both services'))
91-
os.system(f'sudo stopall')
122+
await ctx.send(embed=ctx.error((
123+
'Failed to stop systemd service, attempting to shut down both '
124+
'services'
125+
)))
126+
os.system('sudo stopall')
92127
await asyncio.sleep(1)
93-
await ctx.send(embed=ctx.error('Failed to stop systemd service, attempting to logout normally'))
128+
await ctx.send(embed=ctx.error((
129+
'Failed to stop systemd service, attempting to logout normally'
130+
)))
94131
await self.bot.logout()
95132

96133
@commands.command(name='disable')
97134
async def _disable(self, ctx, toggle: bool = None):
98135
"""
99-
Disable the bot in case of an exploit, major bug, or other emergency. The bot will remain online, but only bot owners will be able to run commands on it
136+
Disable the bot in case of an exploit, major bug, or other emergency.
137+
The bot will remain online, but only bot owners will be able to run
138+
commands on it.
100139
"""
101140
self.bot.disabled = not self.bot.disabled if toggle is None else toggle
102141
embed = ctx.embed(title='Bot Status', timestamp=ctx.message.created_at)
103-
embed.add_field(name='Disabled',value=self.bot.disabled)
104-
self.bot.helpers.storage(self.bot, key='disabled', value=self.bot.disabled)
142+
embed.add_field(name='Disabled', value=self.bot.disabled)
143+
self.bot.helpers.storage(self.bot, key='disabled',
144+
value=self.bot.disabled)
105145
await ctx.send(embed=embed)
106146

107147
async def cog_check(self, ctx):
108148
return ctx.author.id in self.bot.owner_ids
109149

150+
110151
def setup(bot):
111152
bot.add_cog(Owner(bot))

‎ext/helpers.py

Lines changed: 72 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,13 @@
55
import datetime
66
import asyncpg
77
import asyncio
8-
import discord
9-
import inspect
108
from discord.ext import commands
11-
from discord_slash import SlashContext as SlashCtx
129

1310

1411
class Bot(commands.Bot):
1512

1613
async def logout(self, *args, **kwargs):
17-
if hasattr(self.pools,'config'):
14+
if hasattr(self.pools, 'config'):
1815
try:
1916
await asyncio.wait_for(self.pools.config.close(), timeout=5)
2017
except Exception as e:
@@ -24,40 +21,47 @@ async def logout(self, *args, **kwargs):
2421
await asyncio.wait_for(self.sr_api.close(), timeout=5)
2522
except Exception as e:
2623
print(e)
27-
if hasattr(self,'wavelink'):
24+
if hasattr(self, 'wavelink'):
2825
if not self.wavelink.session.closed:
29-
await asyncio.wait_for(self.wavelink.session.close(), timeout=5)
26+
await asyncio.wait_for(self.wavelink.session.close(),
27+
timeout=5)
3028
await super().logout(*args, **kwargs)
3129

30+
3231
class Embed(discord.Embed):
3332
def __repr__(self):
3433
return self.description or ''
3534

35+
3636
class Context(commands.Context):
3737

3838
Embed = Embed
3939

40-
def embed(self, description=None, *args,**kwargs):
40+
def embed(self, description=None, *args, **kwargs):
4141
default = {
4242
'timestamp': self.message.created_at,
4343
'description': description
4444
}
4545
default.update(kwargs)
46-
return_embed = self.Embed(*args,**default)
47-
return_embed.set_footer(icon_url=self.author.avatar_url,text=f'Requested by {self.author}')
46+
return_embed = self.Embed(*args, **default)
47+
return_embed.set_footer(icon_url=self.author.avatar_url,
48+
text=f'Requested by {self.author}')
4849
return return_embed
4950

50-
def error(self, description=None, *args,**kwargs):
51+
def error(self, description=None, *args, **kwargs):
5152
default = {
5253
'title': 'Error',
5354
'color': discord.Color.red(),
5455
'timestamp': self.message.created_at,
5556
'description': description
5657
}
5758
default.update(kwargs)
58-
return_embed = self.Embed(*args,**default)
59-
return_embed.set_author(name=self.author,icon_url=self.author.avatar_url)
60-
return_embed.set_footer(icon_url=self.bot.user.avatar_url,text=f'If you think this is a mistake please contact {self.bot.get_user(self.bot.owner_ids[0])}')
59+
return_embed = self.Embed(*args, **default)
60+
return_embed.set_author(name=self.author,
61+
icon_url=self.author.avatar_url)
62+
return_embed.set_footer(icon_url=self.bot.user.avatar_url, text=(
63+
'If you think this is a mistake please contact '
64+
f'{self.bot.get_user(self.bot.owner_ids[0])}'))
6165
return return_embed
6266

6367

@@ -69,44 +73,51 @@ async def init_connection(connection):
6973
schema='pg_catalog'
7074
)
7175

76+
7277
def storage(bot, key=None, value=None, method=None, override=False):
7378
try:
74-
with open('./storage/config.json','r') as f:
79+
with open('./storage/config.json', 'r') as f:
7580
data = json.load(f)
76-
except:
77-
with open('./storage/config.json','w+') as f:
81+
except OSError:
82+
with open('./storage/config.json', 'w+') as f:
7883
f.write('{}')
79-
with open('./storage/config.json','r') as f:
84+
with open('./storage/config.json', 'r') as f:
8085
data = json.load(f)
8186
data['cogs'] = data.get('cogs', [])
8287
data['blacklisted'] = data.get('blacklisted', [])
8388
data['disabled'] = data.get('disabled', False)
84-
data['owners'] = data.get('owners', [int(bot.default_owner) if bot.default_owner else 690420846774321221])
89+
if bot.default_owner:
90+
temp_owner = int(bot.default_owner)
91+
else:
92+
temp_owner = 690420846774321221
93+
data['owners'] = data.get('owners', [temp_owner])
8594
bot.restart_channel = data.get('restart_channel', None)
8695
data['restart_channel'] = None
8796
if key and value:
8897
if method == 'append':
89-
if not value in data[key] or override:
98+
if value not in data[key] or override:
9099
data[key].append(value)
91100
elif method == 'remove':
92101
if value in data[key] or override:
93102
data[key].remove(value)
94103
else:
95104
data[key] = value
96-
with open('./storage/config.json','w') as f:
97-
json.dump(data,f,indent=4)
105+
with open('./storage/config.json', 'w') as f:
106+
json.dump(data, f, indent=4)
98107
return data
99108

109+
100110
async def prepare(bot, guild=None):
101111
try:
102112
connection = await bot.pools.config.acquire()
103113
await bot.pools.config.release(connection)
104-
except:
114+
except asyncpg.exceptions._base.InterfaceError:
105115
try:
106-
bot.pools.config = await asyncio.wait_for(asyncpg.create_pool(database='codingbot_db', init=init_connection), timeout=5)
116+
bot.pools.config = await asyncio.wait_for(asyncpg.create_pool(
117+
database='codingbot_db', init=init_connection), timeout=5)
107118
connection = await bot.pools.config.acquire()
108119
await bot.pools.config.release(connection)
109-
except:
120+
except (OSError, asyncpg.exceptions._base.InterfaceError):
110121
if guild:
111122
bot.server_cache[guild.id] = bot.server_cache.get(guild.id, {
112123
'prefixes': bot.default_prefixes.copy(),
@@ -122,7 +133,8 @@ async def prepare(bot, guild=None):
122133
prefixes text[]
123134
);
124135
''')
125-
data = await connection.fetchrow('SELECT * FROM serverconf WHERE id = $1', guild.id)
136+
data = await connection.fetchrow(
137+
'SELECT * FROM serverconf WHERE id = $1', guild.id)
126138
bot.server_cache[guild.id] = bot.server_cache.get(guild.id, {
127139
'prefixes': bot.default_prefixes.copy(),
128140
'commands': {}
@@ -133,72 +145,87 @@ async def prepare(bot, guild=None):
133145
if isinstance(data['commands'], dict):
134146
bot.server_cache[guild.id]['commands'] = data['commands']
135147

148+
136149
async def is_disabled(ctx):
137150
if not ctx.guild:
138151
return False
139152
try:
140153
data = ctx.bot.server_cache[ctx.guild.id].copy()
141-
except:
154+
except KeyError:
142155
await prepare(ctx.bot, ctx.guild)
143156
try:
144157
data = ctx.bot.server_cache[ctx.guild.id].copy()
145-
except:
158+
except KeyError:
146159
data = {}
147-
ids_to_check = [ctx.guild.id, ctx.channel.id, ctx.author.id] + [r.id for r in ctx.author.roles]
160+
ids_to_check = [ctx.guild.id, ctx.channel.id, ctx.author.id]
161+
ids_to_check += [r.id for r in ctx.author.roles]
148162
for id_ in ids_to_check:
149163
data[int(id_)] = data.get(int(id_), [])
150-
if True in data[int(id_)] or ctx.command.qualified_name in data[int(id_)]:
164+
if (True in data[int(id_)]
165+
or ctx.command.qualified_name in data[int(id_)]):
151166
return True
152167
return False
153168

169+
154170
async def prefix(bot, message):
155171
return_prefixes = bot.default_prefixes.copy()
156172
if not message.guild:
157173
return_prefixes.append('')
158174
else:
159175
try:
160176
data = bot.server_cache[message.guild.id]['prefixes']
161-
except:
177+
except KeyError:
162178
try:
163-
bot.server_cache[message.guild.id] = bot.server_cache.get(message.guild.id, {
164-
'prefixes': return_prefixes,
165-
'commands': {}
166-
})
179+
bot.server_cache[message.guild.id] = bot.server_cache.get(
180+
message.guild.id, {
181+
'prefixes': return_prefixes,
182+
'commands': {}
183+
})
167184
bot.loop.create_task(prepare(bot, message.guild))
168185
data = bot.server_cache[message.guild.id]['prefixes']
169-
except:
186+
except KeyError:
170187
data = bot.default_prefixes
171188
return_prefixes = data or return_prefixes
172189
return return_prefixes
173190

174191

175-
async def log_command_error(ctx,error,handled):
192+
async def log_command_error(ctx, error, handled):
176193
if not handled:
177194
channel = ctx.bot.get_channel(787461422896513104)
178195
else:
179196
channel = ctx.bot.get_channel(787476834689744926)
180197
title = 'Ignoring exception in command {}:'.format(ctx.command)
181-
err = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
198+
err = ''.join(traceback.format_exception(
199+
type(error), error, error.__traceback__))
182200
try:
183-
embed = discord.Embed(title=title,description=f'```py\n{err}```',timestamp=ctx.message.created_at,color=discord.Color.red()).set_author(name=ctx.author,icon_url=ctx.author.avatar_url)
201+
embed = discord.Embed(title=title, description=f'```py\n{err}```',
202+
timestamp=ctx.message.created_at,
203+
color=discord.Color.red())
204+
embed.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)
184205
await channel.send(embed=embed)
185-
except:
206+
except discord.errors.Forbidden:
186207
try:
187-
await channel.send(f"**<@{ctx.bot.owner_ids[0]}> An error occurred but I couldn't log it here**")
188-
except:
208+
await channel.send((f"**<@{ctx.bot.owner_ids[0]}> An error "
209+
"occurred but I couldn't log it here**"))
210+
except discord.errors.Forbidden:
189211
pass
190-
print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
191-
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
212+
print('Ignoring exception in command {}:'.format(ctx.command),
213+
file=sys.stderr)
214+
traceback.print_exception(type(error), error, error.__traceback__,
215+
file=sys.stderr)
192216
finally:
193217
return
194218

219+
195220
async def log_error(bot, event_method, *args, **kwargs):
196221
channel = bot.get_channel(812359854890156073)
197222
try:
198223
title = 'Ignoring exception in {}'.format(event_method)
199224
err = ''.join(traceback.format_exc())
200-
embed = discord.Embed(title=title,description=f'```py\n{err}```',timestamp=datetime.datetime.utcnow(),color=discord.Color.red())
225+
embed = discord.Embed(title=title, description=f'```py\n{err}```',
226+
timestamp=datetime.datetime.utcnow(),
227+
color=discord.Color.red())
201228
await channel.send(embed=embed)
202-
except:
229+
except discord.errors.Forbidden:
203230
print('Ignoring exception in {}'.format(event_method), file=sys.stderr)
204231
traceback.print_exc()

‎requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,5 @@ DiscordUtils
99
pytest
1010
aiosqlite_pool.zip
1111
time-str
12-
discord-flags
12+
discord-flags
13+
url-parser

‎test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import pytest
21
import bot
32

3+
44
def test(token):
55
bot.bot.run(token)

0 commit comments

Comments
 (0)
Please sign in to comment.