-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathProgram.cs
More file actions
212 lines (180 loc) · 8.91 KB
/
Copy pathProgram.cs
File metadata and controls
212 lines (180 loc) · 8.91 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
namespace MechanicalMilkshake;
internal class Program
{
internal static async Task Main()
{
Setup.Constants.HttpClient.DefaultRequestHeaders.UserAgent.ParseAdd("MechanicalMilkshake (https://github.com/FloatingMilkshake/MechanicalMilkshake)");
#region read config.json
#if DEBUG
const string configFile = "config.dev.json";
#else
const string configFile = "config.json";
#endif
Setup.State.Process.Configuration = JsonConvert.DeserializeObject<Setup.Types.ConfigJson>(await File.ReadAllTextAsync(configFile));
if (string.IsNullOrWhiteSpace(Setup.State.Process.Configuration.HomeChannel) ||
string.IsNullOrWhiteSpace(Setup.State.Process.Configuration.HomeServer) ||
string.IsNullOrWhiteSpace(Setup.State.Process.Configuration.BotToken))
{
Console.WriteLine("You are missing required values in your config.json file! Please ensure 'botToken', 'homeServer' and 'homeChannel' are set.");
Environment.Exit(1);
}
if (string.IsNullOrEmpty(Setup.State.Process.Configuration.UptimeKumaHeartbeatUrl))
Setup.State.Process.LastUptimeKumaHeartbeatStatus = "disabled";
#endregion read config.json
#region set up logging
var logConfig = new LoggerConfiguration().WriteTo.Console(theme: AnsiConsoleTheme.Sixteen).MinimumLevel.Override("System.Net.Http", Serilog.Events.LogEventLevel.Error);
#if DEBUG
logConfig.MinimumLevel.Debug();
#else
logConfig.MinimumLevel.Debug();
#endif
if (Setup.State.Process.Configuration.GrafanaLokiUrl is not null)
{
var discordBot = "mechanicalmilkshake";
#if DEBUG
discordBot = "mechanicalmilkshake_dev";
#endif
logConfig.WriteTo.GrafanaLoki(Setup.State.Process.Configuration.GrafanaLokiUrl, [new LokiLabel { Key = "discord_bot", Value = discordBot }]);
}
Log.Logger = logConfig.CreateLogger();
#endregion set up logging
#region set up Discord client
var clientBuilder = DiscordClientBuilder.CreateDefault(Setup.State.Process.Configuration.BotToken,
DiscordIntents.AllUnprivileged.AddIntent(DiscordIntents.MessageContents));
clientBuilder.ConfigureLogging(config =>
{
config.AddSerilog();
});
clientBuilder.ConfigureExtraFeatures(config =>
{
config.LogUnknownEvents = false;
config.LogUnknownAuditlogs = false;
});
clientBuilder.ConfigureEventHandlers(builder =>
builder.HandleSessionCreated(ReadyEvents.HandleReadyEventAsync)
.HandleMessageCreated(MessageEvents.HandleMessageCreatedEventAsync)
.HandleMessageUpdated(MessageEvents.HandleMessageUpdatedEventAsync)
.HandleMessageDeleted(MessageEvents.HandleMessageDeletedEventAsync)
.HandleChannelDeleted(ChannelEvents.HandleChannelDeletedEventAsync)
.HandleComponentInteractionCreated(InteractionEvents.HandleComponentInteractionCreatedEventAsync)
.HandleModalSubmitted(InteractionEvents.HandleModalSubmittedEventAsync)
.HandleGuildCreated(GuildEvents.HandleGuildCreatedEventAsync)
.HandleGuildDeleted(GuildEvents.HandleGuildDeletedEventAsync)
.HandleGuildDownloadCompleted(GuildEvents.HandleGuildDownloadCompletedEventAsync)
);
clientBuilder.UseCommands((_, extension) =>
{
// Use custom TextCommandProcessor to set custom prefixes & disable CommandNotFoundExceptions
TextCommandProcessor textCommandProcessor = new(new()
{
PrefixResolver = new DefaultPrefixResolver(true, ["pls"]).ResolvePrefixAsync,
EnableCommandNotFoundException = false
});
extension.AddProcessor(textCommandProcessor);
// Use custom SlashCommandProcessor to use UnconditionallyOverwriteCommands
SlashCommandProcessor slashCommandProcessor = new(new()
{
UnconditionallyOverwriteCommands = true,
});
extension.AddProcessor(slashCommandProcessor);
// Register context checks
extension.AddCheck<RequireBotCommanderContextCheck>();
// Register error handling
extension.CommandErrored += Errors.CommandErrors.HandleCommandErroredEventAsync;
// Register logging
extension.CommandExecuted += Events.InteractionEvents.HandleCommandExecutedEventAsync;
// Register commands
extension.RegisterCommands();
}, new CommandsConfiguration
{
UseDefaultCommandErrorHandler = false,
});
Setup.State.Discord.Client = clientBuilder.Build();
#endregion set up Discord client
await CheckConfigurationAsync();
await Setup.State.Discord.Client.ConnectAsync();
// Give bot time to connect before starting tasks
await Task.Delay(TimeSpan.FromSeconds(3));
#region one-off tasks
// Populate list of application commands
await Task.Run(async () => CommandTasks.ExecuteAsync());
// Populate list of application emoji
await Task.Run(async () => EmojiTasks.ExecuteAsync());
#endregion one-off tasks
#region recurring tasks
// Uptime Kuma heartbeat
await Task.Run(async () => HeartbeatTasks.ExecuteAsync());
// Reminder check
await Task.Run(async () => ReminderTasks.ExecuteAsync());
// DBots stats update
await Task.Run(async () => DBotsTasks.ExecuteAsync());
#endregion recurring tasks
// Send startup message
await Setup.State.Discord.Channels.Home.SendMessageAsync(await Setup.Types.DebugInfo.CreateDebugInfoEmbedAsync(true));
// Wait indefinitely, let tasks continue running in async threads
await Task.Delay(Timeout.InfiniteTimeSpan);
}
private static async Task CheckConfigurationAsync()
{
try
{
Setup.State.Discord.HomeServer =
await Setup.State.Discord.Client.GetGuildAsync(Convert.ToUInt64(Setup.State.Process.Configuration.HomeServer));
Setup.State.Discord.Channels.Home =
await Setup.State.Discord.Client.GetChannelAsync(Convert.ToUInt64(Setup.State.Process.Configuration.HomeChannel));
}
catch (Exception)
{
Setup.State.Discord.Client.Logger.LogCritical("\"homeChannel\" or \"homeServer\" in config.json are misconfigured. Please make sure you have a valid ID for both of these values.");
Environment.Exit(1);
}
if (!string.IsNullOrWhiteSpace(Setup.State.Process.Configuration.FeedbackChannel))
{
try
{
Setup.State.Discord.Channels.Feedback =
await Setup.State.Discord.Client.GetChannelAsync(Convert.ToUInt64(Setup.State.Process.Configuration.FeedbackChannel));
}
catch (Exception)
{
Setup.State.Discord.Client.Logger.LogWarning("Feedback command disabled due to invalid or missing channel ID.");
}
}
if (!string.IsNullOrWhiteSpace(Setup.State.Process.Configuration.GuildLogChannel))
{
try
{
Setup.State.Discord.Channels.GuildLogs =
await Setup.State.Discord.Client.GetChannelAsync(Convert.ToUInt64(Setup.State.Process.Configuration.GuildLogChannel));
}
catch (Exception)
{
Setup.State.Discord.Client.Logger.LogWarning("Guild join/leave logs disabled due to invalid or missing channel ID.");
}
}
if (!string.IsNullOrWhiteSpace(Setup.State.Process.Configuration.SlashCommandLogChannel))
{
try
{
Setup.State.Discord.Channels.CommandLogs =
await Setup.State.Discord.Client.GetChannelAsync(Convert.ToUInt64(Setup.State.Process.Configuration.SlashCommandLogChannel));
}
catch (Exception)
{
Setup.State.Discord.Client.Logger.LogWarning("Interaction command logs disabled due to invalid or missing channel ID.");
}
}
if (string.IsNullOrWhiteSpace(Setup.State.Process.Configuration.WolframAlphaAppId))
{
Setup.State.Discord.Client.Logger.LogWarning("WolframAlpha commands disabled due to missing App ID.");
}
if (string.IsNullOrWhiteSpace(Setup.State.Process.Configuration.UptimeKumaHeartbeatUrl))
{
Setup.State.Discord.Client.Logger.LogWarning("Uptime Kuma heartbeats disabled due to missing push URL.");
}
if (string.IsNullOrWhiteSpace(Setup.State.Process.Configuration.DbotsApiToken))
{
Setup.State.Discord.Client.Logger.LogWarning("DBots stats posting disabled due to missing configuration.");
}
}
}