-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
158 lines (127 loc) · 5.24 KB
/
bot.py
File metadata and controls
158 lines (127 loc) · 5.24 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
149
150
151
152
153
154
155
156
157
158
"""
------------------------------------------------------------------------------
Copyright © Gengar-lab 2021 - https://github.com/Gengar-lab
Version: 1.3v
------------------------------------------------------------------------------
"""
import json
import os
import platform
import random
import discord
from discord.ext import commands, tasks
from dotenv import load_dotenv
from helpers import exceptions
# Get configuration
with open("config.json", encoding="utf-8") as file:
config = json.load(file)
# Get token of bot
load_dotenv()
TOKEN = os.environ.get("TOKEN")
# Set intents
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix=commands.when_mentioned_or(config["bot_prefix"]), intents=intents)
# Remove the default help command of discord.py
bot.remove_command("help")
bot.config = config
@bot.event
async def on_ready():
"""This 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()
@bot.event
async def setup_hook():
"""Load our modules when the bot is run"""
for infile in os.listdir("./cogs"):
if infile.endswith(".py"):
extension = infile[:-3]
try:
await bot.load_extension(f"cogs.{extension}")
print(f"Loaded extension '{extension}'")
except Exception as e: # If module fails to load, let us know the error
exception = f"{type(e).__name__}: {e}"
print(f"Failed to load extension {extension}\n{exception}")
# await bot.tree.sync()
@tasks.loop(minutes=60.0) # Change status after 60 minutes
async def status_task():
"""Setup the game status task of the bot"""
with open("config.json", encoding="utf-8") as infile:
body = json.load(infile)
status = random.choice(body["statuses"])
await bot.change_presence(status=discord.Status.idle,
activity=discord.Game(status))
@bot.event
async def on_message(message: discord.Message):
"""This is executed every time when someone sends a message"""
# Ignore if a command is being executed by a bot or by the bot itself
if message.author == bot.user or message.author.bot:
return
# Ignore if a command is being executed by a blacklisted user
with open("blacklist.json", encoding="utf-8") as infile:
blacklist = json.load(infile)
if message.author.id in blacklist["ids"]:
return
await bot.process_commands(message)
@bot.event
async def on_command_completion(ctx: commands.Context):
"""This is executed every time a command has been successfully executed"""
full_command_name = ctx.command.qualified_name
split = full_command_name.split(" ")
executed_command = str(split[0])
print(f"Executed {executed_command} command in {ctx.guild.name} (ID: {ctx.message.guild.id})"
f" by {ctx.message.author} (ID: {ctx.message.author.id})")
@bot.event
async def on_command_error(ctx: commands.Context, error):
"""This is executed every time a valid command catches an error"""
if isinstance(error, commands.MissingRequiredArgument):
args = ""
args = [args.join(i) for i in str(error).split("_")]
embed = discord.Embed(
title="Error!",
description=args.strip().capitalize(),
color=0xE02B2B
)
await ctx.send(embed=embed)
elif isinstance(error, commands.MissingPermissions):
embed = discord.Embed(
title="Error!",
description=f"You are missing the permission `,{error.missing_perms}"
"` to execute this command!",
color=0xE02B2B
)
await ctx.send(embed=embed)
elif isinstance(error, commands.CommandNotFound):
err = str(error.args).split(',')[0]
print(f"Unknown command {err} in {ctx.guild.name} (ID: {ctx.message.guild.id})"
f" by {ctx.message.author} (ID: {ctx.message.author.id})")
elif 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="You can use this command again in "
f"{f'{round(hours)} hours' if round(hours) > 0 else ''} "
f"{f'{round(minutes)} minutes' if round(minutes) > 0 else ''} "
f"{f'{round(seconds)} seconds' if round(seconds) > 0 else ''}.",
color=0xE02B2B
)
await ctx.send(embed=embed)
elif isinstance(error, exceptions.UserNotOwner):
embed = discord.Embed(
title="Error!",
description="You don't have the permission to use this command.",
color=0xE02B2B
)
await ctx.send(embed=embed)
elif isinstance(error, exceptions.VoiceChError):
print(error.description)
else:
raise error
if __name__ == "__main__":
bot.run(TOKEN) # Run the bot with the token