Skip to content

Commit 98ba3e5

Browse files
committed
Cleaning code and better layout
1 parent 89d2a6d commit 98ba3e5

File tree

10 files changed

+59
-45
lines changed

10 files changed

+59
-45
lines changed

cogs/admin.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
import time
22
import subprocess
33

4-
from utils import repo
4+
from utils import repo, default
55
from discord.ext import commands
66

77

88
class Admin:
99
def __init__(self, bot):
1010
self.bot = bot
11+
self.config = default.get("config.json")
1112
self._last_result = None
1213

1314
@commands.command()

cogs/discord.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
class Discord_Info:
99
def __init__(self, bot):
1010
self.bot = bot
11+
self.config = default.get("config.json")
1112

1213
@commands.command()
1314
async def avatar(self, ctx, user: discord.Member = None):

cogs/events.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
11
import discord
2-
import json
32

43
from discord.ext.commands import errors
5-
6-
with open("config.json") as f:
7-
data = json.load(f)
4+
from utils import default
85

96

107
async def send_cmd_help(ctx):
@@ -20,6 +17,7 @@ async def send_cmd_help(ctx):
2017
class Events:
2118
def __init__(self, bot):
2219
self.bot = bot
20+
self.config = default.get("config.json")
2321

2422
async def on_command_error(self, ctx, err):
2523
if isinstance(err, errors.MissingRequiredArgument) or isinstance(err, errors.BadArgument):
@@ -39,7 +37,7 @@ async def on_command_error(self, ctx, err):
3937

4038
async def on_ready(self):
4139
print(f'Ready: {self.bot.user} | Servers: {len(self.bot.guilds)}')
42-
await self.bot.change_presence(activity=discord.Game(type=0, name=data["playing"]), status=discord.Status.online)
40+
await self.bot.change_presence(activity=discord.Game(type=0, name=self.config.playing), status=discord.Status.online)
4341

4442

4543
def setup(bot):

cogs/fun.py

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,40 +4,45 @@
44

55
from io import BytesIO
66
from discord.ext import commands
7-
from utils import lists, permissions, http
7+
from utils import lists, permissions, http, default
88

99

1010
class Fun_Commands:
1111
def __init__(self, bot):
1212
self.bot = bot
13+
self.config = default.get("config.json")
1314

1415
@commands.command(aliases=['8ball'])
1516
async def eightball(self, ctx, *, question: commands.clean_content):
1617
""" Consult 8ball to receive an answer """
1718
answer = random.choice(lists.ballresponse)
1819
await ctx.send(f"🎱 **Question:** {question}\n**Answer:** {answer}")
1920

20-
@commands.command()
21-
@commands.cooldown(rate=1, per=1.5, type=commands.BucketType.user)
22-
async def cat(self, ctx):
23-
""" Posts a random cat """
21+
async def randomimageapi(self, ctx, url, endpoint):
2422
try:
25-
r = await http.get('https://nekos.life/api/v2/img/meow', res_method="json", no_cache=True)
23+
r = await http.get(url, res_method="json", no_cache=True)
2624
except json.JSONDecodeError:
2725
return await ctx.send("Couldn't find anything from the API")
2826

29-
await ctx.send(r['url'])
27+
await ctx.send(r[endpoint])
28+
29+
@commands.command()
30+
@commands.cooldown(rate=1, per=1.5, type=commands.BucketType.user)
31+
async def cat(self, ctx):
32+
""" Posts a random cat """
33+
await self.randomimageapi(ctx, 'https://nekos.life/api/v2/img/meow', 'url')
3034

3135
@commands.command()
3236
@commands.cooldown(rate=1, per=1.5, type=commands.BucketType.user)
3337
async def dog(self, ctx):
3438
""" Posts a random dog """
35-
try:
36-
r = await http.get('https://random.dog/woof.json', res_method="json", no_cache=True)
37-
except json.JSONDecodeError:
38-
await ctx.send("Couldn't find anything from the API")
39+
await self.randomimageapi(ctx, 'https://random.dog/woof.json', 'url')
3940

40-
await ctx.send(r['url'])
41+
@commands.command()
42+
@commands.cooldown(rate=1, per=1.5, type=commands.BucketType.user)
43+
async def duck(self, ctx):
44+
""" Posts a random duck """
45+
await self.randomimageapi(ctx, 'https://random-d.uk/api/v1/random', 'url')
4146

4247
@commands.command(aliases=['flip', 'coin'])
4348
async def coinflip(self, ctx):

cogs/info.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,13 @@
44
import os
55

66
from discord.ext import commands
7-
from utils import repo
7+
from utils import repo, default
88

99

1010
class Information:
1111
def __init__(self, bot):
1212
self.bot = bot
13+
self.config = default.get("config.json")
1314
self.process = psutil.Process(os.getpid())
1415

1516
@commands.command()
@@ -38,14 +39,14 @@ async def botserver(self, ctx):
3839

3940
await ctx.send(f"**{ctx.author.name}** this is my home you know :3")
4041

41-
@commands.command(aliases=['info', 'stats'])
42+
@commands.command(aliases=['info', 'stats', 'status'])
4243
async def about(self, ctx):
4344
""" About the bot """
4445
ramUsage = self.process.memory_full_info().rss / 1024**2
4546

46-
embed = discord.Embed(colour=0xC29FAF)
47+
embed = discord.Embed(colour=ctx.me.top_role.colour)
4748
embed.set_thumbnail(url=ctx.bot.user.avatar_url)
48-
embed.add_field(name="Developer", value="AlexFlipnote", inline=True)
49+
embed.add_field(name="Developer", value="AlexFlipnote#0001", inline=True)
4950
embed.add_field(name="Library", value="discord.py", inline=True)
5051
embed.add_field(name="Servers", value=len(ctx.bot.guilds), inline=True)
5152
embed.add_field(name="RAM", value=f"{ramUsage:.2f} MB", inline=True)

cogs/mod.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ async def convert(self, ctx, argument):
3939
class Moderator:
4040
def __init__(self, bot):
4141
self.bot = bot
42+
self.config = default.get("config.json")
4243

4344
@commands.command()
4445
@commands.guild_only()
@@ -178,10 +179,10 @@ async def find_discriminator(self, ctx, *, search: str):
178179
await ctx.send(content=f"Found **{len(result)}** on your search for **{search}**",
179180
file=discord.File(data, filename=default.timetext(f'DiscriminatorSearch')))
180181

181-
@commands.group(aliases=['prune'])
182+
@commands.group()
182183
@commands.guild_only()
183184
@permissions.has_permissions(manage_messages=True)
184-
async def remove(self, ctx):
185+
async def prune(self, ctx):
185186
""" Removes messages from the current server. """
186187

187188
if ctx.invoked_subcommand is None:
@@ -211,32 +212,32 @@ async def do_removal(self, ctx, limit, predicate, *, before=None, after=None, me
211212
if message is True:
212213
await ctx.send(f'🚮 Successfully removed {deleted} message{"" if deleted == 1 else "s"}.')
213214

214-
@remove.command()
215+
@prune.command()
215216
async def embeds(self, ctx, search=100):
216217
"""Removes messages that have embeds in them."""
217218
await self.do_removal(ctx, search, lambda e: len(e.embeds))
218219

219-
@remove.command()
220+
@prune.command()
220221
async def files(self, ctx, search=100):
221222
"""Removes messages that have attachments in them."""
222223
await self.do_removal(ctx, search, lambda e: len(e.attachments))
223224

224-
@remove.command()
225+
@prune.command()
225226
async def images(self, ctx, search=100):
226227
"""Removes messages that have embeds or attachments."""
227228
await self.do_removal(ctx, search, lambda e: len(e.embeds) or len(e.attachments))
228229

229-
@remove.command(name='all')
230+
@prune.command(name='all')
230231
async def _remove_all(self, ctx, search=100):
231232
"""Removes all messages."""
232233
await self.do_removal(ctx, search, lambda e: True)
233234

234-
@remove.command()
235+
@prune.command()
235236
async def user(self, ctx, member: discord.Member, search=100):
236237
"""Removes all messages by the member."""
237238
await self.do_removal(ctx, search, lambda e: e.author == member)
238239

239-
@remove.command()
240+
@prune.command()
240241
async def contains(self, ctx, *, substr: str):
241242
"""Removes all messages containing a substring.
242243
The substring must be at least 3 characters long.
@@ -246,7 +247,7 @@ async def contains(self, ctx, *, substr: str):
246247
else:
247248
await self.do_removal(ctx, 100, lambda e: substr in e.content)
248249

249-
@remove.command(name='bots')
250+
@prune.command(name='bots')
250251
async def _bots(self, ctx, prefix=None, search=100):
251252
"""Removes a bot user's messages and messages with their optional prefix."""
252253

@@ -255,7 +256,7 @@ def predicate(m):
255256

256257
await self.do_removal(ctx, search, predicate)
257258

258-
@remove.command(name='users')
259+
@prune.command(name='users')
259260
async def _users(self, ctx, prefix=None, search=100):
260261
"""Removes only user messages. """
261262

@@ -264,7 +265,7 @@ def predicate(m):
264265

265266
await self.do_removal(ctx, search, predicate)
266267

267-
@remove.command(name='emoji')
268+
@prune.command(name='emoji')
268269
async def _emoji(self, ctx, search=100):
269270
"""Removes all messages containing custom emoji."""
270271
custom_emoji = re.compile(r'<:(\w+):(\d+)>')
@@ -274,7 +275,7 @@ def predicate(m):
274275

275276
await self.do_removal(ctx, search, predicate)
276277

277-
@remove.command(name='reactions')
278+
@prune.command(name='reactions')
278279
async def _reactions(self, ctx, search=100):
279280
"""Removes all reactions from messages that have them."""
280281

index.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
import json
21
import os
32

43
from discord.ext.commands import HelpFormatter
54
from data import Bot
6-
from utils import permissions
5+
from utils import permissions, default
76

7+
config = default.get("config.json")
88
description = """
99
A simple starter bot code
1010
Made by AlexFlipnote
@@ -19,18 +19,13 @@ async def format_help_for(self, context, command_or_bot):
1919
return await super().format_help_for(context, command_or_bot)
2020

2121

22-
with open("config.json") as f:
23-
data = json.load(f)
24-
token = data["token"]
25-
prefix = data["prefix"]
26-
2722
print("Logging in...")
2823
help_attrs = dict(hidden=True)
29-
bot = Bot(command_prefix=prefix, prefix=prefix, pm_help=True, help_attrs=help_attrs, formatter=HelpFormat())
24+
bot = Bot(command_prefix=config.prefix, prefix=config.prefix, pm_help=True, help_attrs=help_attrs, formatter=HelpFormat())
3025

3126
for file in os.listdir("cogs"):
3227
if file.endswith(".py"):
3328
name = file[:-3]
3429
bot.load_extension(f"cogs.{name}")
3530

36-
bot.run(token)
31+
bot.run(config.token)

requirements.txt

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
11
git+https://github.com/Rapptz/discord.py@rewrite
22
psutil
3-
youtube_dl
43
asyncio

utils/default.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,17 @@
11
import time
2+
import json
3+
4+
from collections import namedtuple
5+
6+
7+
def get(file):
8+
try:
9+
with open(file) as data:
10+
return json.load(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
11+
except AttributeError:
12+
raise AttributeError("Unknown argument")
13+
except FileNotFoundError:
14+
raise FileNotFoundError("JSON file wasn't found")
215

316

417
def timetext(name):

utils/repo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
86477779717066752 # AlexFlipnote
33
]
44

5-
version = "v1.2.1"
5+
version = "v1.2.3"
66
invite = "https://discord.gg/DpxkY3x"
77

88

0 commit comments

Comments
 (0)