Skip to content

Commit

Permalink
Add Token Validation
Browse files Browse the repository at this point in the history
The program will now report an invalid token with a single log line and stop the application
  • Loading branch information
HEJOK254 committed Sep 22, 2024
1 parent 3c54763 commit 82aef8a
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions Bot.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using System;
using System.Diagnostics;
using Discord;
using Discord.WebSocket;
using Microsoft.Extensions.Hosting;
Expand All @@ -21,8 +19,36 @@ public async Task StartAsync(CancellationToken cancellationToken)
_client.Log += AutoLog.LogMessage;
_client.Ready += OnReadyAsync;

await _client.LoginAsync(TokenType.Bot, _discordConfig.Token);
await _client.StartAsync();
// Try-catch ValidateToken since LoginAsync doesn't throw exceptions, they just catch them
// So there's no way to know if the token is invalid without checking it first (or is there?)
// Also this is separate from the other try-catch to make sure it's the token that's invalid
try
{
TokenUtils.ValidateToken(TokenType.Bot, _discordConfig.Token);
}
catch (ArgumentException e)
{
Log.Fatal("{e}", e.Message);
Environment.ExitCode = 1;
_appLifetime.StopApplication();
return; // The app would normally continue for a short amount of time before stopping
}

// Most of the exceptions are caught by the library :( [maybe not idk i'm writing this at 2am]
// This means that the program will log stuff in an ugly way and NOT stop the program on fatal errors
try
{
// The token is already validated, so there's no need to validate it again
await _client.LoginAsync(TokenType.Bot, _discordConfig.Token, validateToken: false);
await _client.StartAsync();
}
catch (Exception e)
{
Log.Fatal("Failed to start the bot: {e}", e);
Environment.ExitCode = 1;
_appLifetime.StopApplication();
return;
}

// Custom activities use a different method
if (_discordConfig.StatusType == ActivityType.CustomStatus)
Expand Down

0 comments on commit 82aef8a

Please sign in to comment.