forked from RPCS3/discord-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSudo.Bot.cs
261 lines (243 loc) · 11.1 KB
/
Sudo.Bot.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
using System;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using CompatBot.Commands.Attributes;
using CompatBot.Database;
using CompatBot.Database.Providers;
using CompatBot.Utils;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.EntityFrameworkCore;
using NLog;
namespace CompatBot.Commands;
internal partial class Sudo
{
private static readonly SemaphoreSlim LockObj = new(1, 1);
private static readonly SemaphoreSlim ImportLockObj = new(1, 1);
private static readonly ProcessStartInfo RestartInfo = new("dotnet", $"run -c Release");
[Group("bot"), Aliases("kot")]
[Description("Commands to manage the bot instance")]
public sealed partial class Bot: BaseCommandModuleCustom
{
[Command("version")]
[Description("Returns currently checked out bot commit")]
public async Task Version(CommandContext ctx)
{
using var git = new Process
{
StartInfo = new("git", "log -1 --oneline")
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
StandardOutputEncoding = Encoding.UTF8,
},
};
git.Start();
var stdout = await git.StandardOutput.ReadToEndAsync().ConfigureAwait(false);
await git.WaitForExitAsync().ConfigureAwait(false);
if (!string.IsNullOrEmpty(stdout))
await ctx.Channel.SendMessageAsync("```" + stdout + "```").ConfigureAwait(false);
}
[Command("update"), Aliases("upgrade", "pull", "pet")]
[Description("Updates the bot, and then restarts it")]
public Task Update(CommandContext ctx) => UpdateCheckAsync(ctx.Channel, Config.Cts.Token);
[Command("restart"), Aliases("reboot")]
[Description("Restarts the bot")]
public async Task Restart(CommandContext ctx)
{
if (await LockObj.WaitAsync(0).ConfigureAwait(false))
{
DiscordMessage? msg = null;
try
{
msg = await ctx.Channel.SendMessageAsync("Saving state...").ConfigureAwait(false);
await StatsStorage.SaveAsync(true).ConfigureAwait(false);
msg = await msg.UpdateOrCreateMessageAsync(ctx.Channel, "Restarting...").ConfigureAwait(false);
Restart(ctx.Channel.Id, "Restarted due to command request");
}
catch (Exception e)
{
await msg.UpdateOrCreateMessageAsync(ctx.Channel, "Restarting failed: " + e.Message).ConfigureAwait(false);
}
finally
{
LockObj.Release();
}
}
else
await ctx.Channel.SendMessageAsync("Update is in progress").ConfigureAwait(false);
}
[Command("stop"), Aliases("exit", "shutdown", "terminate")]
[Description("Stops the bot. Useful if you can't find where you left one running")]
public async Task Stop(CommandContext ctx)
{
await ctx.Channel.SendMessageAsync(ctx.Channel.IsPrivate
? $"Shutting down bot instance on {Environment.MachineName}..."
: "Shutting down the bot..."
).ConfigureAwait(false);
Config.Log.Info($"Shutting down by request from {ctx.User.Username}#{ctx.User.Discriminator}");
Config.InMemorySettings["shutdown"] = "true";
await Config.Cts.CancelAsync().ConfigureAwait(false);
}
[Command("status")]
[Description("Sets bot status with specified activity and message")]
public async Task Status(CommandContext ctx, [Description("One of: None, Playing, Watching or ListeningTo")] string activity, [RemainingText] string message)
{
try
{
await using var db = new BotDb();
var status = await db.BotState.FirstOrDefaultAsync(s => s.Key == "bot-status-activity").ConfigureAwait(false);
var txt = await db.BotState.FirstOrDefaultAsync(s => s.Key == "bot-status-text").ConfigureAwait(false);
if (Enum.TryParse(activity, true, out ActivityType activityType)
&& !string.IsNullOrEmpty(message))
{
if (status == null)
await db.BotState.AddAsync(new() {Key = "bot-status-activity", Value = activity}).ConfigureAwait(false);
else
status.Value = activity;
if (txt == null)
await db.BotState.AddAsync(new() {Key = "bot-status-text", Value = message}).ConfigureAwait(false);
else
txt.Value = message;
await ctx.Client.UpdateStatusAsync(new(message, activityType), UserStatus.Online).ConfigureAwait(false);
}
else
{
if (status != null)
db.BotState.Remove(status);
await ctx.Client.UpdateStatusAsync(new()).ConfigureAwait(false);
}
await db.SaveChangesAsync(Config.Cts.Token).ConfigureAwait(false);
}
catch (Exception e)
{
Config.Log.Error(e);
}
}
[Command("import_metacritic"), Aliases("importmc", "imc"), TriggersTyping]
[Description("Imports Metacritic database dump and links it to existing items")]
public async Task ImportMc(CommandContext ctx)
{
if (await ImportLockObj.WaitAsync(0).ConfigureAwait(false))
try
{
await CompatList.ImportMetacriticScoresAsync().ConfigureAwait(false);
await using var db = new ThumbnailDb();
var linkedItems = await db.Thumbnail.CountAsync(i => i.MetacriticId != null).ConfigureAwait(false);
await ctx.Channel.SendMessageAsync($"Importing Metacritic info was successful, linked {linkedItems} items").ConfigureAwait(false);
}
finally
{
ImportLockObj.Release();
}
else
await ctx.Channel.SendMessageAsync("Another import operation is already in progress").ConfigureAwait(false);
}
internal static async Task UpdateCheckScheduledAsync(CancellationToken cancellationToken)
{
do
{
await Task.Delay(TimeSpan.FromHours(6), cancellationToken).ConfigureAwait(false);
await UpdateCheckAsync(null, cancellationToken).ConfigureAwait(false);
} while (!cancellationToken.IsCancellationRequested);
}
private static async Task UpdateCheckAsync(DiscordChannel? channel, CancellationToken cancellationToken)
{
// ReSharper disable once MethodHasAsyncOverloadWithCancellation
#pragma warning disable VSTHRD103
if (LockObj.Wait(0))
#pragma warning restore VSTHRD103
{
DiscordMessage? msg = null;
try
{
Config.Log.Info("Checking for available bot updates...");
if (channel is not null)
msg = await msg.UpdateOrCreateMessageAsync(channel, "Checking for bot updates...").ConfigureAwait(false);
var (updated, stdout) = await GitPullAsync(cancellationToken).ConfigureAwait(false);
if (!string.IsNullOrEmpty(stdout))
{
Config.Log.Debug($"git pull output:\n{stdout}");
if (channel is not null)
await channel.SendAutosplitMessageAsync("```" + stdout + "```").ConfigureAwait(false);
}
if (!updated)
return;
if (channel is not null)
msg = await channel.SendMessageAsync("Saving state...").ConfigureAwait(false);
await StatsStorage.SaveAsync(true).ConfigureAwait(false);
if (channel is not null)
msg = await msg.UpdateOrCreateMessageAsync(channel, "Restarting...").ConfigureAwait(false);
Restart(channel?.Id ?? Config.BotLogId, "Restarted after successful bot update");
}
catch (Exception e)
{
Config.Log.Warn($"Updating failed: {e.Message}");
if (channel is not null)
await msg.UpdateOrCreateMessageAsync(channel, "Updating failed: " + e.Message).ConfigureAwait(false);
}
finally
{
LockObj.Release();
}
}
else
{
Config.Log.Info("Update check is already in progress");
if (channel is not null)
await channel.SendMessageAsync("Update is in progress").ConfigureAwait(false);
}
}
internal static async Task<(bool updated, string stdout)> GitPullAsync(CancellationToken cancellationToken)
{
var stdout = await GitRunner.Exec("pull", cancellationToken);
if (string.IsNullOrEmpty(stdout))
return (false, stdout);
if (stdout.Contains("Already up to date", StringComparison.InvariantCultureIgnoreCase))
return (false, stdout);
return (true, stdout);
}
internal static void Restart(ulong channelId, string? restartMsg)
{
Config.Log.Info($"Saving channelId {channelId} into settings...");
using var db = new BotDb();
var ch = db.BotState.FirstOrDefault(k => k.Key == "bot-restart-channel");
if (ch is null)
{
ch = new() {Key = "bot-restart-channel", Value = channelId.ToString()};
db.BotState.Add(ch);
}
else
ch.Value = channelId.ToString();
var msg = db.BotState.FirstOrDefault(k => k.Key == "bot-restart-msg");
if (msg is null)
{
msg = new() {Key = "bot-restart-msg", Value = restartMsg};
db.BotState.Add(msg);
}
else
msg.Value = restartMsg;
db.SaveChanges();
Config.TelemetryClient?.TrackEvent("Restart");
RestartNoSaving();
}
internal static void RestartNoSaving()
{
if (SandboxDetector.Detect() != SandboxType.Docker)
{
Config.Log.Info("Restarting...");
LogManager.LogFactory.Flush();
using var self = new Process {StartInfo = RestartInfo};
self.Start();
Config.InMemorySettings["shutdown"] = "true";
Config.Cts.Cancel();
}
Environment.Exit(-1);
}
}
}