-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
393 lines (336 loc) · 13.3 KB
/
Program.cs
File metadata and controls
393 lines (336 loc) · 13.3 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
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
391
392
393
using System.Reflection;
using Bloqbit;
using Bloqbit.Include;
using System;
using Discord;
using Discord.WebSocket;
using Discord.Webhook;
class Program
{
private DiscordSocketClient? _client;
private static List<Command> _commands = new List<Command>();
private static readonly string? token = Environment.GetEnvironmentVariable("MAIN_TOKEN");
private static readonly string? _webhookUrl = Environment.GetEnvironmentVariable("MAIN_LOG_WH");
public Program()
{
if (string.IsNullOrEmpty(token))
{
Log.Error("MAIN_TOKEN environment variable is not set! Cannot run Bloqbit without a bot token.");
Environment.Exit(1);
}
else
{
Log.Info("Token variable is set, starting...");
}
}
static async Task Main(string[] _)
{
Log.Print("Starting Bloqbit ...");
await new Program().RunBotAsync();
}
public async Task RunBotAsync()
{
_client = new DiscordSocketClient(
new DiscordSocketConfig
{
LogLevel = LogSeverity.Debug,
MessageCacheSize = 100,
GatewayIntents = GatewayIntents.AllUnprivileged | GatewayIntents.Guilds | GatewayIntents.GuildMessages | GatewayIntents.MessageContent,
HandlerTimeout = null
}
);
Log.Debug("Setting up event listeners...");
_client.Log += Debug;
_client.Ready += OnReadyAsync;
Log.Debug("Logging in...");
await _client.LoginAsync(TokenType.Bot, token);
await _client.StartAsync();
_client.SlashCommandExecuted += OnSlashCommand;
_client.MessageReceived += OnMessage;
_client.JoinedGuild += OnJoinedGuildAsync;
_client.LeftGuild += OnLeftGuildAsync;
await Task.Delay(-1); // Keep it running
}
static public List<Command> LoadAllCommands()
{
var commandTypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => t.IsClass && !t.IsAbstract && t.IsSubclassOf(typeof(Command)));
Log.Info($"Adding {commandTypes.Count()} commands to loading queue");
_commands = commandTypes
.Select(t => Activator.CreateInstance(t) as Command)
.Where(c => c is not null)
.Cast<Command>()
.ToList();
return _commands;
}
private async Task OnReadyAsync()
{
await _client!.SetGameAsync("Nothing to see here...", "https://bloqbit.cubicstudios.xyz/", ActivityType.Watching);
await RegisterCommandsAsync();
try
{
if (string.IsNullOrEmpty(_webhookUrl))
{
Log.Warn("MAIN_LOG_WH environment variable is not set, using default logging method");
}
else
{
var webhook = new DiscordWebhookClient(_webhookUrl);
if (webhook is not null)
{
Embed logEmbed = new EmbedBuilder()
.WithAuthor(
new EmbedAuthorBuilder()
.WithName("Service Status")
)
.WithDescription($"{Assets.Icons.Check} **{_client.CurrentUser.GlobalName ?? "Bloqbit "}** is now __online__")
.WithColor(Assets.Colors.Primary)
.WithFooter(
new EmbedFooterBuilder()
.WithText(_client.CurrentUser.GlobalName ?? "Bloqbit ")
.WithIconUrl(_client.CurrentUser.GetDisplayAvatarUrl(ImageFormat.Auto, 512))
)
.Build();
await webhook.SendMessageAsync(embeds: [logEmbed], avatarUrl: _client.CurrentUser.GetAvatarUrl(ImageFormat.Auto, 512));
}
else
{
Log.Error("Failed to create webhook client");
}
}
}
catch (Exception e)
{
Log.Error(e.Message);
}
Log.Success($"Bloqbit is online, running v{Bloqbit.Include.Version.Get()} on {_client?.Guilds.Count} servers!");
}
private Task Debug(LogMessage log)
{
switch (log.Severity)
{
case LogSeverity.Critical:
Log.Critical(log.Message);
break;
case LogSeverity.Error:
Log.Error(log.Message);
break;
case LogSeverity.Warning:
Log.Warn(log.Message);
break;
case LogSeverity.Info:
Log.Info(log.Message);
break;
case LogSeverity.Verbose:
Log.Print(log.Message);
break;
case LogSeverity.Debug:
Log.Debug(log.Message);
break;
default:
Log.Print(log.Message);
break;
}
return Task.CompletedTask;
}
private async Task RegisterCommandsAsync()
{
if (_client is not null)
{
var cmds = LoadAllCommands();
Log.Info($"Registering {cmds.Count} commands globally (bulk)");
var builtCommands = cmds
.Select(c => c.Builder?.Build())
.Where(b => b is not null)
.Cast<ApplicationCommandProperties>()
.ToList();
foreach (var bc in builtCommands)
Log.Debug($"Built command /{bc.Name}");
if (builtCommands.Count > 0)
{
try
{
await _client!.Rest.BulkOverwriteGlobalCommands([.. builtCommands]);
Log.Info($"Bulk registered {builtCommands.Count} commands globally");
}
catch (Exception e)
{
Log.Error(e.Message);
}
}
}
else
{
Log.Error("Bloqbit client not found to register slash commands");
}
}
private async Task OnSlashCommand(SocketSlashCommand command)
{
try
{
var matched = _commands.FirstOrDefault((c) => c.Builder.Build().Name.GetValueOrDefault("invalid") == command.Data.Name);
var guild = _client?.GetGuild(command.GuildId.GetValueOrDefault());
if (guild?.OwnerId == 358673524661157897 || command.ContextType != InteractionContextType.Guild)
{
if (matched is not null)
{
try
{
if (string.IsNullOrEmpty(_webhookUrl))
{
Log.Warn("MAIN_LOG_WH environment variable is not set, using default logging method");
}
else
{
var webhook = new DiscordWebhookClient(_webhookUrl);
if (webhook is not null)
{
string useDesc = $"Used **/{command.Data.Name}** in user context";
if (guild is not null) useDesc = $"Used **/{command.Data.Name}** in __{guild?.Name}__";
Embed logEmbed = new EmbedBuilder()
.WithAuthor(
new EmbedAuthorBuilder()
.WithName("Interaction")
)
.WithDescription(useDesc)
.WithColor(Assets.Colors.Tertiary)
.AddField(
new EmbedFieldBuilder()
.WithName("Used At")
.WithValue($"<t:{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}:F> • <t:{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}:R>")
.WithIsInline(false)
)
.WithFooter(
new EmbedFooterBuilder()
.WithText(command.User.Username)
.WithIconUrl(command.User.GetDisplayAvatarUrl(ImageFormat.Auto, 512))
)
.Build();
await webhook.SendMessageAsync(embeds: [logEmbed], avatarUrl: _client?.CurrentUser.GetAvatarUrl(ImageFormat.Auto, 512));
}
else
{
Log.Error("Failed to create webhook client");
}
}
}
catch (Exception e)
{
Log.Error(e.Message);
}
Log.Debug($"Running command /{command.Data.Name}");
await matched.ExecuteAsync(command, _client!);
}
else
{
await command.RespondAsync(text: $"{Assets.Icons.XMark} Unknown command.", flags: MessageFlags.Ephemeral);
Log.Error($"Command /{command.CommandName} not found");
}
}
else
{
await command.RespondAsync(text: $"{Assets.Icons.XMark} Bloqbit is currently in private testing and cannot be used in your server.", flags: MessageFlags.Ephemeral);
Log.Error("Unauthorized guild tried to use a command");
}
}
catch (Exception e)
{
string errRes = $"{Assets.Icons.XMark} An error occurred while executing this command.";
if (command.HasResponded)
{
await command.FollowupAsync(text: errRes, flags: MessageFlags.Ephemeral);
}
else
{
await command.RespondAsync(text: errRes, flags: MessageFlags.Ephemeral);
}
Log.Error(e.Message);
}
}
private async Task OnMessage(SocketMessage msg)
{
var msgs = await msg.Channel.GetMessagesAsync(100, CacheMode.AllowDownload).ToArrayAsync();
Log.Debug($"Cached {msgs.Length}/{msg.Channel.GetCachedMessages().Count} messages from guild channel");
}
private async Task OnJoinedGuildAsync(SocketGuild guild)
{
try
{
var webhook = new DiscordWebhookClient(_webhookUrl);
if (webhook is not null)
{
var date = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
Embed logEmbed = new EmbedBuilder()
.WithAuthor(
new EmbedAuthorBuilder()
.WithName("Servers")
)
.WithDescription($"{Assets.Icons.Plus} **{_client?.CurrentUser.GlobalName ?? "Bloqbit "}** was authorized to join the guild __{guild.Name}__")
.WithColor(Assets.Colors.Primary)
.AddField(
new EmbedFieldBuilder()
.WithName("Time of Join")
.WithValue($"<t:{date}:F> • <t:{date}:R>")
.WithIsInline(false)
)
.WithFooter(
new EmbedFooterBuilder()
.WithText(guild.Name)
.WithIconUrl(guild.IconUrl)
)
.Build();
await webhook.SendMessageAsync(embeds: [logEmbed], avatarUrl: _client?.CurrentUser.GetAvatarUrl(ImageFormat.Auto, 512));
}
else
{
Log.Error("Failed to create webhook client");
}
}
catch (Exception e)
{
Log.Error(e.Message);
}
Log.Info($"Authorized to join guild {guild.Name} ({guild.Id})");
}
private async Task OnLeftGuildAsync(SocketGuild guild)
{
try
{
var webhook = new DiscordWebhookClient(_webhookUrl);
if (webhook is not null)
{
var date = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
Embed logEmbed = new EmbedBuilder()
.WithAuthor(
new EmbedAuthorBuilder()
.WithName("Servers")
)
.WithDescription($"{Assets.Icons.Minus} **{_client?.CurrentUser.GlobalName ?? "Bloqbit "}** was forced to leave the guild __{guild.Name}__")
.WithColor(Assets.Colors.Secondary)
.AddField(
new EmbedFieldBuilder()
.WithName("Time of Leave")
.WithValue($"<t:{date}:F> • <t:{date}:R>")
.WithIsInline(false)
)
.WithFooter(
new EmbedFooterBuilder()
.WithText(guild.Name)
.WithIconUrl(guild.IconUrl)
)
.Build();
await webhook.SendMessageAsync(embeds: [logEmbed], avatarUrl: _client?.CurrentUser.GetAvatarUrl(ImageFormat.Auto, 512));
}
else
{
Log.Error("Failed to create webhook client");
}
}
catch (Exception e)
{
Log.Error(e.Message);
}
Log.Info($"Forced to leave guild {guild.Name} ({guild.Id})");
}
}