Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/Sonar.yml
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ jobs:

- name: Build and analyze
run: |
./.sonar/scanner/dotnet-sonarscanner begin /k:"${{ secrets.SONAR_PROJECT_KEY }}" /d:sonar.token="${{ secrets.SONAR_TOKEN }}" /d:sonar.host.url="${{ secrets.SONAR_HOST_URL }}" /d:sonar.coverage.exclusions="**/tests/**" /d:sonar.cs.opencover.reportsPaths="**/coverage.opencover.xml"
./.sonar/scanner/dotnet-sonarscanner begin /k:"${{ secrets.SONAR_PROJECT_KEY }}" /d:sonar.token="${{ secrets.SONAR_TOKEN }}" /d:sonar.host.url="${{ secrets.SONAR_HOST_URL }}" /d:sonar.coverage.exclusions="**/tests/**" /d:sonar.cs.opencover.reportsPaths="**/coverage.opencover.xml" /d:sonar.cpd.exclusions="**/Migrations/*.cs" /d:sonar.exclusions="**/Migrations/*.cs,**/obj/**,**/bin/**"
dotnet build --no-restore --configuration Release
dotnet test --no-build --configuration Release --collect:"XPlat Code Coverage;Format=opencover" --blame-hang-timeout 60s
./.sonar/scanner/dotnet-sonarscanner end /d:sonar.token="${{ secrets.SONAR_TOKEN }}"
Expand Down
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.9" />
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="10.0.9" />
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.9" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.9" />
<PackageVersion Include="Persistord.Core" Version="1.0.0-beta.1" />
<PackageVersion Include="RustPlusApi" Version="2.0.0-beta.3" />
<PackageVersion Include="RustPlusApi.Fcm" Version="2.0.0-beta.3" />
Expand Down
2 changes: 2 additions & 0 deletions RustPlusBot.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
<Project Path="src/RustPlusBot.Features.Players/RustPlusBot.Features.Players.csproj" />
<Project Path="src/RustPlusBot.Features.Switches/RustPlusBot.Features.Switches.csproj" />
<Project Path="src/RustPlusBot.Features.Workspace/RustPlusBot.Features.Workspace.csproj" />
<Project Path="src/RustPlusBot.Localization/RustPlusBot.Localization.csproj" />
<Project Path="src/RustPlusBot.Persistence/RustPlusBot.Persistence.csproj" />
</Folder>
<Folder Name="/tests/">
Expand All @@ -28,6 +29,7 @@
<Project Path="tests/RustPlusBot.Features.Alarms.Tests/RustPlusBot.Features.Alarms.Tests.csproj" />
<Project Path="tests/RustPlusBot.Features.Chat.Tests/RustPlusBot.Features.Chat.Tests.csproj" />
<Project Path="tests/RustPlusBot.Features.Events.Tests/RustPlusBot.Features.Events.Tests.csproj" />
<Project Path="tests/RustPlusBot.Localization.Tests/RustPlusBot.Localization.Tests.csproj" />
<Project Path="tests/RustPlusBot.Persistence.Tests/RustPlusBot.Persistence.Tests.csproj" />
</Folder>
</Solution>
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace RustPlusBot.Features.Connections.Listening;
namespace RustPlusBot.Abstractions.Connections;

/// <summary>Reads live data from a connected server's socket (implemented by the connection supervisor).</summary>
public interface IRustServerQuery
Expand Down
2 changes: 1 addition & 1 deletion src/RustPlusBot.Abstractions/Connections/MapDimensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace RustPlusBot.Features.Connections.Listening;
namespace RustPlusBot.Abstractions.Connections;

/// <summary>The static-per-wipe map size needed to convert world coordinates to a grid reference.</summary>
/// <param name="Width">Map image width.</param>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace RustPlusBot.Features.Connections.Listening;
namespace RustPlusBot.Abstractions.Connections;

/// <summary>One map marker observed in a <c>GetMapMarkers</c> poll.</summary>
/// <param name="Id">The stable marker id (used to diff polls).</param>
Expand Down
2 changes: 1 addition & 1 deletion src/RustPlusBot.Abstractions/Connections/MarkerKind.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace RustPlusBot.Features.Connections.Listening;
namespace RustPlusBot.Abstractions.Connections;

/// <summary>The subset of Rust map-marker types this bot reasons about; everything else is <see cref="Other"/>.</summary>
public enum MarkerKind
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace RustPlusBot.Features.Connections.Listening;
namespace RustPlusBot.Abstractions.Connections;

/// <summary>One named monument observed in a <c>GetMap</c> response.</summary>
/// <param name="Token">The monument token (e.g. <c>oilrig_1</c>, <c>large_oil_rig</c>).</param>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace RustPlusBot.Features.Connections.Listening;
namespace RustPlusBot.Abstractions.Connections;

/// <summary>A point-in-time view of a server's population and wipe, decoupled from RustPlusApi types.</summary>
/// <param name="Players">Current player count.</param>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace RustPlusBot.Features.Connections.Listening;
namespace RustPlusBot.Abstractions.Connections;

/// <summary>A point-in-time view of in-game time, decoupled from RustPlusApi types.</summary>
/// <param name="TimeOfDay">Current in-game time of day (RustPlusApi <c>TimeInfo.Time</c>).</param>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace RustPlusBot.Features.Connections.Listening;
namespace RustPlusBot.Abstractions.Connections;

/// <summary>A point-in-time view of a team, decoupled from RustPlusApi types.</summary>
/// <param name="LeaderSteamId">Steam64 id of the current team leader.</param>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using RustPlusBot.Features.Connections.Listening;
using RustPlusBot.Abstractions.Connections;

namespace RustPlusBot.Abstractions.Events;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using RustPlusBot.Features.Connections.Listening;
using RustPlusBot.Abstractions.Connections;

namespace RustPlusBot.Abstractions.Events;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using RustPlusBot.Features.Connections.Listening;
using RustPlusBot.Abstractions.Connections;

namespace RustPlusBot.Abstractions.Events;

Expand Down
132 changes: 132 additions & 0 deletions src/RustPlusBot.Discord/Posting/DiscordChannelMessenger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
using Discord;
using Discord.Net;
using Discord.WebSocket;
using Microsoft.Extensions.Logging;

namespace RustPlusBot.Discord.Posting;

/// <summary>Shared Discord channel post/edit boilerplate: fetch, options, self-heal, broad-catch.</summary>
public static class DiscordChannelMessenger
{
/// <summary>
/// Edits the message by id (self-healing on 404 by reposting) or posts a new one.
/// Returns the message id, or null on failure.
/// </summary>
/// <param name="client">The Discord socket client.</param>
/// <param name="channelId">The target channel id.</param>
/// <param name="messageId">The existing message id to edit, or null to post a new one.</param>
/// <param name="embed">The embed to post or update.</param>
/// <param name="components">The message components to post or update.</param>
/// <param name="logger">The caller's logger.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public static async Task<ulong?> EnsureAsync(
DiscordSocketClient client,
ulong channelId,
ulong? messageId,
Embed embed,
MessageComponent components,
ILogger logger,
CancellationToken cancellationToken)
{
try
{
var options = new RequestOptions
{
CancelToken = cancellationToken
};
if (await client.GetChannelAsync(channelId, options).ConfigureAwait(false)
is not ITextChannel channel)
{
return null;
}

if (messageId is { } id)
{
// Inner try: some Discord.Net versions THROW (HttpException 404/Unknown Message)
// rather than return null for a deleted message. Catch it and fall through to repost
// so the self-heal path always runs.
try
{
var existing = await channel.GetMessageAsync(id, options: options).ConfigureAwait(false);
if (existing is IUserMessage userMessage)
{
await userMessage.ModifyAsync(m =>
{
m.Embed = embed;
m.Components = components;
}, options).ConfigureAwait(false);
return userMessage.Id;
}

// Message was deleted (returned null / not a user message); fall through to repost.
}
catch (HttpException ex) when (ex.HttpCode == System.Net.HttpStatusCode.NotFound)
{
// Deleted/unknown message; fall through to repost and return the new id.
#pragma warning disable CA1848, CA1873 // Use LoggerMessage delegates / avoid expensive log-arg evaluation — plain logger.Log is fine for a shared helper (no source-gen partial context); ulong boxing is negligible vs. the caught exception.
logger.LogDebug(ex, "Embed {MessageId} in channel {ChannelId} was deleted; reposting.", id,
channelId);
#pragma warning restore CA1848, CA1873
}
}

var posted = await channel
.SendMessageAsync(embed: embed, options: options, components: components)
.ConfigureAwait(false);
return posted.Id;
}
catch (OperationCanceledException)
{
throw; // Shutdown — let the loop unwind.
}
#pragma warning disable CA1031 // Broad catch: a Discord hiccup must not crash the relay; report failure as null.
catch (Exception ex)
#pragma warning restore CA1031
{
#pragma warning disable CA1848, CA1873 // Use LoggerMessage delegates / avoid expensive log-arg evaluation — plain logger.Log is fine for a shared helper (no source-gen partial context); ulong boxing is negligible vs. the caught exception.
logger.LogWarning(ex, "Posting/editing an embed in channel {ChannelId} failed.", channelId);
#pragma warning restore CA1848, CA1873
return null;
}
}

/// <summary>Posts an embed fire-and-forget; Discord hiccups are logged and swallowed.</summary>
/// <param name="client">The Discord socket client.</param>
/// <param name="channelId">The target channel id.</param>
/// <param name="embed">The embed to post.</param>
/// <param name="logger">The caller's logger.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public static async Task PostAsync(
DiscordSocketClient client,
ulong channelId,
Embed embed,
ILogger logger,
CancellationToken cancellationToken)
{
try
{
var options = new RequestOptions
{
CancelToken = cancellationToken
};
if (await client.GetChannelAsync(channelId, options).ConfigureAwait(false) is not ITextChannel channel)
{
return;
}

await channel.SendMessageAsync(embed: embed, options: options).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
throw; // Cancellation (shutdown) is not a post failure; let the relay loop unwind cleanly.
}
#pragma warning disable CA1031 // Broad catch: a Discord hiccup must not crash the relay.
catch (Exception ex)
#pragma warning restore CA1031
{
#pragma warning disable CA1848, CA1873 // Use LoggerMessage delegates / avoid expensive log-arg evaluation — plain logger.Log is fine for a shared helper (no source-gen partial context); ulong boxing is negligible vs. the caught exception.
logger.LogWarning(ex, "Posting an embed to channel {ChannelId} failed.", channelId);
#pragma warning restore CA1848, CA1873
}
}
}
1 change: 1 addition & 0 deletions src/RustPlusBot.Discord/RustPlusBot.Discord.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
<ItemGroup>
<PackageReference Include="Discord.Net" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public static IServiceCollection AddAlarms(this IServiceCollection services)
services.AddSingleton<IAlarmChannelPoster, DiscordAlarmChannelPoster>();
services.AddSingleton<IAlarmRefresher, AlarmRefresher>();
services.AddSingleton<AlarmPairingCoordinator>();
services.AddSingleton<AlarmRelayChannels>();
services.AddSingleton<AlarmStateRelay>();
services.AddHostedService<AlarmsHostedService>();

Expand Down
14 changes: 8 additions & 6 deletions src/RustPlusBot.Features.Alarms/Modules/AlarmComponentModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,16 @@ public sealed class AlarmComponentModule(
IServiceScopeFactory scopeFactory,
IAlarmRefresher refresher) : InteractionModuleBase<SocketInteractionContext>
{
private const string InvalidControlMessage = "That control wasn't valid.";

/// <summary>Accepts a pending pairing prompt and starts managing the alarm.</summary>
/// <param name="tail">The "{serverId}:{entityId}" custom-id tail.</param>
[ComponentInteraction(AlarmComponentIds.AcceptPrefix + "*")]
public async Task AcceptAsync(string tail)
{
if (!TryParse(tail, out var serverId, out var entityId) || Context.Guild is null)
{
await RespondAsync("That control wasn't valid.", ephemeral: true).ConfigureAwait(false);
await RespondAsync(InvalidControlMessage, ephemeral: true).ConfigureAwait(false);
return;
}

Expand All @@ -47,7 +49,7 @@ public async Task DismissAsync(string tail)
{
if (!TryParse(tail, out var serverId, out var entityId) || Context.Guild is null)
{
await RespondAsync("That control wasn't valid.", ephemeral: true).ConfigureAwait(false);
await RespondAsync(InvalidControlMessage, ephemeral: true).ConfigureAwait(false);
return;
}

Expand All @@ -71,7 +73,7 @@ public async Task PingToggleAsync(string tail)
{
if (!TryParse(tail, out var serverId, out var entityId) || Context.Guild is null)
{
await RespondAsync("That control wasn't valid.", ephemeral: true).ConfigureAwait(false);
await RespondAsync(InvalidControlMessage, ephemeral: true).ConfigureAwait(false);
return;
}

Expand Down Expand Up @@ -106,7 +108,7 @@ public async Task RelayToggleAsync(string tail)
{
if (!TryParse(tail, out var serverId, out var entityId) || Context.Guild is null)
{
await RespondAsync("That control wasn't valid.", ephemeral: true).ConfigureAwait(false);
await RespondAsync(InvalidControlMessage, ephemeral: true).ConfigureAwait(false);
return;
}

Expand Down Expand Up @@ -141,7 +143,7 @@ public async Task RenamePromptAsync(string tail)
{
if (!TryParse(tail, out _, out _) || Context.Guild is null)
{
await RespondAsync("That control wasn't valid.", ephemeral: true).ConfigureAwait(false);
await RespondAsync(InvalidControlMessage, ephemeral: true).ConfigureAwait(false);
return;
}

Expand All @@ -159,7 +161,7 @@ public async Task RenameSubmitAsync(string tail, AlarmRenameModal modal)
ArgumentNullException.ThrowIfNull(modal);
if (!TryParse(tail, out var serverId, out var entityId) || Context.Guild is null)
{
await RespondAsync("That control wasn't valid.", ephemeral: true).ConfigureAwait(false);
await RespondAsync(InvalidControlMessage, ephemeral: true).ConfigureAwait(false);
return;
}

Expand Down
Loading
Loading