Skip to content

Commit 1afd94e

Browse files
committed
Template v2.5
* Code reformat * Rewrote the status task * Now using the `has_permissions` decorator for user permissions * Using `.yaml` instead of `.py` file for config
1 parent 4e58c5b commit 1afd94e

13 files changed

+489
-476
lines changed

LICENSE.md

+126-183
Large diffs are not rendered by default.

README.md

+32-10
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# Python Discord Bot Template
2+
23
<p align="center">
34
<a href="//discord.gg/HzJ3Gfr"><img src="https://img.shields.io/discord/739934735387721768?logo=discord"></a>
45
<a href="//github.com/kkrypt0nn/Python-Discord-Bot-Template/releases"><img src="https://img.shields.io/github/v/release/kkrypt0nn/Python-Discord-Bot-Template"></a>
@@ -11,39 +12,52 @@
1112

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

14-
When I first started creating my discord bot it took me a while to get everything setup and working with cogs and more. I would've been happy if there were any template existing. But there wasn't any existing template. That's why I decided to create my own template to let <b>you</b> guys create your discord bot in an easy way.
15+
When I first started creating my discord bot it took me a while to get everything setup and working with cogs and more.
16+
I would've been happy if there were any template existing. But there wasn't any existing template. That's why I decided
17+
to create my own template to let <b>you</b> guys create your discord bot in an easy way.
1518

16-
Please note that this template is not supposed to be the best template, but a good template to start learning how discord.py works and to make your own bot in a simple way. You're
19+
Please note that this template is not supposed to be the best template, but a good template to start learning how
20+
discord.py works and to make your own bot in a simple way. You're
1721

18-
If you plan to use this template to make your own template or bot, you **have to** give me credits somewhere and keep the copyright notice on the files. See [the license file](https://github.com/kkrypt0nn/Python-Discord-Bot-Template/blob/master/LICENSE.md) for more information.
22+
If you plan to use this template to make your own template or bot, you **have to** give me credits somewhere and keep
23+
the copyright notice on the files.
24+
See [the license file](https://github.com/kkrypt0nn/Python-Discord-Bot-Template/blob/master/LICENSE.md) for more
25+
information.
1926

2027
## Authors
28+
2129
* **[Krypton (@kkrypt0nn)](https://github.com/kkrypt0nn)**
2230

2331
## Support
2432

25-
Before requesting support you should know that this template requires you to have a **basic knowledge** of Python. Do not use this template if you don't know the basics. [Here's](https://pythondiscord.com/pages/resources) a link for resources to learn python.
33+
Before requesting support you should know that this template requires you to have a **basic knowledge** of Python. Do
34+
not use this template if you don't know the basics. [Here's](https://pythondiscord.com/pages/resources) a link for
35+
resources to learn python.
2636

2737
If you need some help for something, do not hesitate to join my discord server [here](https://discord.gg/HzJ3Gfr).
2838

2939
All the updates of the template are available [here](UPDATES.md).
3040

3141
## How to download it
3242

33-
This repository is now a template, on the top left you can simple click on "**Use this template**" to create a GitHub repository based on this template.
43+
This repository is now a template, on the top left you can simple click on "**Use this template**" to create a GitHub
44+
repository based on this template.
3445

3546
Alternatively you can do the following:
47+
3648
* Clone/Download the repository
3749
* To clone it and get the updates you can definitely use the command
38-
`git clone`
50+
`git clone`
3951
* Create a discord bot [here](https://discord.com/developers/applications)
4052
* Get your bot token
4153
* Invite your bot on servers using the following invite:
42-
https://discordapp.com/oauth2/authorize?&client_id=YOUR_APPLICATION_ID_HERE&scope=bot&permissions=8 (Replace `YOUR_APPLICATION_ID_HERE` with the application ID)
54+
https://discordapp.com/oauth2/authorize?&client_id=YOUR_APPLICATION_ID_HERE&scope=bot&permissions=8 (
55+
Replace `YOUR_APPLICATION_ID_HERE` with the application ID)
4356

4457
## How to setup
4558

46-
To setup the bot I made it as simple as possible. I now created a [config.py](config.py) file where you can put the needed things to edit.
59+
To set up the bot I made it as simple as possible. I now created a [config.yaml](config.yaml) file where you can put the
60+
needed things to edit.
4761

4862
Here is an explanation of what everything is:
4963

@@ -57,24 +71,31 @@ Here is an explanation of what everything is:
5771

5872
## How to start
5973

60-
To start the bot you simply need to launch, either your terminal (Linux, Mac & Windows) or your Command Prompt (Windows).
74+
To start the bot you simply need to launch, either your terminal (Linux, Mac & Windows) or your Command Prompt (Windows)
75+
.
6176

6277
Before running the bot you will need to install all the requirements with this command:
78+
6379
```
6480
pip install -r requirements.txt
6581
```
6682

6783
If you have multiple versions of python installed (2.x and 3.x) then you will need to use the following command:
84+
6885
```
6986
python3 bot.py
7087
```
88+
7189
or eventually
90+
7291
```
7392
python3.8 bot.py
7493
```
94+
7595
<br>
7696

7797
If you have just installed python today, then you just need to use the following command:
98+
7899
```
79100
python bot.py
80101
```
@@ -94,7 +115,8 @@ Me or other people will take their time to answer and help you.
94115

95116
## Versioning
96117

97-
We use [SemVer](http://semver.org) for versioning. For the versions available, see the [tags on this repository](https://github.com/kkrypt0nn/Python-Discord-Bot-Template/tags).
118+
We use [SemVer](http://semver.org) for versioning. For the versions available, see
119+
the [tags on this repository](https://github.com/kkrypt0nn/Python-Discord-Bot-Template/tags).
98120

99121
## Bots who used this template
100122

UPDATES.md

+17
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,56 @@
11
# Updates List
2+
23
Here is the list of all the updates that I made on this template.
34

5+
### Version 2.5
6+
7+
* Code reformat
8+
* Rewrote the status task
9+
* Now using the `has_permissions` decorator for user permissions
10+
* Using `.yaml` instead of `.py` file for config
11+
412
### Version 2.4.3
13+
514
* Fixed intents for `serverinfo` command
615

716
### Version 2.4.2
17+
818
* Blacklisted users are being ignored when executing a command
919

1020
### Version 2.4.1
21+
1122
* Added config import to moderation cog
1223

1324
### Version 2.4
25+
1426
* Added some fun commands
1527
* Colors are saved in the [config file](config.py) for easier usage
1628
* Cogs are now being loaded automatically
1729
* Fixed some typos
1830

1931
### Version 2.3
32+
2033
* Made the kick command actually kick
2134
* Added a template cog to create cogs easily
2235

2336
### Version 2.2
37+
2438
* Fixed the purge command
2539
* Made the error embeds actually red...
2640

2741
### Version 2.1
42+
2843
* Made the help command dynamic
2944
* Added a small description to all commands
3045
* Added intents when creating the bot
3146

3247
### Version 2.0
48+
3349
* Added cogs
3450
* Added f-strings and removed `.format()`
3551
* Created [config file](config.py) for easier setup
3652

3753
### Version 1.2
54+
3855
* Added blacklist command
3956
* Removed commands cool down

bot.py

+71-53
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,24 @@
33
Description:
44
This is a template to create your own discord bot in python.
55
6-
Version: 2.4.3
6+
Version: 2.5
77
"""
88

9-
import discord, asyncio, os, platform, sys
9+
import os
10+
import platform
11+
import random
12+
import sys
13+
14+
import discord
15+
import yaml
16+
from discord.ext import commands, tasks
1017
from discord.ext.commands import Bot
11-
from discord.ext import commands
1218

13-
if not os.path.isfile("config.py"):
14-
sys.exit("'config.py' not found! Please add it and try again.")
19+
if not os.path.isfile("config.yaml"):
20+
sys.exit("'config.yaml' not found! Please add it and try again.")
1521
else:
16-
import config
22+
with open("config.yaml") as file:
23+
config = yaml.load(file, Loader=yaml.FullLoader)
1724

1825
"""
1926
Setup bot intents (events restrictions)
@@ -40,81 +47,92 @@
4047
intents.voice_states = False
4148
intents.webhooks = False
4249
43-
Privileged Intents (Needs to be enabled on dev page):
50+
Privileged Intents (Needs to be enabled on dev page), please use them only if you need them:
4451
intents.presences = True
4552
intents.members = True
4653
"""
4754

48-
intents = discord.Intents.all()
55+
intents = discord.Intents.default()
56+
57+
bot = Bot(command_prefix=config["bot_prefix"], intents=intents)
4958

50-
bot = Bot(command_prefix=config.BOT_PREFIX, intents=intents)
5159

5260
# The code in this even is executed when the bot is ready
5361
@bot.event
5462
async def on_ready():
55-
bot.loop.create_task(status_task())
56-
print(f"Logged in as {bot.user.name}")
57-
print(f"Discord.py API version: {discord.__version__}")
58-
print(f"Python version: {platform.python_version()}")
59-
print(f"Running on: {platform.system()} {platform.release()} ({os.name})")
60-
print("-------------------")
63+
print(f"Logged in as {bot.user.name}")
64+
print(f"Discord.py API version: {discord.__version__}")
65+
print(f"Python version: {platform.python_version()}")
66+
print(f"Running on: {platform.system()} {platform.release()} ({os.name})")
67+
print("-------------------")
68+
status_task.start()
69+
6170

6271
# Setup the game status task of the bot
72+
@tasks.loop(minutes=1.0)
6373
async def status_task():
64-
while True:
65-
await bot.change_presence(activity=discord.Game("with you!"))
66-
await asyncio.sleep(60)
67-
await bot.change_presence(activity=discord.Game("with Krypton!"))
68-
await asyncio.sleep(60)
69-
await bot.change_presence(activity=discord.Game(f"{config.BOT_PREFIX} help"))
70-
await asyncio.sleep(60)
71-
await bot.change_presence(activity=discord.Game("with humans!"))
72-
await asyncio.sleep(60)
74+
statuses = ["with you!", "with Krypton!", f"{config['bot_prefix']}help", "with humans!"]
75+
await bot.change_presence(activity=discord.Game(random.choice(statuses)))
76+
7377

7478
# Removes the default help command of discord.py to be able to create our custom help command.
7579
bot.remove_command("help")
7680

7781
if __name__ == "__main__":
78-
for file in os.listdir("./cogs"):
79-
if file.endswith(".py"):
80-
extension = file[:-3]
81-
try:
82-
bot.load_extension(f"cogs.{extension}")
83-
print(f"Loaded extension '{extension}'")
84-
except Exception as e:
85-
exception = f"{type(e).__name__}: {e}"
86-
print(f"Failed to load extension {extension}\n{exception}")
82+
for file in os.listdir("./cogs"):
83+
if file.endswith(".py"):
84+
extension = file[:-3]
85+
try:
86+
bot.load_extension(f"cogs.{extension}")
87+
print(f"Loaded extension '{extension}'")
88+
except Exception as e:
89+
exception = f"{type(e).__name__}: {e}"
90+
print(f"Failed to load extension {extension}\n{exception}")
91+
8792

8893
# The code in this event is executed every time someone sends a message, with or without the prefix
8994
@bot.event
9095
async def on_message(message):
91-
# Ignores if a command is being executed by a bot or by the bot itself
92-
if message.author == bot.user or message.author.bot:
93-
return
94-
# Ignores if a command is being executed by a blacklisted user
95-
if message.author.id in config.BLACKLIST:
96-
return
97-
await bot.process_commands(message)
96+
# Ignores if a command is being executed by a bot or by the bot itself
97+
if message.author == bot.user or message.author.bot:
98+
return
99+
# Ignores if a command is being executed by a blacklisted user
100+
101+
if message.author.id in config["blacklist"]:
102+
return
103+
await bot.process_commands(message)
104+
98105

99106
# The code in this event is executed every time a command has been *successfully* executed
100107
@bot.event
101108
async def on_command_completion(ctx):
102-
fullCommandName = ctx.command.qualified_name
103-
split = fullCommandName.split(" ")
104-
executedCommand = str(split[0])
105-
print(f"Executed {executedCommand} command in {ctx.guild.name} (ID: {ctx.message.guild.id}) by {ctx.message.author} (ID: {ctx.message.author.id})")
109+
fullCommandName = ctx.command.qualified_name
110+
split = fullCommandName.split(" ")
111+
executedCommand = str(split[0])
112+
print(
113+
f"Executed {executedCommand} command in {ctx.guild.name} (ID: {ctx.message.guild.id}) by {ctx.message.author} (ID: {ctx.message.author.id})")
114+
106115

107116
# The code in this event is executed every time a valid commands catches an error
108117
@bot.event
109118
async def on_command_error(context, error):
110-
if isinstance(error, commands.CommandOnCooldown):
111-
embed = discord.Embed(
112-
title="Error!",
113-
description="This command is on a %.2fs cool down" % error.retry_after,
114-
color=config.error
115-
)
116-
await context.send(embed=embed)
117-
raise error
119+
if isinstance(error, commands.CommandOnCooldown):
120+
embed = discord.Embed(
121+
title="Error!",
122+
description="This command is on a %.2fs cool down" % error.retry_after,
123+
color=config["error"]
124+
)
125+
await context.send(embed=embed)
126+
elif isinstance(error, commands.MissingPermissions):
127+
embed = discord.Embed(
128+
title="Error!",
129+
description="You are missing the permission `" + ", ".join(
130+
error.missing_perms) + "` to execute this command!",
131+
color=config["error"]
132+
)
133+
await context.send(embed=embed)
134+
raise error
135+
118136

119137
# Run the bot with the token
120-
bot.run(config.TOKEN)
138+
bot.run(config["token"])

0 commit comments

Comments
 (0)