Skip to content

Commit

Permalink
24.08.17
Browse files Browse the repository at this point in the history
- Update latest core to support latest S/V (Tomoya's Sylveon & WCS 2024 Steenee)
- Made Clone command non-blocking
- Added reconnect logic for discord disconnects (Should fix issue Daiivr/DaiBot.NET#1 (comment))
- Wrap AnnounceBotStatus in try/catch blocks for insufficient priveledges
- Bump Version
  • Loading branch information
bdawg1989 committed Aug 17, 2024
1 parent cd62485 commit d81a332
Show file tree
Hide file tree
Showing 6 changed files with 101 additions and 30 deletions.
38 changes: 24 additions & 14 deletions SysBot.Pokemon.Discord/Commands/Bots/CloneModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,25 @@ public async Task CloneAsync(int code)
await ReplyAsync("You already have an existing trade in the queue. Please wait until it is processed.").ConfigureAwait(false);
return;
}

var sig = Context.User.GetFavor();
var lgcode = Info.GetRandomLGTradeCode();

await QueueHelper<T>.AddToQueueAsync(Context, code, Context.User.Username, sig, new T(), PokeRoutineType.Clone, PokeTradeType.Clone, Context.User, false, 1, 1, false, false, lgcode);
// Add to queue asynchronously
_ = QueueHelper<T>.AddToQueueAsync(Context, code, Context.User.Username, sig, new T(), PokeRoutineType.Clone, PokeTradeType.Clone, Context.User, false, 1, 1, false, false, lgcode);

// Immediately send a confirmation message without waiting
var confirmationMessage = await ReplyAsync("Processing your clone request...").ConfigureAwait(false);

await Task.Delay(2000).ConfigureAwait(false);

if (Context.Message is IUserMessage userMessage)
await userMessage.DeleteAsync().ConfigureAwait(false);
// Use a fire-and-forget approach for the delay and deletion
_ = Task.Delay(2000).ContinueWith(async _ =>
{
if (Context.Message is IUserMessage userMessage)
await userMessage.DeleteAsync().ConfigureAwait(false);

if (confirmationMessage != null)
await confirmationMessage.DeleteAsync().ConfigureAwait(false);
if (confirmationMessage != null)
await confirmationMessage.DeleteAsync().ConfigureAwait(false);
}).ConfigureAwait(false);
}

[Command("clone")]
Expand All @@ -52,21 +57,26 @@ public async Task CloneAsync([Summary("Trade Code")][Remainder] string code)
await ReplyAsync("You already have an existing trade in the queue. Please wait until it is processed.").ConfigureAwait(false);
return;
}

int tradeCode = Util.ToInt32(code);
var sig = Context.User.GetFavor();
var lgcode = Info.GetRandomLGTradeCode();

await QueueHelper<T>.AddToQueueAsync(Context, tradeCode == 0 ? Info.GetRandomTradeCode(userID) : tradeCode, Context.User.Username, sig, new T(), PokeRoutineType.Clone, PokeTradeType.Clone, Context.User, false, 1, 1, false, false, lgcode);
// Add to queue asynchronously
_ = QueueHelper<T>.AddToQueueAsync(Context, tradeCode == 0 ? Info.GetRandomTradeCode(userID) : tradeCode, Context.User.Username, sig, new T(), PokeRoutineType.Clone, PokeTradeType.Clone, Context.User, false, 1, 1, false, false, lgcode);

// Immediately send a confirmation message without waiting
var confirmationMessage = await ReplyAsync("Processing your clone request...").ConfigureAwait(false);

await Task.Delay(2000).ConfigureAwait(false);

if (Context.Message is IUserMessage userMessage)
await userMessage.DeleteAsync().ConfigureAwait(false);
// Use a fire-and-forget approach for the delay and deletion
_ = Task.Delay(2000).ContinueWith(async _ =>
{
if (Context.Message is IUserMessage userMessage)
await userMessage.DeleteAsync().ConfigureAwait(false);

if (confirmationMessage != null)
await confirmationMessage.DeleteAsync().ConfigureAwait(false);
if (confirmationMessage != null)
await confirmationMessage.DeleteAsync().ConfigureAwait(false);
}).ConfigureAwait(false);
}

[Command("clone")]
Expand Down
77 changes: 75 additions & 2 deletions SysBot.Pokemon.Discord/SysCord.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,13 +100,72 @@ public SysCord(PokeBotRunner<T> runner)
_services = ConfigureServices();

_client.PresenceUpdated += Client_PresenceUpdated;

_client.Disconnected += async (exception) =>
{
LogUtil.LogText($"Discord connection lost. Reason: {exception?.Message ?? "Unknown"}");
await ReconnectAsync();
};
}

public static PokeBotRunner<T> Runner { get; private set; } = default!;

// Track loading of Echo/Logging channels, so they aren't loaded multiple times.
private bool MessageChannelsLoaded { get; set; }

private async Task ReconnectAsync()
{
const int maxRetries = 5;
const int delayBetweenRetries = 5000; // 5 seconds
const int initialDelay = 10000; // 10 seconds

// Initial delay to allow Discord's automatic reconnection
await Task.Delay(initialDelay).ConfigureAwait(false);

for (int i = 0; i < maxRetries; i++)
{
try
{
if (_client.ConnectionState == ConnectionState.Connected)
{
LogUtil.LogText("Client reconnected automatically.");
return; // Already reconnected
}

// Check if the client is in the process of reconnecting
if (_client.ConnectionState == ConnectionState.Connecting)
{
LogUtil.LogText("Client is already attempting to reconnect.");
await Task.Delay(delayBetweenRetries).ConfigureAwait(false);
continue;
}

await _client.LoginAsync(TokenType.Bot, Hub.Config.Discord.Token).ConfigureAwait(false);
await _client.StartAsync().ConfigureAwait(false);
LogUtil.LogText("Reconnected successfully.");
return;
}
catch (Exception ex)
{
LogUtil.LogText($"Reconnection attempt {i + 1} failed: {ex.Message}");
if (i < maxRetries - 1)
await Task.Delay(delayBetweenRetries).ConfigureAwait(false);
}
}

// If all attempts to reconnect fail, stop and restart the bot
LogUtil.LogText("Failed to reconnect after maximum attempts. Restarting the bot...");

// Stop the bot
await _client.StopAsync().ConfigureAwait(false);

// Restart the bot
await _client.LoginAsync(TokenType.Bot, Hub.Config.Discord.Token).ConfigureAwait(false);
await _client.StartAsync().ConfigureAwait(false);

LogUtil.LogText("Bot restarted successfully.");
}

public async Task AnnounceBotStatus(string status, EmbedColorOption color)
{
// Check the BotEmbedStatus setting before proceeding
Expand Down Expand Up @@ -185,12 +244,26 @@ public async Task AnnounceBotStatus(string status, EmbedColorOption color)

public async Task HandleBotStart()
{
await AnnounceBotStatus("Online", EmbedColorOption.Green);
try
{
await AnnounceBotStatus("Online", EmbedColorOption.Green);
}
catch (Exception ex)
{
LogUtil.LogText($"HandleBotStart: Exception when announcing bot start: {ex.Message}");
}
}

public async Task HandleBotStop()
{
await AnnounceBotStatus("Offline", EmbedColorOption.Red);
try
{
await AnnounceBotStatus("Offline", EmbedColorOption.Red);
}
catch (Exception ex)
{
LogUtil.LogText($"HandleBotStop: Exception when announcing bot stop: {ex.Message}");
}
}

public async Task InitCommands()
Expand Down
14 changes: 1 addition & 13 deletions SysBot.Pokemon/BDSP/BotTrade/PokeTradeBotBS.cs
Original file line number Diff line number Diff line change
Expand Up @@ -765,19 +765,7 @@ private async Task<PokeTradeResult> PerformLinkCodeTrade(SAV8BS sav, PokeTradeDe
// Wait for user input... Needs to be different from the previously offered Pokémon.
var tradeOffered = await ReadUntilChanged(LinkTradePokemonOffset, lastOffered, 25_000, 1_000, false, true, token).ConfigureAwait(false);
if (!tradeOffered)
{
// Check if b1s1 slot didn't change at all
var currentB1S1 = await ReadPokemon(BoxStartOffset, BoxFormatSlotSize, token).ConfigureAwait(false);
if (SearchUtil.HashByDetails(currentB1S1) == SearchUtil.HashByDetails(toSend) && currentB1S1.Checksum == toSend.Checksum)
{
Log("No Pokémon change detected in b1s1. Trainer too slow.");

// Exit back to overworld
await EnsureOutsideOfUnionRoom(token).ConfigureAwait(false);

return PokeTradeResult.TrainerTooSlow;
}
}
return PokeTradeResult.TrainerTooSlow;

// If we detected a change, they offered something.
var offered = await ReadPokemon(LinkTradePokemonOffset, BoxFormatSlotSize, token).ConfigureAwait(false);
Expand Down
2 changes: 1 addition & 1 deletion SysBot.Pokemon/Helpers/TradeBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ public static class TradeBot

public const string ConfigPath = "config.json";

public const string Version = "v2.9.5";
public const string Version = "v2.9.6";
}
}
Binary file modified SysBot.Pokemon/deps/PKHeX.Core.AutoMod.dll
Binary file not shown.
Binary file modified SysBot.Pokemon/deps/PKHeX.Core.dll
Binary file not shown.

0 comments on commit d81a332

Please sign in to comment.