-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbot.py
More file actions
148 lines (123 loc) · 4.92 KB
/
bot.py
File metadata and controls
148 lines (123 loc) · 4.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import asyncio
import json
import os
import platform
import random
import sys
import discord
from discord.ext import commands, tasks
from discord.ext.commands import Bot, Context
import exceptions
if not os.path.isfile(f"{os.path.realpath(os.path.dirname(__file__))}/config.json"):
sys.exit("'config.json' not found! Please add it and try again.")
else:
with open(f"{os.path.realpath(os.path.dirname(__file__))}/config.json") as file:
config = json.load(file)
intents = discord.Intents.default()
intents.message_content = True
bot = Bot(command_prefix=commands.when_mentioned_or(
config["prefix"]), intents=intents, help_command=None)
bot.config = config
@bot.event
async def on_ready() -> None:
"""
The code in this even is executed when the bot is ready
"""
print(f"Logged in as {bot.user.name}")
print(f"discord.py API version: {discord.__version__}")
print(f"Python version: {platform.python_version()}")
print(f"Running on: {platform.system()} {platform.release()} ({os.name})")
print("-------------------")
status_task.start()
if config["sync_commands_globally"]:
print("Syncing commands globally...")
await bot.tree.sync()
@tasks.loop(minutes=1.0)
async def status_task() -> None:
"""
Setup the game status task of the bot
"""
statuses = ["with you!", "with Nyom Nyom!", "with humans!"]
await bot.change_presence(activity=discord.Game(random.choice(statuses)))
@bot.event
async def on_message(message: discord.Message) -> None:
if message.author == bot.user or message.author.bot:
return
await bot.process_commands(message)
@bot.event
async def on_command_completion(context: Context) -> None:
full_command_name = context.command.qualified_name
split = full_command_name.split(" ")
executed_command = str(split[0])
if context.guild is not None:
print(
f"Executed {executed_command} command in {context.guild.name} (ID: {context.guild.id}) by {context.author} (ID: {context.author.id})")
else:
print(
f"Executed {executed_command} command by {context.author} (ID: {context.author.id}) in DMs")
@bot.event
async def on_command_error(context: Context, error) -> None:
if isinstance(error, commands.CommandOnCooldown):
minutes, seconds = divmod(error.retry_after, 60)
hours, minutes = divmod(minutes, 60)
hours = hours % 24
embed = discord.Embed(
title="Hey, please slow down!",
description=f"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 ''}.",
color=0xE02B2B
)
await context.send(embed=embed)
elif isinstance(error, exceptions.UserBlacklisted):
embed = discord.Embed(
title="Error!",
description="You are blacklisted from using the bot.",
color=0xE02B2B
)
await context.send(embed=embed)
elif isinstance(error, exceptions.UserNotOwner):
"""
Same as above, just for the @checks.is_owner() check.
"""
embed = discord.Embed(
title="Error!",
description="You are not the owner of the bot!",
color=0xE02B2B
)
await context.send(embed=embed)
elif isinstance(error, commands.MissingPermissions):
embed = discord.Embed(
title="Error!",
description="You are missing the permission(s) `" + ", ".join(
error.missing_permissions) + "` to execute this command!",
color=0xE02B2B
)
await context.send(embed=embed)
elif isinstance(error, commands.BotMissingPermissions):
embed = discord.Embed(
title="Error!",
description="I am missing the permission(s) `" + ", ".join(
error.missing_permissions) + "` to fully perform this command!",
color=0xE02B2B
)
await context.send(embed=embed)
elif isinstance(error, commands.MissingRequiredArgument):
embed = discord.Embed(
title="Error!",
# We need to capitalize because the command arguments have no capital letter in the code.
description=str(error).capitalize(),
color=0xE02B2B
)
await context.send(embed=embed)
raise error
async def load_cogs() -> None:
for file in os.listdir(f"{os.path.realpath(os.path.dirname(__file__))}/cogs"):
if file.endswith(".py"):
extension = file[:-3]
try:
await bot.load_extension(f"cogs.{extension}")
print(f"Loaded extension '{extension}'")
except Exception as e:
exception = f"{type(e).__name__}: {e}"
print(f"Failed to load extension {extension}\n{exception}")
asyncio.run(load_cogs())
bot.run(config["token"])