This repository has been archived by the owner on Sep 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
390 lines (337 loc) · 16 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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import discord, db_handler as dbh, asyncio, sys
from discord.ext.commands import Bot
from discord.ext import commands
from discord import utils
from asyncio import sleep, Lock
from cs_cog import Settings
from owner_cog import Owner
from util_cog import Utility
from lb_cog import Leaderboard
from pretty_help import PrettyHelp
import functions
import converters
from secrets import TOKEN, BETA_TOKEN, OWNER_ID, INVITE, SUPPORT_SERVER, SUPPORT_ID, SUGGESTION_CHANNEL
PREFIXES = functions.get_prefix
BETA_PREFIXES = functions.get_prefix
DOWNVOTE = '⬇️'
UPVOTE = '⬆️'
if len(sys.argv) == 0:
bot = Bot(command_prefix=PREFIXES, help_command=PrettyHelp(color=0xFCFF00))
else:
if sys.argv[1].lower() == 'beta':
bot = Bot(command_prefix=BETA_PREFIXES, help_command=PrettyHelp(color=0xFCFF00))
else:
print("Invalid Argument. Did you mean \"beta\"?")
exit()
running = True
async def loop_save():
while dbh.database is None:
await sleep(5)
while running:
await sleep(60)
dbh.database.save_database()
@bot.command(
name='about', brief='About Starboards',
description='Give quick description of what a starboard is and what it is for'
)
async def about_starbot(ctx):
msg = """
StarBot is a Discord starboard bot.\
Starboards are kind of like democratic pins.\
A user can "vote" to have a message displayed on a channel by reacting with an emoji, usually a star.\
A Starboard is a great way to archive funny messages.\
"""
embed=discord.Embed(
title='About StarBot and Starboards',
description=msg, color=0xFCFF00
)
await ctx.send(embed=embed)
@commands.cooldown(2, 120, commands.BucketType.user)
@bot.command(
name='suggest', aliases=['suggestion'],
description='Send a suggestion to the bot creator to report a bug or suggest a change/feature',
brief='Send suggestion to bot creator'
)
async def suggest(ctx, *, suggestion):
if ctx.message.author.bot:
return
support_guild = bot.get_guild(SUPPORT_ID)
suggestion_channel = utils.get(support_guild.channels, id=SUGGESTION_CHANNEL)
embed = discord.Embed(title='Suggestion', description=suggestion)
embed.set_author(name=ctx.message.author, icon_url=ctx.message.author.avatar_url)
sent = await suggestion_channel.send(embed=embed)
await sent.add_reaction(emoji=UPVOTE)
await sent.add_reaction(emoji=DOWNVOTE)
await ctx.send(f"{ctx.author.mention}, your suggestion has been sent!")
@bot.command(
name='ping', aliases=['latency'], description='Get bot latency',
brief='Get bot latency'
)
async def ping(ctx):
await ctx.send('Pong! {0} ms'.format(round(bot.latency*1000, 3)))
@bot.command(
name='links', aliases=['support', 'server', 'invite'], description='Get helpful links',
brief='Get helpful links'
)
async def links(ctx):
embed = discord.Embed(title='Helpful Links', colour=0xFCFF00)
embed.description = f"[**Add me to your server**]({INVITE})\
\n[**Join the support server**]({SUPPORT_SERVER})\
\n[**View documentation**](https://circuitsacul.github.io/StarBot/)\
\n[**View source code**](https://github.com/CircuitSacul/StarBot)"
await ctx.send(embed=embed)
@bot.command(name='info', aliases=['botstats'], description='Bot stats', brief='Bot stats')
async def stats_for_bot(ctx):
owner = bot.get_user(OWNER_ID)
if ctx.author.id == OWNER_ID:
owner_string = "You!"
else:
owner_string = owner
embed = discord.Embed(
title='Bot Stats', colour=0xFCFF00,
description = f"""
**Owner:** {owner_string}
**Guilds:** {len(bot.guilds)}
**Users:** {len(bot.users)}
**Ping:** {round(bot.latency*1000, 3)} ms
"""
)
await ctx.send(embed=embed)
@bot.event
async def on_command_error(ctx, error):
if ctx.author.bot:
return
elif type(error) is discord.ext.commands.errors.CommandNotFound:
return
elif type(error) is discord.ext.commands.errors.BadArgument:
pass
elif type(error) is discord.ext.commands.errors.MissingRequiredArgument:
pass
elif type(error) is discord.ext.commands.errors.NoPrivateMessage:
pass
elif type(error) is discord.ext.commands.errors.MissingPermissions:
pass
elif str(error).startswith('Command raised an exception: Forbidden'):
error = "I don't have the necessary permissions to do that :("
else:
embed = discord.Embed(title='Error!', description='An unexpected error ocurred. Please report this to the dev.', color=discord.Color.red())
embed.add_field(name='Error Message:', value=f"```{type(error)}:\n{error}```")
print(f"Error: {error}")
await ctx.send(embed=embed)
return
embed = discord.Embed(title='Oops!', description=f"```{error}```", color=discord.Color.orange())
await ctx.send(embed=embed)
@bot.event
async def on_ready():
if dbh.database is None:
dbh.set_database(bot)
bot.loop.create_task(loop_save())
print(f"Logged in as {bot.user.name} in {len(bot.guilds)} guilds!")
await bot.change_presence(
status=discord.Status.online
#activity=discord.Game('Mention me for help')
)
@bot.event
async def on_guild_join(guild):
while dbh.database is None:
await sleep(1)
dbh.database.add_guild(guild.id)
@bot.event
async def on_guild_remove(guild):
while dbh.database is None:
await sleep(1)
pass
@bot.event
async def on_raw_reaction_add(payload):
while dbh.database is None:
await sleep(1)
guild_id = payload.guild_id
channel_id = payload.channel_id
message_id = payload.message_id
user_id = payload.user_id
guild = bot.get_guild(guild_id)
if guild is None:
return
user = utils.get(guild.members, id=user_id)
channel = utils.get(guild.channels, id=channel_id)
try:
message = await channel.fetch_message(message_id)
except discord.errors.NotFound:
message = None
if user.bot:
return
if payload.emoji.id is not None:
emoji_str = payload.emoji.id
else:
emoji_str = payload.emoji.name
if guild_id not in dbh.database.locks:
dbh.database.locks[guild_id] = Lock()
async with dbh.database.locks[guild_id]:
if channel_id not in dbh.database.db['guilds'][guild_id]['channels']:
if (channel_id, message_id) not in dbh.database.db['guilds'][guild_id]['messages']:
dbh.database.db['guilds'][guild_id]['messages'][(channel_id, message_id)] = {'emojis': {}, 'links': {}}
if emoji_str not in dbh.database.db['guilds'][guild_id]['messages'][(channel_id, message_id)]['emojis']:
dbh.database.db['guilds'][guild_id]['messages'][(channel_id, message_id)]['emojis'][emoji_str] = {}
original = user_id in dbh.database.db['guilds'][guild_id]['messages'][(channel_id, message_id)]['emojis'][emoji_str]
dbh.database.db['guilds'][guild_id]['messages'][(channel_id, message_id)]['emojis'][emoji_str][user_id] = True
if original == False:
if message is not None:
if message.author.id != user_id:
if await functions.is_starboard_emoji(guild_id, emoji_str):
await functions.award_give_star(guild_id, user_id, 1, bot)
await functions.award_receive_star(guild_id, message.author.id, 1, bot)
await functions.update_message(guild_id, channel_id, message_id, bot)
else:
if message_id in dbh.database.db['guilds'][guild_id]['channels'][channel_id]['messages']:
original_channel_id, original_message_id = dbh.database.db['guilds'][guild_id]['channels'][channel_id]['messages'][message_id]
if (original_channel_id, original_message_id) not in dbh.database.db['guilds'][guild_id]['messages']:
dbh.database.db['guilds'][guild_id]['messages'][(original_channel_id, original_message_id)] = {'emojis': {}, 'links': {}}
if emoji_str not in dbh.database.db['guilds'][guild_id]['messages'][(original_channel_id, original_message_id)]['emojis']:
dbh.database.db['guilds'][guild_id]['messages'][(original_channel_id, original_message_id)]['emojis'][emoji_str] = {}
original = user_id in dbh.database.db['guilds'][guild_id]['messages'][(original_channel_id, original_message_id)]['emojis'][emoji_str]
dbh.database.db['guilds'][guild_id]['messages'][(original_channel_id, original_message_id)]['emojis'][emoji_str][user_id] = True
if original == False:
try:
original_channel = utils.get(guild.channels, id=original_channel_id)
original_message = await original_channel.fetch_message(original_message_id)
except discord.errors.NotFound:
pass
except AttributeError:
pass
else:
if original_message.author.id != user_id:
if await functions.is_starboard_emoji(guild_id, emoji_str):
await functions.award_give_star(guild_id, user_id, 1, bot)
await functions.award_receive_star(guild_id, original_message.author.id, 1, bot)
await functions.update_message(guild_id, original_channel_id, original_message_id, bot)
@bot.event
async def on_raw_reaction_remove(payload):
while dbh.database is None:
await sleep(1)
guild_id = payload.guild_id
guild = bot.get_guild(guild_id)
if guild is None:
return
channel_id = payload.channel_id
message_id = payload.message_id
user_id = payload.user_id
user = utils.get(guild.members, id=user_id)
channel = utils.get(guild.channels, id=channel_id)
try:
message = await channel.fetch_message(message_id)
except discord.errors.NotFound:
message = None
if user.bot:
return
if payload.emoji.id is not None:
emoji_str = payload.emoji.id
else:
emoji_str = payload.emoji.name
if guild_id not in dbh.database.locks:
dbh.database.locks[guild_id] = Lock()
async with dbh.database.locks[guild_id]:
if channel_id not in dbh.database.db['guilds'][guild_id]['channels']:
if (channel_id, message_id) not in dbh.database.db['guilds'][guild_id]['messages']:
dbh.database.db['guilds'][guild_id]['messages'][(channel_id, message_id)] = {'emojis': {}, 'links': {}}
if emoji_str not in dbh.database.db['guilds'][guild_id]['messages'][(channel_id, message_id)]['emojis']:
dbh.database.db['guilds'][guild_id]['messages'][(channel_id, message_id)]['emojis'][emoji_str] = {}
if user_id in dbh.database.db['guilds'][guild_id]['messages'][(channel_id, message_id)]['emojis'][emoji_str]:
del dbh.database.db['guilds'][guild_id]['messages'][(channel_id, message_id)]['emojis'][emoji_str][user_id]
original = True
else:
original = False
if original is True:
if message is not None:
if message.author.id != user_id:
if await functions.is_starboard_emoji(guild_id, emoji_str):
await functions.award_give_star(guild_id, user_id, -1, bot)
await functions.award_receive_star(guild_id, message.author.id, -1, bot)
await functions.update_message(guild_id, channel_id, message_id, bot)
else:
if message_id in dbh.database.db['guilds'][guild_id]['channels'][channel_id]['messages']:
original_channel_id, original_message_id = dbh.database.db['guilds'][guild_id]['channels'][channel_id]['messages'][message_id]
if emoji_str not in dbh.database.db['guilds'][guild_id]['messages'][(original_channel_id, original_message_id)]['emojis']:
dbh.database.db['guilds'][guild_id]['messages'][(original_channel_id, original_message_id)]['emojis'][emoji_str] = {}
if user_id in dbh.database.db['guilds'][guild_id]['messages'][(original_channel_id, original_message_id)]['emojis'][emoji_str]:
del dbh.database.db['guilds'][guild_id]['messages'][(original_channel_id, original_message_id)]['emojis'][emoji_str][user_id]
original = True
else:
original = False
if original == True:
try:
original_channel = utils.get(guild.channels, id=original_channel_id)
original_message = await original_channel.fetch_message(original_message_id)
except discord.errors.NotFound:
original_message = None
except AttributeError:
pass
else:
if original_message.author.id != user_id:
if await functions.is_starboard_emoji(guild_id, emoji_str):
await functions.award_give_star(guild_id, user_id, -1, bot)
await functions.award_receive_star(guild_id, original_message.author.id, -1, bot)
await functions.update_message(guild_id, original_channel_id, original_message_id, bot)
@bot.event
async def on_raw_message_delete(payload):
while dbh.database is None:
await sleep(1)
guild_id = payload.guild_id
channel_id = payload.channel_id
message_id = payload.message_id
if guild_id not in dbh.database.locks:
guild = bot.get_guild(guild_id)
if guild is None:
return
dbh.database.locks[guild_id] = Lock()
async with dbh.database.locks[guild_id]:
if channel_id not in dbh.database.db['guilds'][guild_id]['channels']:
if (channel_id, message_id) in dbh.database.db['guilds'][guild_id]['messages']:
await functions.update_message(guild_id, channel_id, message_id, bot)
@bot.event
async def on_message_edit(ctx, message):
while dbh.database is None:
await sleep(1)
if ctx.guild is None:
return
guild_id = ctx.guild.id
channel_id = ctx.channel.id
message_id = message.id
if guild_id not in dbh.database.locks:
dbh.database.locks[guild_id] = Lock()
async with dbh.database.locks[guild_id]:
if channel_id not in dbh.database.db['guilds'][guild_id]['channels']:
if (channel_id, message_id) in dbh.database.db['guilds'][guild_id]['messages']:
await functions.update_message(guild_id, channel_id, message_id, bot)
@bot.event
async def on_message(message):
while dbh.database is None:
await sleep(1)
is_valid = True
if message.guild is not None:
prefix = dbh.database.db['guilds'][message.guild.id]['prefix'].lower()
if message.channel.id in dbh.database.db['guilds'][message.guild.id]['media_channels']:
is_valid = await functions.handle_media_channel(message.guild, message.channel.id, message)
else:
prefix = 'sb '
if message.author.bot:
return
if message.content != '' and is_valid:
if bot.user.mention == message.content.split()[0].replace('!', '') and len(message.content.split()) == 1:
await message.channel.send(f"The prefix here is `{prefix}`\nCall `{prefix}help` for help with commands or `{prefix}links` for helpful links.")
else:
message.content = message.content[0].lower() + message.content[1:] if len(message.content) > 1 else message.content[0].lower()
await bot.process_commands(message)
try:
bot.add_cog(Settings(bot))
bot.add_cog(Owner(bot))
bot.add_cog(Utility(bot))
bot.add_cog(Leaderboard(bot))
if len(sys.argv) > 1:
if sys.argv[1].lower() == 'beta':
bot.run(BETA_TOKEN)
else:
bot.run(TOKEN)
finally:
running = False
dbh.database.save_database()
print("logging out")