forked from yiliansource/brackeys-bot
/
BrackeysBot.cs
298 lines (249 loc) · 11.1 KB
/
BrackeysBot.cs
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
#pragma warning disable CS1998
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Discord;
using Discord.WebSocket;
using BrackeysBot.Commands;
using BrackeysBot.Modules;
namespace BrackeysBot
{
public sealed class BrackeysBot
{
public static IConfiguration Configuration { get; set; }
public const int Version = 3;
public bool OriginalProcess = true;
public DataModule Data { get; set; }
public CommandHandler Commands { get; set; }
private IServiceProvider _services;
public DiscordSocketClient _client;
private EventPointCommand.LeaderboardNavigator _leaderboardNavigator;
/// <summary>
/// Creates a new instance of the bot and initializes the configuration.
/// </summary>
public BrackeysBot()
{
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
}
/// <summary>
/// Starts the execution of the bot.
/// </summary>
public async Task Start()
{
Log.Initialize();
Log.Settings = new Log.LogSettings
{
IncludeTimestamp = true
};
Console.WriteLine($"\n [ ] BrackeysBot v{Version}\n");
Log.WriteLine("=== Intializing Startup ===");
_client = new DiscordSocketClient();
_client.Log += async logMessage => Log.WriteLine($"[DiscordClient] ({logMessage.Severity.ToString()}) {logMessage.Message}");
_client.Ready += OnReady;
Data = new DataModule();
Data.InitializeDataFiles();
Commands = new CommandHandler(Data, Configuration["prefix"]);
_leaderboardNavigator = new EventPointCommand.LeaderboardNavigator(Data.EventPoints, Data.Settings);
_services = new ServiceCollection()
// Add BrackeysBot
.AddSingleton(this)
// Add the command service
.AddSingleton(Commands.Service)
// Add the singletons for the databases
.AddSingleton(Data.EventPoints)
.AddSingleton(Data.Settings)
.AddSingleton(Data.Statistics)
.AddSingleton(Data.CustomCommands)
.AddSingleton(Data.Cooldowns)
.AddSingleton(Data.Rules)
.AddSingleton(Data.UnityDocs)
.AddSingleton(Data.Mutes)
.AddSingleton(Data.Bans)
.AddSingleton(_leaderboardNavigator)
// Finally, build the provider
.BuildServiceProvider();
UserHelper.Data = Data;
Commands.ServiceProvider = _services;
await Commands.InstallCommands(_client);
RegisterMuteOnJoin();
RegisterMassiveCodeblockHandle();
RegisterMentionMessage();
RegisterStaffPingLogging();
RegisterLeaderboardNavigationHandle();
_ = PeriodicCheckMute(new TimeSpan(TimeSpan.TicksPerMinute * 2), CancellationToken.None);
_ = PeriodicCheckBan(new TimeSpan(TimeSpan.TicksPerMinute * 3), CancellationToken.None);
await _client.LoginAsync(TokenType.Bot, Configuration["token"]);
await _client.SetGameAsync($"{ Configuration["prefix"] }help");
await _client.StartAsync();
}
/// <summary>
/// Asynchronously logs out the bot. Also terminates the application, if specified.
/// </summary>
public Task Shutdown(bool terminate)
{
if (terminate)
_client.Disconnected += Terminate;
_ = _client.StopAsync();
return Task.CompletedTask;
}
public Task Terminate(Exception e)
{
Environment.Exit(0);
return Task.CompletedTask;
}
private async Task OnReady()
{
// This means that the bot updated last time, so send a message, kill the useless process and delete the file
if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "updated.txt")))
{
OriginalProcess = false;
string[] contents = (await File.ReadAllTextAsync(Path.Combine(Directory.GetCurrentDirectory(), "updated.txt"))).Split('\n');
SocketGuild guild = _client.GetGuild(ulong.Parse(contents[0]));
SocketGuildChannel channel = guild.GetChannel(ulong.Parse(contents[1]));
await ((IMessageChannel)channel).SendMessageAsync("Successfully updated! :white_check_mark:");
File.Delete(Path.Combine(Directory.GetCurrentDirectory(), "updated.txt"));
}
// Bot didn't shut down gracefully, close leftover process
if (File.Exists(VersioningCommand.pidPath) && OriginalProcess)
{
VersioningCommand.CloseChild(null, null);
}
}
/// <summary>
/// Registers a method to handle massive codeblocks.
/// </summary>
private void RegisterMassiveCodeblockHandle()
{
_client.MessageReceived += HandleMassiveCodeblock;
}
private void RegisterMentionMessage()
{
_client.MessageReceived += async (s) =>
{
if (!(s is SocketUserMessage msg)) return;
string mention = _client.CurrentUser.Mention.Replace("!", "");
if (msg.Content.StartsWith(mention) && msg.Content.Length == mention.Length)
{
await msg.Channel.SendMessageAsync($"The command prefix for this server is `{ Configuration["prefix"] }`!");
return;
}
};
}
private void RegisterStaffPingLogging()
{
_client.MessageReceived += async (s) =>
{
if (!(s is SocketUserMessage msg) || s.Author.IsBot) { return; }
if (!Data.Settings.Has("staff-role") || !Data.Settings.Has("log-channel-id")) { return; }
SocketGuild guild = (msg.Channel as SocketGuildChannel).Guild;
SocketRole staffRole = guild.Roles.FirstOrDefault(r => r.Name == Data.Settings.Get("staff-role"));
if (staffRole != null && s.MentionedRoles.Contains(staffRole))
{
if (guild.Channels.FirstOrDefault(c => c.Id == ulong.Parse(Data.Settings.Get("log-channel-id"))) is IMessageChannel logChannel)
{
string author = msg.Author.Mention;
string messageLink = $@"https://discordapp.com/channels/{ guild.Id }/{ msg.Channel.Id }/{ msg.Id }";
string messageContent = msg.Content.Replace(staffRole.Mention, "@" + staffRole.Name);
await logChannel.SendMessageAsync($"{ author } mentioned staff in the following message! (<{ messageLink }>)\n```\n{ messageContent }\n```");
Log.WriteLine($"{author} mentioned @Staff in the following message: {messageLink}");
}
}
};
}
/// <summary>
/// Registers a method to mute people who were muted but decided to be clever
/// and wanted to rejoin to lose the muted role.
/// </summary>
private void RegisterMuteOnJoin()
{
_client.UserJoined += CheckMuteOnJoin;
}
async Task CheckMuteOnJoin(SocketGuildUser user)
{
if (DateTime.UtcNow.ToBinary() < user.GetMuteTime()) { await user.Mute(); }
else { await user.Unmute(); }
}
public async Task PeriodicCheckMute(TimeSpan interval, CancellationToken cancellationToken)
{
while (true)
{
Parallel.For(0, Data.Mutes.Mutes.Count,
async index =>
{
try
{
var current = Data.Mutes.Mutes.ElementAt(index);
if (DateTime.UtcNow.ToBinary() >= long.Parse(current.Value))
{
SocketGuild guild = _client.GetGuild(ulong.Parse(current.Key.Split(',')[1]));
SocketGuildUser user = guild.GetUser(ulong.Parse(current.Key.Split(',')[0]));
await user.Unmute();
Data.Mutes.Remove(current.Key);
}
}
catch { }
});
await Task.Delay(interval, cancellationToken).ConfigureAwait(false);
}
}
public async Task PeriodicCheckBan(TimeSpan interval, CancellationToken cancellationToken)
{
while (true)
{
Parallel.For(0, Data.Bans.Bans.Count,
async index =>
{
try
{
var current = Data.Bans.Bans.ElementAt(index);
if (DateTime.UtcNow.ToBinary() >= long.Parse(current.Value))
{
SocketGuild guild = _client.GetGuild(ulong.Parse(current.Key.Split(',')[1]));
IUser user = null;
foreach (IBan ban in await guild.GetBansAsync())
{
if (ban.User.Id == ulong.Parse(current.Key.Split(',')[0]))
{
user = ban.User;
}
}
await guild.RemoveBanAsync(user);
Data.Bans.Remove(current.Key);
}
}
catch { }
});
await Task.Delay(interval, cancellationToken);
}
}
/// <summary>
/// Registers the handle for a leaderboard navigation event.
/// </summary>
private void RegisterLeaderboardNavigationHandle()
{
_client.ReactionAdded += _leaderboardNavigator.HandleLeaderboardNavigation;
}
/// <summary>
/// Handles a massive codeblock.
/// </summary>
private async Task HandleMassiveCodeblock(SocketMessage s)
{
if (!(s is SocketUserMessage msg) || msg.Author.IsBot) return;
// Ignore specific channels
if (Data.Settings.Has("job-channel-ids"))
{
ulong[] ignoreChannelIds = Data.Settings.Get("job-channel-ids").Split(',').Select(id => ulong.Parse(id.Trim())).ToArray();
if (ignoreChannelIds.Any(id => id == s.Channel.Id)) return;
}
await PasteCommand.PasteIfMassiveCodeblock(s);
}
}
}