Skip to content

Commit 5075a35

Browse files
committed
Formatted and annotated all functions and methods.
1 parent 9cc859e commit 5075a35

18 files changed

+614
-674
lines changed

bot/__main__.py

+2-91
Original file line numberDiff line numberDiff line change
@@ -1,97 +1,8 @@
1-
"""
2-
Launches the bot, starts the asyncio loop when called.
3-
"""
4-
import discord
51
from . import settings
6-
from .bot import Bot
2+
from bot.bot import Friendo
73

84
if __name__ == "__main__":
9-
bot = Bot(command_prefix=settings.COMMAND_PREFIX)
10-
bot.remove_command("help")
11-
12-
@bot.command(name="help", help="This will be shown")
13-
async def help(ctx, *, name=None):
14-
char_repeat = 20
15-
embed = discord.Embed(
16-
title=f"{'-' * (char_repeat//2)}Friendo_Bot{'-' * (char_repeat//2)}",
17-
url=settings.BASE_GITHUB_REPO,
18-
color=0x1C1C1C,
19-
)
20-
embed.set_thumbnail(
21-
url="https://images.discordapp.net/avatars/723555941118771262/8f586ecb1f89cec031d00b3a616573ea.png?size=512"
22-
)
23-
24-
if name is None:
25-
cogs = list(bot.cogs.keys())
26-
field_body = "\n".join(cogs)
27-
field_body = field_body.strip()
28-
29-
field_body += (
30-
"\n\nUsage: `%shelp [Cog | Command]`. Example: `%shelp greetings`"
31-
% (bot.command_prefix, bot.command_prefix)
32-
)
33-
34-
embed.add_field(name="Cogs", value=field_body, inline=False)
35-
else:
36-
cog = bot.cogs.get(name.title(), None)
37-
38-
if cog is None:
39-
# Check if this is not a command
40-
command = bot.get_command(name.lower())
41-
42-
if command is not None:
43-
embed.title += "\n" + command.name
44-
45-
field_body = (
46-
command.description
47-
if command.description != ""
48-
else (
49-
command.brief
50-
if command.brief != ""
51-
else "This command has no description."
52-
)
53-
)
54-
field_body += "\n" + (
55-
"Usage: `" + command.usage + "`"
56-
if command.usage is not None
57-
else ""
58-
)
59-
60-
embed.add_field(
61-
name=command.name, value=field_body.strip(), inline=False
62-
)
63-
else:
64-
field_body = (
65-
"Error: Cog or command `%s` not found! Use `%shelp` to see a list of cogs"
66-
% (name, bot.command_prefix)
67-
)
68-
embed.add_field(name="Cogs", value=field_body, inline=False)
69-
else:
70-
embed.title += "\n" + name.title()
71-
72-
for command in cog.get_commands():
73-
field_body = (
74-
(command.brief if command.brief is not None else "")
75-
+ "\n"
76-
+ (
77-
"Usage: `" + command.usage + "`"
78-
if command.usage is not None
79-
else ""
80-
)
81-
)
82-
field_body = field_body.strip()
83-
84-
embed.add_field(
85-
name=command.name,
86-
value=(
87-
field_body + "\n"
88-
if field_body != ""
89-
else "This command has no help message"
90-
),
91-
inline=False,
92-
)
93-
94-
await ctx.send(embed=embed)
5+
bot = Friendo(command_prefix=settings.COMMAND_PREFIX, help_command=None)
956

967
# load in basic commands
978
bot.load_extension("bot.cogs.greetings")

bot/bot.py

+21-19
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,19 @@
11
import asyncio
22
import logging
3-
import traceback
43

54
import aiohttp
6-
from discord.ext import commands
5+
from discord.ext.commands import Bot, CommandError, Context
76

8-
from .settings import NAME, API_COGS
97
from .disable import DisableApi
8+
from .settings import API_COGS
109

11-
logger = logging.getLogger(__name__)
10+
log = logging.getLogger(__name__)
1211

1312

14-
class Bot(commands.Bot):
13+
class Friendo(Bot):
1514
"""Base Class for the discord bot."""
1615

17-
def __init__(self, *args, **kwargs):
16+
def __init__(self, *args, **kwargs) -> None:
1817
super().__init__(*args, **kwargs)
1918

2019
# Setting the loop.
@@ -23,22 +22,16 @@ def __init__(self, *args, **kwargs):
2322
# Creating session for web requests.
2423
self.session = aiohttp.ClientSession()
2524

26-
def __str__(self):
27-
"""Returns the name of the bot."""
28-
return NAME
29-
30-
async def on_ready(self):
25+
@staticmethod
26+
async def on_ready() -> None:
3127
"""Runs when the bot is connected."""
32-
logger.info("Logged in as")
33-
logger.info(self.user.name)
34-
logger.info(self.user.id)
35-
logger.info("------")
28+
log.info('Awaiting...')
3629

37-
async def on_command_error(self, ctx, exception):
30+
async def on_command_error(self, ctx: Context, exception: CommandError) -> None:
3831
"""Fired when exception happens."""
39-
logger.error(
32+
log.error(
4033
"Exception happened while executing command",
41-
exc_info=(type(exception), exception, exception.__traceback__),
34+
exc_info=(type(exception), exception, exception.__traceback__)
4235
)
4336

4437
async def logout(self) -> None:
@@ -47,28 +40,37 @@ async def logout(self) -> None:
4740

4841
return await super().logout()
4942

50-
def load_extension(self, name):
43+
def load_extension(self, name: str) -> None:
44+
"""Loads an extension after checking if it's disabled or not."""
5145
disable_api = DisableApi()
5246
cog_name = name.split(".")[-1]
47+
5348
# If no-api is passed disable API_COGS ie. memes and events
5449
if disable_api.get_no_api() and cog_name in API_COGS:
5550
return
51+
5652
disabled_list = disable_api.get_disable()
53+
5754
if disabled_list:
5855
if cog_name in disabled_list:
5956
return
57+
6058
# If cog is not disabled, load it
6159
else:
6260
super().load_extension(name)
6361
return
62+
6463
enabled_list = disable_api.get_enable()
64+
6565
if enabled_list:
6666
# If cog is enabled, load it
6767
if cog_name in enabled_list:
6868
super().load_extension(name)
6969
return
70+
7071
# Don't load cogs not passed along with enable
7172
else:
7273
return
74+
7375
# load cogs if no argument is passed
7476
super().load_extension(name)

bot/cogs/__init__.py

-3
This file was deleted.

bot/cogs/admin.py

+31-36
Original file line numberDiff line numberDiff line change
@@ -1,78 +1,73 @@
1-
"""
2-
Contains all commands relating to admin duties and permissions.
3-
"""
4-
51
import json
62
import logging
3+
from pathlib import Path
74
import re
5+
from typing import Callable, Optional
86

9-
from discord.ext.commands import Bot, Cog, command, check
7+
from discord import Member
8+
from discord.ext.commands import Cog, Context, check, command
109

11-
from bot.settings import BASE_DIR
10+
from bot.bot import Friendo
1211

13-
logger = logging.getLogger(__name__)
12+
log = logging.getLogger(__name__)
1413

1514

16-
def is_admin():
15+
def is_admin() -> Callable:
1716
"""Return whether or not the user invoking a command is an admin."""
1817

19-
def predicate(ctx):
20-
with open(f"{BASE_DIR}/save_data.JSON", "r") as data:
21-
save_data = json.load(data)
18+
def predicate(ctx: Context) -> bool:
19+
"""Opening the admin json config file."""
20+
with open(Path.cwd() / "save_data.json", "r") as file:
21+
save_data = json.load(file)
22+
2223
return str(ctx.message.author.id) in save_data["admins"]
2324

2425
return check(predicate)
2526

2627

27-
def id_from_mention(message_content: str):
28+
def id_from_mention(message_content: str) -> Optional[int]:
2829
"""Return a user id from an @mention in a message."""
30+
get_id = re.search(r"\d{18}", message_content)
2931

30-
pattern = r"\d{18}"
31-
get_id = re.search(pattern, message_content)
3232
if get_id is not None:
3333
return int(get_id.group())
34-
return None
3534

3635

37-
class AdminCommands(Cog):
38-
"""
39-
Commands for bot and server administration, all require the admin status on the invoking user.
40-
"""
36+
class Administration(Cog):
37+
"""Commands for bot and server administration, all require the admin status on the invoking user."""
4138

42-
def __init__(self, bot: Bot):
39+
def __init__(self, bot: Friendo) -> None:
4340
self.bot = bot
4441

4542
@command(brief="Kills your robotic friend")
4643
@is_admin()
47-
async def shutdown(self, ctx):
44+
async def shutdown(self, ctx: Context) -> None:
4845
"""Cleanly shuts down the bot."""
46+
await ctx.send("Mr. Stark, I don't feel so good...")
47+
48+
log.info("Closing Client...")
4949

50-
msg = "Mr. Stark, I don't feel so good. . ."
51-
await ctx.send(msg)
52-
logger.info("Closing Client...")
5350
await self.bot.logout()
5451

5552
@command(name="createadmin", brief="gives the @mention user admin permissions")
5653
@is_admin()
57-
async def create_admin(self, ctx, user):
54+
async def create_admin(self, ctx: Context, member: Member) -> None:
5855
"""Adds a new user id to the list of admins."""
56+
msg = f"Could not create admin from {member.name}"
5957

60-
msg = f"Could not create admin from {user}"
61-
62-
with open(f"{BASE_DIR}/save_data.JSON", "r") as data:
63-
save_data = json.load(data)
58+
with open(Path.cwd() / "save_data.json", "r") as file:
59+
save_data = json.load(file)
6460

65-
this_user = self.bot.get_user(id_from_mention(ctx.message.content))
61+
if str(member.id) not in save_data["admins"]:
62+
save_data["admins"].append(str(member.id))
6663

67-
if this_user and str(this_user.id) not in save_data["admins"]:
68-
save_data["admins"].append(str(this_user.id))
69-
with open(f"{BASE_DIR}/save_data.JSON", "w") as file:
64+
with open(Path.cwd() / "save_data.json", "r") as file:
7065
json.dump(save_data, file)
71-
msg = f"{ctx.author.mention}, {user} added to admins"
66+
msg = f"{ctx.author.mention}, {member.name} has been added to admins"
7267

7368
await ctx.send(msg)
7469

7570

76-
def setup(bot: Bot) -> None:
71+
def setup(bot: Friendo) -> None:
7772
"""Load the Admin cog."""
78-
bot.add_cog(AdminCommands(bot))
73+
bot.add_cog(Administration(bot))

0 commit comments

Comments
 (0)