Skip to content

Commit 2c82bf3

Browse files
committed
style: Using black formatter
1 parent 927d0e7 commit 2c82bf3

File tree

9 files changed

+294
-230
lines changed

9 files changed

+294
-230
lines changed

CONTRIBUTING.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ Pull requests are the best way to propose changes to the codebase. We actively w
2222

2323
1. Fork the repo and create your branch from `main`.
2424
2. Keep consistency with the current state of the codebase, this includes but is not limited to naming convention, Discord embeds, etc.
25-
3. Format the code of the files you've edited with the **autopep8** formatter.
25+
3. Format the code of the files you've edited with the **black** formatter.
2626
4. Issue that pull request!
2727

2828
## Commit messages guidelines

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66
<a href="https://github.com/kkrypt0nn/Python-Discord-Bot-Template/commits/main"><img src="https://img.shields.io/github/last-commit/kkrypt0nn/Python-Discord-Bot-Template"></a>
77
<a href="https://github.com/kkrypt0nn/Python-Discord-Bot-Template/blob/main/LICENSE.md"><img src="https://img.shields.io/github/license/kkrypt0nn/Python-Discord-Bot-Template"></a>
88
<a href="https://github.com/kkrypt0nn/Python-Discord-Bot-Template"><img src="https://img.shields.io/github/languages/code-size/kkrypt0nn/Python-Discord-Bot-Template"></a>
9-
<a href="https://github.com/kkrypt0nn/Python-Discord-Bot-Template/issues"><img src="https://img.shields.io/github/issues-raw/kkrypt0nn/Python-Discord-Bot-Template"></a>
109
<a href="https://conventionalcommits.org/en/v1.0.0/"><img src="https://img.shields.io/badge/Conventional%20Commits-1.0.0-%23FE5196?logo=conventionalcommits&logoColor=white"></a>
10+
<a href="https://github.com/psf/black"><img src="https://img.shields.io/badge/code%20style-black-000000.svg"></a>
1111
</p>
1212

1313
This repository is a template that everyone can use for the start of their discord bot.

bot.py

Lines changed: 45 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -70,10 +70,15 @@
7070
"""
7171
# intents.message_content = True
7272

73-
bot = Bot(command_prefix=commands.when_mentioned_or(
74-
config["prefix"]), intents=intents, help_command=None)
73+
bot = Bot(
74+
command_prefix=commands.when_mentioned_or(config["prefix"]),
75+
intents=intents,
76+
help_command=None,
77+
)
7578

7679
# Setup both of the loggers
80+
81+
7782
class LoggingFormatter(logging.Formatter):
7883
# Colors
7984
black = "\x1b[30m"
@@ -91,7 +96,7 @@ class LoggingFormatter(logging.Formatter):
9196
logging.INFO: blue + bold,
9297
logging.WARNING: yellow + bold,
9398
logging.ERROR: red,
94-
logging.CRITICAL: red + bold
99+
logging.CRITICAL: red + bold,
95100
}
96101

97102
def format(self, record):
@@ -112,10 +117,10 @@ def format(self, record):
112117
console_handler = logging.StreamHandler()
113118
console_handler.setFormatter(LoggingFormatter())
114119
# File handler
115-
file_handler = logging.FileHandler(
116-
filename="discord.log", encoding="utf-8", mode="w")
120+
file_handler = logging.FileHandler(filename="discord.log", encoding="utf-8", mode="w")
117121
file_handler_formatter = logging.Formatter(
118-
"[{asctime}] [{levelname:<8}] {name}: {message}", "%Y-%m-%d %H:%M:%S", style="{")
122+
"[{asctime}] [{levelname:<8}] {name}: {message}", "%Y-%m-%d %H:%M:%S", style="{"
123+
)
119124
file_handler.setFormatter(file_handler_formatter)
120125

121126
# Add the handlers
@@ -125,8 +130,12 @@ def format(self, record):
125130

126131

127132
async def init_db():
128-
async with aiosqlite.connect(f"{os.path.realpath(os.path.dirname(__file__))}/database/database.db") as db:
129-
with open(f"{os.path.realpath(os.path.dirname(__file__))}/database/schema.sql") as file:
133+
async with aiosqlite.connect(
134+
f"{os.path.realpath(os.path.dirname(__file__))}/database/database.db"
135+
) as db:
136+
with open(
137+
f"{os.path.realpath(os.path.dirname(__file__))}/database/schema.sql"
138+
) as file:
130139
await db.executescript(file.read())
131140
await db.commit()
132141

@@ -149,8 +158,7 @@ async def on_ready() -> None:
149158
bot.logger.info(f"Logged in as {bot.user.name}")
150159
bot.logger.info(f"discord.py API version: {discord.__version__}")
151160
bot.logger.info(f"Python version: {platform.python_version()}")
152-
bot.logger.info(
153-
f"Running on: {platform.system()} {platform.release()} ({os.name})")
161+
bot.logger.info(f"Running on: {platform.system()} {platform.release()} ({os.name})")
154162
bot.logger.info("-------------------")
155163
status_task.start()
156164
if config["sync_commands_globally"]:
@@ -191,10 +199,12 @@ async def on_command_completion(context: Context) -> None:
191199
executed_command = str(split[0])
192200
if context.guild is not None:
193201
bot.logger.info(
194-
f"Executed {executed_command} command in {context.guild.name} (ID: {context.guild.id}) by {context.author} (ID: {context.author.id})")
202+
f"Executed {executed_command} command in {context.guild.name} (ID: {context.guild.id}) by {context.author} (ID: {context.author.id})"
203+
)
195204
else:
196205
bot.logger.info(
197-
f"Executed {executed_command} command by {context.author} (ID: {context.author.id}) in DMs")
206+
f"Executed {executed_command} command by {context.author} (ID: {context.author.id}) in DMs"
207+
)
198208

199209

200210
@bot.event
@@ -211,7 +221,7 @@ async def on_command_error(context: Context, error) -> None:
211221
hours = hours % 24
212222
embed = discord.Embed(
213223
description=f"**Please slow down** - You can use this command again in {f'{round(hours)} hours' if round(hours) > 0 else ''} {f'{round(minutes)} minutes' if round(minutes) > 0 else ''} {f'{round(seconds)} seconds' if round(seconds) > 0 else ''}.",
214-
color=0xE02B2B
224+
color=0xE02B2B,
215225
)
216226
await context.send(embed=embed)
217227
elif isinstance(error, exceptions.UserBlacklisted):
@@ -220,49 +230,55 @@ async def on_command_error(context: Context, error) -> None:
220230
the @checks.not_blacklisted() check in your command, or you can raise the error by yourself.
221231
"""
222232
embed = discord.Embed(
223-
description="You are blacklisted from using the bot!",
224-
color=0xE02B2B
233+
description="You are blacklisted from using the bot!", color=0xE02B2B
225234
)
226235
await context.send(embed=embed)
227236
if context.guild:
228-
bot.logger.warning(f"{context.author} (ID: {context.author.id}) tried to execute a command in the guild {context.guild.name} (ID: {context.guild.id}), but the user is blacklisted from using the bot.")
237+
bot.logger.warning(
238+
f"{context.author} (ID: {context.author.id}) tried to execute a command in the guild {context.guild.name} (ID: {context.guild.id}), but the user is blacklisted from using the bot."
239+
)
229240
else:
230-
bot.logger.warning(f"{context.author} (ID: {context.author.id}) tried to execute a command in the bot's DMs, but the user is blacklisted from using the bot.")
241+
bot.logger.warning(
242+
f"{context.author} (ID: {context.author.id}) tried to execute a command in the bot's DMs, but the user is blacklisted from using the bot."
243+
)
231244
elif isinstance(error, exceptions.UserNotOwner):
232245
"""
233246
Same as above, just for the @checks.is_owner() check.
234247
"""
235248
embed = discord.Embed(
236-
description="You are not the owner of the bot!",
237-
color=0xE02B2B
249+
description="You are not the owner of the bot!", color=0xE02B2B
238250
)
239251
await context.send(embed=embed)
240252
if context.guild:
241253
bot.logger.warning(
242-
f"{context.author} (ID: {context.author.id}) tried to execute an owner only command in the guild {context.guild.name} (ID: {context.guild.id}), but the user is not an owner of the bot.")
254+
f"{context.author} (ID: {context.author.id}) tried to execute an owner only command in the guild {context.guild.name} (ID: {context.guild.id}), but the user is not an owner of the bot."
255+
)
243256
else:
244257
bot.logger.warning(
245-
f"{context.author} (ID: {context.author.id}) tried to execute an owner only command in the bot's DMs, but the user is not an owner of the bot.")
258+
f"{context.author} (ID: {context.author.id}) tried to execute an owner only command in the bot's DMs, but the user is not an owner of the bot."
259+
)
246260
elif isinstance(error, commands.MissingPermissions):
247261
embed = discord.Embed(
248-
description="You are missing the permission(s) `" + ", ".join(
249-
error.missing_permissions) + "` to execute this command!",
250-
color=0xE02B2B
262+
description="You are missing the permission(s) `"
263+
+ ", ".join(error.missing_permissions)
264+
+ "` to execute this command!",
265+
color=0xE02B2B,
251266
)
252267
await context.send(embed=embed)
253268
elif isinstance(error, commands.BotMissingPermissions):
254269
embed = discord.Embed(
255-
description="I am missing the permission(s) `" + ", ".join(
256-
error.missing_permissions) + "` to fully perform this command!",
257-
color=0xE02B2B
270+
description="I am missing the permission(s) `"
271+
+ ", ".join(error.missing_permissions)
272+
+ "` to fully perform this command!",
273+
color=0xE02B2B,
258274
)
259275
await context.send(embed=embed)
260276
elif isinstance(error, commands.MissingRequiredArgument):
261277
embed = discord.Embed(
262278
title="Error!",
263279
# We need to capitalize because the command arguments have no capital letter in the code.
264280
description=str(error).capitalize(),
265-
color=0xE02B2B
281+
color=0xE02B2B,
266282
)
267283
await context.send(embed=embed)
268284
else:
@@ -281,8 +297,7 @@ async def load_cogs() -> None:
281297
bot.logger.info(f"Loaded extension '{extension}'")
282298
except Exception as e:
283299
exception = f"{type(e).__name__}: {e}"
284-
bot.logger.error(
285-
f"Failed to load extension {extension}\n{exception}")
300+
bot.logger.error(f"Failed to load extension {extension}\n{exception}")
286301

287302

288303
asyncio.run(init_db())

cogs/fun.py

Lines changed: 21 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@ def __init__(self):
2222
self.value = None
2323

2424
@discord.ui.button(label="Heads", style=discord.ButtonStyle.blurple)
25-
async def confirm(self, button: discord.ui.Button, interaction: discord.Interaction):
25+
async def confirm(
26+
self, button: discord.ui.Button, interaction: discord.Interaction
27+
):
2628
self.value = "heads"
2729
self.stop()
2830

@@ -66,8 +68,7 @@ async def callback(self, interaction: discord.Interaction):
6668

6769
result_embed = discord.Embed(color=0x9C84EF)
6870
result_embed.set_author(
69-
name=interaction.user.name,
70-
icon_url=interaction.user.avatar.url
71+
name=interaction.user.name, icon_url=interaction.user.avatar.url
7172
)
7273

7374
if user_choice_index == bot_choice_index:
@@ -83,9 +84,13 @@ async def callback(self, interaction: discord.Interaction):
8384
result_embed.description = f"**You won!**\nYou've chosen {user_choice} and I've chosen {bot_choice}."
8485
result_embed.colour = 0x9C84EF
8586
else:
86-
result_embed.description = f"**I won!**\nYou've chosen {user_choice} and I've chosen {bot_choice}."
87+
result_embed.description = (
88+
f"**I won!**\nYou've chosen {user_choice} and I've chosen {bot_choice}."
89+
)
8790
result_embed.colour = 0xE02B2B
88-
await interaction.response.edit_message(embed=result_embed, content=None, view=None)
91+
await interaction.response.edit_message(
92+
embed=result_embed, content=None, view=None
93+
)
8994

9095

9196
class RockPaperScissorsView(discord.ui.View):
@@ -98,10 +103,7 @@ class Fun(commands.Cog, name="fun"):
98103
def __init__(self, bot):
99104
self.bot = bot
100105

101-
@commands.hybrid_command(
102-
name="randomfact",
103-
description="Get a random fact."
104-
)
106+
@commands.hybrid_command(name="randomfact", description="Get a random fact.")
105107
@checks.not_blacklisted()
106108
async def randomfact(self, context: Context) -> None:
107109
"""
@@ -111,24 +113,22 @@ async def randomfact(self, context: Context) -> None:
111113
"""
112114
# This will prevent your bot from stopping everything when doing a web request - see: https://discordpy.readthedocs.io/en/stable/faq.html#how-do-i-make-a-web-request
113115
async with aiohttp.ClientSession() as session:
114-
async with session.get("https://uselessfacts.jsph.pl/random.json?language=en") as request:
116+
async with session.get(
117+
"https://uselessfacts.jsph.pl/random.json?language=en"
118+
) as request:
115119
if request.status == 200:
116120
data = await request.json()
117-
embed = discord.Embed(
118-
description=data["text"],
119-
color=0xD75BF4
120-
)
121+
embed = discord.Embed(description=data["text"], color=0xD75BF4)
121122
else:
122123
embed = discord.Embed(
123124
title="Error!",
124125
description="There is something wrong with the API, please try again later",
125-
color=0xE02B2B
126+
color=0xE02B2B,
126127
)
127128
await context.send(embed=embed)
128129

129130
@commands.hybrid_command(
130-
name="coinflip",
131-
description="Make a coin flip, but give your bet before."
131+
name="coinflip", description="Make a coin flip, but give your bet before."
132132
)
133133
@checks.not_blacklisted()
134134
async def coinflip(self, context: Context) -> None:
@@ -138,28 +138,24 @@ async def coinflip(self, context: Context) -> None:
138138
:param context: The hybrid command context.
139139
"""
140140
buttons = Choice()
141-
embed = discord.Embed(
142-
description="What is your bet?",
143-
color=0x9C84EF
144-
)
141+
embed = discord.Embed(description="What is your bet?", color=0x9C84EF)
145142
message = await context.send(embed=embed, view=buttons)
146143
await buttons.wait() # We wait for the user to click a button.
147144
result = random.choice(["heads", "tails"])
148145
if buttons.value == result:
149146
embed = discord.Embed(
150147
description=f"Correct! You guessed `{buttons.value}` and I flipped the coin to `{result}`.",
151-
color=0x9C84EF
148+
color=0x9C84EF,
152149
)
153150
else:
154151
embed = discord.Embed(
155152
description=f"Woops! You guessed `{buttons.value}` and I flipped the coin to `{result}`, better luck next time!",
156-
color=0xE02B2B
153+
color=0xE02B2B,
157154
)
158155
await message.edit(embed=embed, view=None, content=None)
159156

160157
@commands.hybrid_command(
161-
name="rps",
162-
description="Play the rock paper scissors game against the bot."
158+
name="rps", description="Play the rock paper scissors game against the bot."
163159
)
164160
@checks.not_blacklisted()
165161
async def rock_paper_scissors(self, context: Context) -> None:

0 commit comments

Comments
 (0)