-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathbot.py
238 lines (185 loc) · 8.89 KB
/
bot.py
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# Discord Extreme List - Discord's unbiased list.
# Copyright (C) 2020 Cairo Mitchell-Acason
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import datetime
import json
import logging
import colouredlogs
import discord
from discord.ext import commands
from motor.motor_asyncio import AsyncIOMotorClient
from ext.checks import NoMod, NoSomething
from ext.context import EditingContext
colouredlogs.install()
with open("settings.json") as content:
settings = json.load(content)
logging.basicConfig(level=logging.INFO)
logging.getLogger("discord").setLevel(logging.WARNING)
logging.info("Starting bot")
db = AsyncIOMotorClient(settings["mongo"]["uri"])[settings["mongo"]["db"]]
botExtensions = [
"cogs.help",
"cogs.utility",
"cogs.tickets",
"cogs.tags",
"cogs.notes",
"cogs.admin",
"jishaku"
]
async def get_prefix(bot, message):
if not message.guild:
prefixes = ""
return prefixes
else:
prefixes = settings["prefix"]
return commands.when_mentioned_or(*prefixes)(bot, message)
intents = discord.Intents(guilds=True, members=True, messages=True, reactions=True)
allowed_mentions = discord.AllowedMentions(roles=False, users=False, everyone=False)
if settings["ownership"]["multiple"]:
bot = commands.Bot(command_prefix=get_prefix, case_insensitive=True, owner_ids=settings["ownership"]["owners"],
allowed_mentions=allowed_mentions, intents=intents)
else:
bot = commands.Bot(command_prefix=get_prefix, case_insensitive=True, owner_id=settings["ownership"]["owner"],
allowed_mentions=allowed_mentions, intents=intents)
bot.db = db
bot.remove_command("help")
bot.settings = settings
bot.cmd_edits = {}
if __name__ == "__main__":
for ext in botExtensions:
try:
bot.load_extension(ext)
logging.info(f"{ext} has been loaded")
except Exception as err:
logging.exception(f"An error occurred whilst loading {ext}", exc_info=err)
@bot.event
async def on_ready():
logging.info(f"Connection established! - Logged in as {bot.user} ({bot.user.id})")
game = discord.Game(name="discordextremelist.xyz", type=discord.ActivityType.watching)
await bot.change_presence(status=discord.Status.online, activity=game)
if not hasattr(bot, "uptime"):
bot.uptime = datetime.datetime.utcnow()
@bot.event
async def on_guild_join(guild):
logging.info(f"Joined guild - {guild.name} ({guild.id})")
@bot.event
async def on_user_update(_, after):
if after.bot:
db_bot = db["bots"].find_one({"_id": str(after.id)})
if db_bot:
db["bots"].update_one({"_id": str(after.id)}, {
"$set": {
"name": after.name,
"avatar": {
"hash": after.avatar,
"url": f"https://cdn.discordapp.com/avatars/{after.id}/{after.avatar}" # ffs stay consistent
}
}
})
else:
user = db["users"].find_one({"_id": str(after.id)})
if user:
db["users"].update_one({"_id": str(after.id)}, {
"$set": {
"name": after.name,
"discrim": after.discriminator,
"fullUsername": f"{after.name}#{after.discriminator}",
"avatar": {
"hash": after.avatar,
"url": f"https://cdn.discordapp.com/avatars/{after.id}/{after.avatar}" # ffs
}
}
})
@bot.event
async def on_member_join(member):
if member.bot:
db_bot = await db.bots.find_one({"_id": str(member.id)})
if str(member.guild.id) == settings["guilds"]["main"]:
if db_bot:
if db_bot["status"]["premium"]:
await member.add_roles(discord.Object(id=int(settings["roles"]["premiumBot"])),
reason="Bot is Premium on the website.")
else:
await member.add_roles(discord.Object(id=int(settings["roles"]["bot"])),
reason="Bot is Approved on the website.")
else:
await member.add_roles(discord.Object(id=int(settings["roles"]["unlisted"])),
reason="Bot is not listed on the website.")
else:
if db_bot:
if db_bot["status"]["approved"]:
await member.add_roles(discord.Object(id=int(settings["roles"]["unapprovedBot"])),
reason="Bot is not approved on the website.")
elif str(member.guild.id) == settings["guilds"]["main"]:
db_bot = await db.bots.find_one({"owner": {"id": str(member.id)}})
if db_bot is not None and db_bot["status"]["approved"]:
await member.add_roles(discord.Object(id=int(settings["roles"]["developer"])),
reason="User is a Developer on the website.")
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, (discord.Forbidden, commands.CommandNotFound)):
return
if isinstance(error, NoMod):
return await ctx.channel.send(f"{settings['formats']['noPerms']} **Invalid permission(s):** You need "
f"to be a Moderator to execute this command.")
if isinstance(error, NoSomething):
return await ctx.channel.send(settings['formats']['error'] + error.message)
if isinstance(error, commands.MissingRequiredArgument):
return await ctx.send(f"{settings['formats']['error']} **Missing arguments:** Argument `{error.param.name}` "
f"is required.")
if isinstance(error, commands.CheckFailure) and error.args:
return await ctx.channel.send(error)
if isinstance(error, commands.CommandError) and error.args:
return await ctx.channel.send(error)
logging.exception("something done fucked up", exc_info=error)
@bot.event
async def on_message(msg):
if not msg.author.bot:
ctx = await bot.get_context(msg, cls=EditingContext)
await bot.invoke(ctx)
ticket = await bot.db.tickets.find_one({
"ids.channel": str(ctx.channel.id)
})
if ticket and ticket["status"] == 0:
bot_db = await ctx.bot.db.bots.find_one({
"_id": str(ticket["ids"]["bot"])
})
if bot_db and bot_db["owner"]["id"] == str(ctx.author.id):
message = await ctx.channel.fetch_message(int(ticket["ids"]["message"]))
embed = message.embeds[0]
embed.colour = 0x0fb9fc
embed.set_author(name=f"Approval Feedback - {ticket['_id']} [DEV REPLIED]",
icon_url=ctx.bot.settings["images"]["dev_replied"])
await message.edit(embed=embed)
await ctx.send(f"{bot.settings['formats']['ticketStatus']} **Ticket update:** Changed ticket "
f"status to `Dev Replied`.", mention_author=False)
ticket = await bot.db.tickets.find_one({
"ids.message": str(message.id)
})
log_msg = await ctx.guild.get_channel(int(bot.settings["channels"]["ticketLog"])) \
.fetch_message(int(ticket["ids"]["log"]))
embed2 = log_msg.embeds[0]
embed2.colour = 0x0fb9fc
embed2.set_author(name=f"Approval Feedback - {ticket['_id']} [DEV REPLIED]",
icon_url=ctx.bot.settings["images"]["dev_replied"])
await log_msg.edit(embed=embed2)
await ctx.bot.db.tickets.update_one({"_id": ticket["_id"]}, {
"$set": {
"status": 3
}
})
@bot.event
async def on_message_edit(old_msg, new_msg):
if not old_msg.author.bot and new_msg.content != old_msg.content:
ctx = await bot.get_context(new_msg, cls=EditingContext)
await bot.invoke(ctx)
bot.run(settings["token"], bot=True, reconnect=True)