DiscordClient/DiscordDelete/Program.cs

119 lines
3.7 KiB
C#

using CommandLine;
using DiscordClient;
using DiscordClient.Data;
using DiscordDelete;
string? token = Environment.GetEnvironmentVariable("DISCORD_TOKEN");
if (token == null)
{
// Exit.
Console.WriteLine("Token is null. Make sure you set the DISCORD_TOKEN environmental variable.");
return;
}
DiscordContext db = new DiscordContext();
DiscordUserClient client = new DiscordUserClient(token);
int finalCode = await CommandLine
.Parser.Default.ParseArguments<DeleteOptions, ScanOptions>(args)
.MapResult(
async (DeleteOptions opt) =>
{
foreach (Message message in db.Messages)
{
// If required data is null, continue to next message.
if (message.MessageId is null || message.ChannelId is null)
continue;
HttpResponseMessage response = await client.DeleteMessage(
message.ChannelId,
message.MessageId
);
message.LastHttpCode = (int)response.StatusCode;
db.Update(message);
await db.SaveChangesAsync();
}
return 0;
},
async (ScanOptions opt) =>
{
// This should never happen author required.
if (opt.Author is null)
{
Console.WriteLine("Author ID is null.");
return 1;
}
int totalMessages = 1;
int offset = 0;
if (opt.GuildId is null)
{
Console.WriteLine("Scanning DM messages.");
while (true)
{
// Scanning direct messages.
ChannelMessagesResponse[]? messages = await client.GetChannelMessages(
opt.ChannelId,
offset,
opt.Author
);
if (messages is null)
return 2;
await db.AddRangeAsync(
messages.Select(message => new Message
{
ChannelId = message.ChannelId,
MessageId = message.Id,
Content = message.Content
})
);
await db.SaveChangesAsync();
offset += 50;
}
}
else
{
Console.WriteLine("Scanning guild messages.");
while (offset < totalMessages)
{
// Scanning guild messages.
GuildMessageSearchResponse? response = await client.SearchGuildMessages(
opt.GuildId,
offset,
opt.Author
);
if (response is null || response.Messages is null)
return 3;
totalMessages = response.TotalMessages;
await db.AddRangeAsync(
response.Messages.SelectMany(message =>
message.Select(messagePart => new Message
{
ChannelId = messagePart.ChannelId,
MessageId = messagePart.Id,
Content = messagePart.Content
})
)
);
await db.SaveChangesAsync();
offset += response.Messages.Count();
}
}
return 0;
},
errs => Task.FromResult(0)
);