Skip to content

Commit 59c3737

Browse files
author
Krypton
committed
Template v3.1
* Added a `@checks.is_owner` check which raises a `UserNotOwner` exception * Added a `@checks.not_blacklisted` check which raises a `UserBlacklisted` exception * Using checks instead of same code for every command * Various code cleanup
1 parent 7538145 commit 59c3737

File tree

11 files changed

+183
-226
lines changed

11 files changed

+183
-226
lines changed

README.md

+6-5
Original file line numberDiff line numberDiff line change
@@ -46,15 +46,15 @@ the `guild_ids` parameter in the command decorator so that it gets registered in
4646
@cog_ext.cog_slash(
4747
name="command",
4848
description="Command description",
49-
guild_ids=[GUILD_ID1, GUILD_ID2] # These should be testing guild(s) ID, as always: an integer.
49+
guild_ids=[GUILD_ID1, GUILD_ID2] # These should be testing guild(s) ID, as always: an integer.
5050
)
5151
```
5252

5353
When using the template you confirm that you have read the [license](LICENSE.md) and comprehend that I can take down
5454
your repository if you do not meet these requirements.
5555

5656
Please do not open issues or pull requests about things that are written in the [TODO file](TODO.md), they are **
57-
already** under work for the version 3.0 of the template.
57+
already** under work for a future version of the template.
5858

5959
## How to download it
6060

@@ -70,7 +70,9 @@ Alternatively you can do the following:
7070
* Get your bot token
7171
* Invite your bot on servers using the following invite:
7272
https://discord.com/oauth2/authorize?&client_id=YOUR_APPLICATION_ID_HERE&scope=bot+applications.commands&permissions=PERMISSIONS (
73-
Replace `YOUR_APPLICATION_ID_HERE` with the application ID and replace `PERMISSIONS` with the required permissions your bot needs that it can be get at the bottom of a this page https://discord.com/developers/applications/YOUR_APPLICATION_ID_HERE/bot)
73+
Replace `YOUR_APPLICATION_ID_HERE` with the application ID and replace `PERMISSIONS` with the required permissions
74+
your bot needs that it can be get at the bottom of a this
75+
page https://discord.com/developers/applications/YOUR_APPLICATION_ID_HERE/bot)
7476

7577
## How to set up
7678

@@ -81,7 +83,6 @@ Here is an explanation of what everything is:
8183

8284
| Variable | What it is |
8385
| ------------------------- | ----------------------------------------------------------------------|
84-
| YOUR_BOT_PREFIX_HERE | The prefix(es) of your bot |
8586
| YOUR_BOT_TOKEN_HERE | The token of your bot |
8687
| YOUR_APPLICATION_ID_HERE | The application ID of your bot |
8788
| OWNERS | The user ID of all the bot owners |
@@ -136,7 +137,7 @@ the [tags on this repository](https://github.com/kkrypt0nn/Python-Discord-Bot-Te
136137

137138
## Built With
138139

139-
* [Python 3.8](https://www.python.org/)
140+
* [Python 3.9](https://www.python.org/)
140141

141142
## License
142143

UPDATES.md

+7
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,13 @@
22

33
Here is the list of all the updates that I made on this template.
44

5+
### Version 3.1
6+
7+
* Added a `@checks.is_owner` check which raises a `UserNotOwner` exception
8+
* Added a `@checks.not_blacklisted` check which raises a `UserBlacklisted` exception
9+
* Using checks instead of same code for every command
10+
* Various code cleanup
11+
512
### Version 3.0
613

714
**Now using slash commands**

bot.py

+20-9
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
Description:
44
This is a template to create your own discord bot in python.
55
6-
Version: 3.0
6+
Version: 3.1
77
"""
88

99
import json
@@ -17,6 +17,8 @@
1717
from discord.ext.commands import Bot
1818
from discord_slash import SlashCommand, SlashContext
1919

20+
import exceptions
21+
2022
if not os.path.isfile("config.json"):
2123
sys.exit("'config.json' not found! Please add it and try again.")
2224
else:
@@ -55,7 +57,7 @@
5557

5658
intents = discord.Intents.default()
5759

58-
bot = Bot(command_prefix=config["bot_prefix"], intents=intents)
60+
bot = Bot(command_prefix=None, intents=intents) # The command prefix is a required argument, but will never be used
5961
slash = SlashCommand(bot, sync_commands=True)
6062

6163

@@ -73,7 +75,7 @@ async def on_ready():
7375
# Setup the game status task of the bot
7476
@tasks.loop(minutes=1.0)
7577
async def status_task():
76-
statuses = ["with you!", "with Krypton!", f"{config['bot_prefix']}help", "with humans!"]
78+
statuses = ["with you!", "with Krypton!", "with humans!"]
7779
await bot.change_presence(activity=discord.Game(random.choice(statuses)))
7880

7981

@@ -94,7 +96,7 @@ async def status_task():
9496

9597
# The code in this event is executed every time someone sends a message, with or without the prefix
9698
@bot.event
97-
async def on_message(message):
99+
async def on_message(message: discord.Message):
98100
# Ignores if a command is being executed by a bot or by the bot itself
99101
if message.author == bot.user or message.author.bot:
100102
return
@@ -104,16 +106,25 @@ async def on_message(message):
104106
# The code in this event is executed every time a command has been *successfully* executed
105107
@bot.event
106108
async def on_slash_command(ctx: SlashContext):
107-
fullCommandName = ctx.name
108-
split = fullCommandName.split(" ")
109-
executedCommand = str(split[0])
109+
full_command_name = ctx.name
110+
split = full_command_name.split(" ")
111+
executed_command = str(split[0])
110112
print(
111-
f"Executed {executedCommand} command in {ctx.guild.name} (ID: {ctx.guild.id}) by {ctx.author} (ID: {ctx.author.id})")
113+
f"Executed {executed_command} command in {ctx.guild.name} (ID: {ctx.guild.id}) by {ctx.author} (ID: {ctx.author.id})")
112114

113115

114116
# The code in this event is executed every time a valid commands catches an error
115117
@bot.event
116-
async def on_command_error(context, error):
118+
async def on_slash_command_error(context: SlashContext, error: Exception):
119+
if isinstance(error, exceptions.UserBlacklisted):
120+
"""
121+
The code here will only execute if the error is an instance of 'UserBlacklisted', which can occur when using
122+
the @checks.is_owner() check in your command, or you can raise the error by yourself.
123+
124+
'hidden=True' will make so that only the user who execute the command can see the message
125+
"""
126+
print("A blacklisted user tried to execute a command.")
127+
return await context.send("You are blacklisted from using the bot.", hidden=True)
117128
raise error
118129

119130

cogs/fun.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
Description:
44
This is a template to create your own discord bot in python.
55
6-
Version: 3.0
6+
Version: 3.1
77
"""
88

99
import json
@@ -15,6 +15,8 @@
1515
from discord.ext import commands
1616
from discord_slash import cog_ext, SlashContext
1717

18+
from helpers import checks
19+
1820
if not os.path.isfile("config.json"):
1921
sys.exit("'config.json' not found! Please add it and try again.")
2022
else:
@@ -30,6 +32,7 @@ def __init__(self, bot):
3032
name="randomfact",
3133
description="Get a random fact."
3234
)
35+
@checks.not_blacklisted()
3336
async def randomfact(self, context: SlashContext):
3437
"""
3538
Get a random fact.

cogs/general.py

+16-61
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
Description:
44
This is a template to create your own discord bot in python.
55
6-
Version: 3.0
6+
Version: 3.1
77
"""
88

99
import json
@@ -18,34 +18,30 @@
1818
from discord_slash import cog_ext, SlashContext
1919
from discord_slash.utils.manage_commands import create_option
2020

21+
from helpers import checks
22+
2123
if not os.path.isfile("config.json"):
2224
sys.exit("'config.json' not found! Please add it and try again.")
2325
else:
2426
with open("config.json") as file:
2527
config = json.load(file)
2628

2729

28-
class general(commands.Cog, name="general"):
30+
class General(commands.Cog, name="general"):
2931
def __init__(self, bot):
3032
self.bot = bot
3133

3234
@cog_ext.cog_slash(
3335
name="botinfo",
3436
description="Get some useful (or not) information about the bot.",
3537
)
38+
@checks.not_blacklisted()
3639
async def botinfo(self, context: SlashContext):
3740
"""
3841
Get some useful (or not) information about the bot.
3942
"""
40-
41-
# This is, for now, only temporary
42-
with open("blacklist.json") as file:
43-
blacklist = json.load(file)
44-
if context.author.id in blacklist["ids"]:
45-
return
46-
4743
embed = discord.Embed(
48-
description="Used Krypton's template",
44+
description="Used [Krypton's](https://krypt0n.co.uk) template",
4945
color=0x42F56C
5046
)
5147
embed.set_author(
@@ -63,7 +59,7 @@ async def botinfo(self, context: SlashContext):
6359
)
6460
embed.add_field(
6561
name="Prefix:",
66-
value=f"{config['bot_prefix']}",
62+
value=f"/ (Slash Commands)",
6763
inline=False
6864
)
6965
embed.set_footer(
@@ -75,17 +71,11 @@ async def botinfo(self, context: SlashContext):
7571
name="serverinfo",
7672
description="Get some useful (or not) information about the server.",
7773
)
74+
@checks.not_blacklisted()
7875
async def serverinfo(self, context: SlashContext):
7976
"""
8077
Get some useful (or not) information about the server.
8178
"""
82-
83-
# This is, for now, only temporary
84-
with open("blacklist.json") as file:
85-
blacklist = json.load(file)
86-
if context.author.id in blacklist["ids"]:
87-
return
88-
8979
server = context.guild
9080
roles = [x.name for x in server.roles]
9181
role_length = len(roles)
@@ -130,18 +120,13 @@ async def serverinfo(self, context: SlashContext):
130120
@cog_ext.cog_slash(
131121
name="ping",
132122
description="Check if the bot is alive.",
123+
guild_ids=[909709618681364531]
133124
)
125+
@checks.not_blacklisted()
134126
async def ping(self, context: SlashContext):
135127
"""
136128
Check if the bot is alive.
137129
"""
138-
139-
# This is, for now, only temporary
140-
with open("blacklist.json") as file:
141-
blacklist = json.load(file)
142-
if context.author.id in blacklist["ids"]:
143-
return
144-
145130
embed = discord.Embed(
146131
title="🏓 Pong!",
147132
description=f"The bot latency is {round(self.bot.latency * 1000)}ms.",
@@ -153,17 +138,11 @@ async def ping(self, context: SlashContext):
153138
name="invite",
154139
description="Get the invite link of the bot to be able to invite it.",
155140
)
141+
@checks.not_blacklisted()
156142
async def invite(self, context: SlashContext):
157143
"""
158144
Get the invite link of the bot to be able to invite it.
159145
"""
160-
161-
# This is, for now, only temporary
162-
with open("blacklist.json") as file:
163-
blacklist = json.load(file)
164-
if context.author.id in blacklist["ids"]:
165-
return
166-
167146
embed = discord.Embed(
168147
description=f"Invite me by clicking [here](https://discordapp.com/oauth2/authorize?&client_id={config['application_id']}&scope=bot&permissions=470150263).",
169148
color=0xD75BF4
@@ -179,17 +158,11 @@ async def invite(self, context: SlashContext):
179158
name="server",
180159
description="Get the invite link of the discord server of the bot for some support.",
181160
)
161+
@checks.not_blacklisted()
182162
async def server(self, context: SlashContext):
183163
"""
184164
Get the invite link of the discord server of the bot for some support.
185165
"""
186-
187-
# This is, for now, only temporary
188-
with open("blacklist.json") as file:
189-
blacklist = json.load(file)
190-
if context.author.id in blacklist["ids"]:
191-
return
192-
193166
embed = discord.Embed(
194167
description=f"Join the support server for the bot by clicking [here](https://discord.gg/mTBrXyWxAF).",
195168
color=0xD75BF4
@@ -212,17 +185,11 @@ async def server(self, context: SlashContext):
212185
)
213186
],
214187
)
188+
@checks.not_blacklisted()
215189
async def poll(self, context: SlashContext, title: str):
216190
"""
217191
Create a poll where members can vote.
218192
"""
219-
220-
# This is, for now, only temporary
221-
with open("blacklist.json") as file:
222-
blacklist = json.load(file)
223-
if context.author.id in blacklist["ids"]:
224-
return
225-
226193
embed = discord.Embed(
227194
title="A new poll has been created!",
228195
description=f"{title}",
@@ -248,17 +215,11 @@ async def poll(self, context: SlashContext, title: str):
248215
)
249216
],
250217
)
218+
@checks.not_blacklisted()
251219
async def eight_ball(self, context: SlashContext, question: str):
252220
"""
253221
Ask any question to the bot.
254222
"""
255-
256-
# This is, for now, only temporary
257-
with open("blacklist.json") as file:
258-
blacklist = json.load(file)
259-
if context.author.id in blacklist["ids"]:
260-
return
261-
262223
answers = ['It is certain.', 'It is decidedly so.', 'You may rely on it.', 'Without a doubt.',
263224
'Yes - definitely.', 'As I see, yes.', 'Most likely.', 'Outlook good.', 'Yes.',
264225
'Signs point to yes.', 'Reply hazy, try again.', 'Ask again later.', 'Better not tell you now.',
@@ -278,17 +239,11 @@ async def eight_ball(self, context: SlashContext, question: str):
278239
name="bitcoin",
279240
description="Get the current price of bitcoin.",
280241
)
242+
@checks.not_blacklisted()
281243
async def bitcoin(self, context):
282244
"""
283245
Get the current price of bitcoin.
284246
"""
285-
286-
# This is, for now, only temporary
287-
with open("blacklist.json") as file:
288-
blacklist = json.load(file)
289-
if context.author.id in blacklist["ids"]:
290-
return
291-
292247
url = "https://api.coindesk.com/v1/bpi/currentprice/BTC.json"
293248
# Async HTTP request
294249
async with aiohttp.ClientSession() as session:
@@ -304,4 +259,4 @@ async def bitcoin(self, context):
304259

305260

306261
def setup(bot):
307-
bot.add_cog(general(bot))
262+
bot.add_cog(General(bot))

0 commit comments

Comments
 (0)