Compare commits

...

14 Commits

Author SHA1 Message Date
Toutsu 92d5d9c2d3 Merge pull request #101: fix(discord): add console logging and deferred responses
Deploy Telegram Bot / build-and-push (push) Successful in 5m56s
Deploy Telegram Bot / scan-images (push) Successful in 3m3s
Deploy Telegram Bot / deploy (push) Successful in 31s
fix(discord): add console logging and deferred responses

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 11:46:55 +03:00
Toutsu 47d106e288 fix(tests): update DiscordNewSessionHandlerTests for deferred response pattern
PR Checks / test-and-build (pull_request) Successful in 11m55s
The Command_ShouldRenderEmbedOnSuccess test asserted the presence of
WithEmbeds in DiscordNewSessionCommand.cs. After switching to deferred
responses (InteractionCallback.DeferredMessage + ModifyResponseAsync),
embeds are now set via message.Embeds = embeds instead.

Bump version → 3.0.8

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 11:33:03 +03:00
Toutsu a5624897e9 fix(discord): add console logging and deferred responses
PR Checks / test-and-build (pull_request) Failing after 12m3s
- Add builder.Logging.AddConsole() to DiscordBot Program.cs so logs
  are visible in docker logs.
- Add granular LogInformation/LogError calls to DiscordNewSessionCommand
  and DiscordRescheduleCommand to diagnose failures.
- Use InteractionCallback.DeferredMessage() + ModifyResponseAsync pattern
  for /newsession and /reschedule to avoid Discord 3-second interaction
  timeout.
- Bump version → 3.0.8

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 11:18:09 +03:00
Toutsu 11e75d036a Merge pull request #100: fix(discord): use GuildInteractionUser.Permissions instead of REST guild lookup
Deploy Telegram Bot / build-and-push (push) Successful in 5m52s
Deploy Telegram Bot / scan-images (push) Successful in 3m11s
Deploy Telegram Bot / deploy (push) Successful in 30s
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 10:57:02 +03:00
Toutsu 2942da0c35 fix(discord): use GuildInteractionUser.Permissions instead of REST guild lookup
PR Checks / test-and-build (pull_request) Successful in 11m25s
Replace REST GetGuildAsync/GetGuildUserAsync calls with authoritative
member.Permissions from the slash-command interaction payload. Discord
already resolves channel/guild permissions in the interaction JSON, so
we no longer need to fetch the guild via REST (which returns 404 when
the bot is not a REST member of the guild, e.g. user-installed apps).

Keep a best-effort GetGuildAsync call only to obtain OwnerId for the
permission checker fallback, swallowing 404 silently.

Bump version → 3.0.7

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 10:44:59 +03:00
Toutsu 549c0c96ae Merge pull request #99: fix(discord): cast COUNT to int for slash command list query
Deploy Telegram Bot / build-and-push (push) Successful in 5m27s
Deploy Telegram Bot / scan-images (push) Successful in 2m49s
Deploy Telegram Bot / deploy (push) Successful in 31s
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 10:23:05 +03:00
Toutsu dd9337dd20 fix(discord): cast COUNT to int for slash command list query
PR Checks / test-and-build (pull_request) Successful in 9m34s
PostgreSQL COUNT() returns bigint, but DiscordSessionListItemDto expects
int for PlayerCount and WaitlistCount. Dapper 2.1.72 in GmRelay.DiscordBot
(without Dapper.AOT) fails to materialize the record with bigint→int mismatch.
Added ::int casts to both COUNT expressions.

Bump version to 3.0.6.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 10:10:13 +03:00
Toutsu 3cc3b373e5 Merge pull request #98: fix(discord): resolve slash commands from interaction payload instead of gateway cache
Deploy Telegram Bot / build-and-push (push) Successful in 4m59s
Deploy Telegram Bot / scan-images (push) Successful in 2m20s
Deploy Telegram Bot / deploy (push) Successful in 28s
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 18:12:15 +03:00
Toutsu f6d5281af8 fix(discord): resolve slash commands from interaction payload instead of gateway cache
PR Checks / test-and-build (pull_request) Successful in 8m46s
Context.Guild in NetCord resolves the Guild object from the gateway client cache
(cache.Guilds.GetValueOrDefault(guildId)), not from the interaction JSON payload.
After a bot restart, the guild may not yet be cached when the first slash command
arrives, causing Context.Guild to be null even though the command is invoked
inside a guild channel. This produced "This command can only be used in a guild."

Changes:
- DiscordListSessionsCommand: use Context.Interaction.GuildId instead of Context.Guild.Id
- DiscordNewSessionCommand: use Context.Interaction.GuildId + REST GetGuildAsync/GetGuildUserAsync
- DiscordRescheduleCommand: same as above
- DiscordSessionInteractionModule: same fix for button interactions (CreateInput)
- Add null guard in GetResolvedPermissions for safety
- Bump version to 3.0.5

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 18:01:53 +03:00
Toutsu fa63886195 Merge pull request #97: fix(discord): use correct slash command context type in AddApplicationCommands
Deploy Telegram Bot / build-and-push (push) Successful in 5m1s
Deploy Telegram Bot / scan-images (push) Successful in 2m22s
Deploy Telegram Bot / deploy (push) Successful in 28s
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 17:23:32 +03:00
Toutsu 9bd5fe75c9 test: sync version assertions to 3.0.4
PR Checks / test-and-build (pull_request) Successful in 8m35s
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 17:08:01 +03:00
Toutsu d931da37ec fix(discord): use correct slash command context type in AddApplicationCommands
PR Checks / test-and-build (pull_request) Failing after 8m7s
The default AddApplicationCommands() registers ApplicationCommandService<ApplicationCommandContext>,
but our modules inherit ApplicationCommandModule<SlashCommandContext>. Because SlashCommandContext
does not inherit from ApplicationCommandContext in NetCord, AddModules(typeof(Program).Assembly)
failed to discover the modules, so /newsession, /listsessions, /reschedule were never published
to Discord. Only /ping worked because it uses the minimal API route.

Fix: specify AddApplicationCommands<SlashCommandInteraction, SlashCommandContext>() so the
service matches the module context type, allowing module discovery to succeed.

Bump version to 3.0.4.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 17:05:51 +03:00
Toutsu 9375fa45b2 Merge pull request #96: fix(discord): declare slash commands on module methods
Deploy Telegram Bot / build-and-push (push) Successful in 4m47s
Deploy Telegram Bot / scan-images (push) Successful in 2m9s
Deploy Telegram Bot / deploy (push) Successful in 27s
2026-05-25 16:37:15 +03:00
Toutsu 0b45aee96d fix(discord): declare slash commands on module methods
PR Checks / test-and-build (pull_request) Successful in 8m26s
2026-05-25 16:27:29 +03:00
13 changed files with 196 additions and 81 deletions
+1 -1
View File
@@ -6,7 +6,7 @@ on:
- main - main
env: env:
VERSION: 3.0.2 VERSION: 3.0.8
jobs: jobs:
# ЧАСТЬ 1: Собираем образы и кладем в Gitea (чтобы делиться с ребятами) # ЧАСТЬ 1: Собираем образы и кладем в Gitea (чтобы делиться с ребятами)
+1 -1
View File
@@ -1,6 +1,6 @@
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<Version>3.0.2</Version> <Version>3.0.8</Version>
<TargetFramework>net10.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
<LangVersion>preview</LangVersion> <LangVersion>preview</LangVersion>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
+3 -3
View File
@@ -49,7 +49,7 @@ services:
crond -f crond -f
bot: bot:
image: git.codeanddice.ru/toutsu/gmrelay-bot:3.0.2 image: git.codeanddice.ru/toutsu/gmrelay-bot:3.0.8
restart: always restart: always
depends_on: depends_on:
db: db:
@@ -67,7 +67,7 @@ services:
retries: 3 retries: 3
discord: discord:
image: git.codeanddice.ru/toutsu/gmrelay-discord-bot:3.0.2 image: git.codeanddice.ru/toutsu/gmrelay-discord-bot:3.0.8
restart: always restart: always
depends_on: depends_on:
db: db:
@@ -84,7 +84,7 @@ services:
retries: 3 retries: 3
web: web:
image: git.codeanddice.ru/toutsu/gmrelay-web:3.0.2 image: git.codeanddice.ru/toutsu/gmrelay-web:3.0.8
restart: always restart: always
depends_on: depends_on:
db: db:
@@ -3,7 +3,6 @@ using NetCord.Services.ApplicationCommands;
namespace GmRelay.DiscordBot.Features.Sessions; namespace GmRelay.DiscordBot.Features.Sessions;
[SlashCommand("listsessions", "Show upcoming game sessions in this server")]
public class DiscordListSessionsCommand : ApplicationCommandModule<SlashCommandContext> public class DiscordListSessionsCommand : ApplicationCommandModule<SlashCommandContext>
{ {
private readonly DiscordListSessionsHandler _handler; private readonly DiscordListSessionsHandler _handler;
@@ -13,9 +12,10 @@ public class DiscordListSessionsCommand : ApplicationCommandModule<SlashCommandC
_handler = handler; _handler = handler;
} }
[SlashCommand("listsessions", "Show upcoming game sessions in this server")]
public async Task ExecuteAsync() public async Task ExecuteAsync()
{ {
var guildId = Context.Guild?.Id.ToString() var guildId = Context.Interaction.GuildId?.ToString()
?? throw new InvalidOperationException("This command can only be used in a guild."); ?? throw new InvalidOperationException("This command can only be used in a guild.");
var channelId = Context.Channel.Id.ToString(); var channelId = Context.Channel.Id.ToString();
@@ -21,8 +21,8 @@ public sealed class DiscordListSessionsHandler(NpgsqlDataSource dataSource)
var sessions = await connection.QueryAsync<DiscordSessionListItemDto>( var sessions = await connection.QueryAsync<DiscordSessionListItemDto>(
@"SELECT s.id as Id, s.title as Title, s.scheduled_at as ScheduledAt, s.status as Status, @"SELECT s.id as Id, s.title as Title, s.scheduled_at as ScheduledAt, s.status as Status,
s.max_players as MaxPlayers, s.max_players as MaxPlayers,
COUNT(sp.id) FILTER (WHERE sp.is_gm = false AND sp.registration_status = @Active) as PlayerCount, COUNT(sp.id) FILTER (WHERE sp.is_gm = false AND sp.registration_status = @Active)::int as PlayerCount,
COUNT(sp.id) FILTER (WHERE sp.is_gm = false AND sp.registration_status = @Waitlisted) as WaitlistCount COUNT(sp.id) FILTER (WHERE sp.is_gm = false AND sp.registration_status = @Waitlisted)::int as WaitlistCount
FROM sessions s FROM sessions s
JOIN game_groups g ON s.group_id = g.id JOIN game_groups g ON s.group_id = g.id
LEFT JOIN session_participants sp ON s.id = sp.session_id LEFT JOIN session_participants sp ON s.id = sp.session_id
@@ -1,10 +1,10 @@
using GmRelay.DiscordBot.Rendering; using GmRelay.DiscordBot.Rendering;
using NetCord;
using NetCord.Rest; using NetCord.Rest;
using NetCord.Services.ApplicationCommands; using NetCord.Services.ApplicationCommands;
namespace GmRelay.DiscordBot.Features.Sessions; namespace GmRelay.DiscordBot.Features.Sessions;
[SlashCommand("newsession", "Create a new game session")]
public class DiscordNewSessionCommand : ApplicationCommandModule<SlashCommandContext> public class DiscordNewSessionCommand : ApplicationCommandModule<SlashCommandContext>
{ {
private readonly DiscordNewSessionHandler _handler; private readonly DiscordNewSessionHandler _handler;
@@ -16,15 +16,52 @@ public class DiscordNewSessionCommand : ApplicationCommandModule<SlashCommandCon
_logger = logger; _logger = logger;
} }
[SlashCommand("newsession", "Create a new game session")]
public async Task ExecuteAsync( public async Task ExecuteAsync(
[SlashCommandParameter(Name = "title", Description = "Game title")] string title, [SlashCommandParameter(Name = "title", Description = "Game title")] string title,
[SlashCommandParameter(Name = "time", Description = "Session time (YYYY-MM-DD HH:mm or DD.MM.YYYY HH:mm)")] string time, [SlashCommandParameter(Name = "time", Description = "Session time (YYYY-MM-DD HH:mm or DD.MM.YYYY HH:mm)")] string time,
[SlashCommandParameter(Name = "seats", Description = "Maximum number of players")] long? seats = null, [SlashCommandParameter(Name = "seats", Description = "Maximum number of players")] long? seats = null,
[SlashCommandParameter(Name = "link", Description = "Join link")] string? link = null) [SlashCommandParameter(Name = "link", Description = "Join link")] string? link = null)
{ {
var guild = Context.Guild _logger.LogInformation(
"newsession called by user {UserId} ({UserType}) in guild {GuildId}, channel {ChannelId}",
Context.User.Id,
Context.User.GetType().Name,
Context.Interaction.GuildId,
Context.Channel?.Id);
var guildId = Context.Interaction.GuildId
?? throw new InvalidOperationException("This command can only be used in a guild."); ?? throw new InvalidOperationException("This command can only be used in a guild.");
var member = Context.User as GuildInteractionUser;
if (member is null)
{
_logger.LogError("Context.User is not GuildInteractionUser. Actual type: {ActualType}", Context.User.GetType().Name);
throw new InvalidOperationException("Guild member data not available in interaction.");
}
var resolvedPermissions = (ulong)member.Permissions;
_logger.LogInformation("Resolved permissions for user {UserId}: {Permissions}", Context.User.Id, resolvedPermissions);
ulong guildOwnerId = 0;
try
{
var guild = await Context.Client.Rest.GetGuildAsync(guildId);
guildOwnerId = guild.OwnerId;
_logger.LogInformation("Guild owner id: {OwnerId}", guildOwnerId);
}
catch (RestException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
_logger.LogWarning(
ex,
"Bot is not a REST member of guild {GuildId}; using resolved permissions from interaction payload",
guildId);
}
catch (Exception ex)
{
_logger.LogError(ex, "Unexpected error fetching guild {GuildId}", guildId);
}
var timeResult = DiscordNewSessionHandler.ParseTimeInput(time); var timeResult = DiscordNewSessionHandler.ParseTimeInput(time);
if (!timeResult.IsSuccess) if (!timeResult.IsSuccess)
{ {
@@ -33,55 +70,56 @@ public class DiscordNewSessionCommand : ApplicationCommandModule<SlashCommandCon
return; return;
} }
var resolvedPermissions = GetResolvedPermissions(guild, Context.User.Id); // Defer the response to avoid Discord 3-second interaction timeout
await Context.Interaction.SendResponseAsync(InteractionCallback.DeferredMessage());
try try
{ {
_logger.LogInformation("Creating session for guild {GuildId}, user {UserId}", guildId, Context.User.Id);
var view = await _handler.HandleAsync( var view = await _handler.HandleAsync(
guildId: guild.Id.ToString(), guildId: guildId.ToString(),
channelId: Context.Channel.Id.ToString(), channelId: Context.Channel!.Id.ToString(),
userId: Context.User.Id, userId: Context.User.Id,
userDisplayName: Context.User.GlobalName ?? Context.User.Username, userDisplayName: Context.User.GlobalName ?? Context.User.Username,
resolvedPermissions: resolvedPermissions, resolvedPermissions: resolvedPermissions,
guildOwnerId: guild.OwnerId, guildOwnerId: guildOwnerId,
title: title, title: title,
scheduledAt: timeResult.Value, scheduledAt: timeResult.Value,
maxPlayers: seats is null ? null : (int)seats.Value, maxPlayers: seats is null ? null : (int)seats.Value,
joinLink: link, joinLink: link,
CancellationToken.None); CancellationToken.None);
_logger.LogInformation("Session created successfully. Building render.");
var (embeds, actionRows) = DiscordSessionBatchRenderer.Render(view); var (embeds, actionRows) = DiscordSessionBatchRenderer.Render(view);
await Context.Interaction.SendResponseAsync(
InteractionCallback.Message(new InteractionMessageProperties() _logger.LogInformation("Sending success response.");
.WithContent(":white_check_mark: **Session created successfully!**")
.WithEmbeds(embeds) await Context.Interaction.ModifyResponseAsync(message =>
.WithComponents(actionRows))); {
message.Content = ":white_check_mark: **Session created successfully!**";
message.Embeds = embeds;
message.Components = actionRows;
});
_logger.LogInformation("Success response sent.");
} }
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
await Context.Interaction.SendResponseAsync( _logger.LogWarning(ex, "Unauthorized session creation attempt by user {UserId}", Context.User.Id);
InteractionCallback.Message($":no_entry: {ex.Message}")); await Context.Interaction.ModifyResponseAsync(message =>
{
message.Content = $":no_entry: {ex.Message}";
});
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Failed to create session for user {UserId} in guild {GuildId}", Context.User.Id, guild.Id); _logger.LogError(ex, "Failed to create session for user {UserId} in guild {GuildId}", Context.User.Id, guildId);
await Context.Interaction.SendResponseAsync( await Context.Interaction.ModifyResponseAsync(message =>
InteractionCallback.Message(":boom: An error occurred while creating the session.")); {
message.Content = ":boom: An error occurred while creating the session.";
});
} }
} }
private static ulong GetResolvedPermissions(NetCord.Gateway.Guild guild, ulong userId)
{
if (!guild.Users.TryGetValue(userId, out var guildUser))
return 0;
ulong resolved = 0;
foreach (var roleId in guildUser.RoleIds)
{
if (guild.Roles.TryGetValue(roleId, out var role))
resolved |= (ulong)role.Permissions;
}
return resolved;
}
} }
@@ -1,9 +1,9 @@
namespace GmRelay.DiscordBot.Features.Sessions; namespace GmRelay.DiscordBot.Features.Sessions;
using NetCord;
using NetCord.Rest; using NetCord.Rest;
using NetCord.Services.ApplicationCommands; using NetCord.Services.ApplicationCommands;
[SlashCommand("reschedule", "Initiate reschedule voting for a session")]
public class DiscordRescheduleCommand : ApplicationCommandModule<SlashCommandContext> public class DiscordRescheduleCommand : ApplicationCommandModule<SlashCommandContext>
{ {
private readonly DiscordRescheduleHandler _handler; private readonly DiscordRescheduleHandler _handler;
@@ -15,6 +15,7 @@ public class DiscordRescheduleCommand : ApplicationCommandModule<SlashCommandCon
_logger = logger; _logger = logger;
} }
[SlashCommand("reschedule", "Initiate reschedule voting for a session")]
public async Task ExecuteAsync( public async Task ExecuteAsync(
[SlashCommandParameter(Name = "session", Description = "Session ID to reschedule")] string sessionIdText, [SlashCommandParameter(Name = "session", Description = "Session ID to reschedule")] string sessionIdText,
[SlashCommandParameter(Name = "option1", Description = "First time option (YYYY-MM-DD HH:mm)")] string option1, [SlashCommandParameter(Name = "option1", Description = "First time option (YYYY-MM-DD HH:mm)")] string option1,
@@ -22,9 +23,44 @@ public class DiscordRescheduleCommand : ApplicationCommandModule<SlashCommandCon
[SlashCommandParameter(Name = "option3", Description = "Third time option (optional)")] string? option3 = null, [SlashCommandParameter(Name = "option3", Description = "Third time option (optional)")] string? option3 = null,
[SlashCommandParameter(Name = "deadline", Description = "Voting deadline (YYYY-MM-DD HH:mm)")] string deadline = "") [SlashCommandParameter(Name = "deadline", Description = "Voting deadline (YYYY-MM-DD HH:mm)")] string deadline = "")
{ {
var guild = Context.Guild _logger.LogInformation(
"reschedule called by user {UserId} ({UserType}) in guild {GuildId}",
Context.User.Id,
Context.User.GetType().Name,
Context.Interaction.GuildId);
var guildId = Context.Interaction.GuildId
?? throw new InvalidOperationException("This command can only be used in a guild."); ?? throw new InvalidOperationException("This command can only be used in a guild.");
var member = Context.User as GuildInteractionUser;
if (member is null)
{
_logger.LogError("Context.User is not GuildInteractionUser. Actual type: {ActualType}", Context.User.GetType().Name);
throw new InvalidOperationException("Guild member data not available in interaction.");
}
var resolvedPermissions = (ulong)member.Permissions;
_logger.LogInformation("Resolved permissions for user {UserId}: {Permissions}", Context.User.Id, resolvedPermissions);
ulong guildOwnerId = 0;
try
{
var guild = await Context.Client.Rest.GetGuildAsync(guildId);
guildOwnerId = guild.OwnerId;
_logger.LogInformation("Guild owner id: {OwnerId}", guildOwnerId);
}
catch (RestException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
_logger.LogWarning(
ex,
"Bot is not a REST member of guild {GuildId}; using resolved permissions from interaction payload",
guildId);
}
catch (Exception ex)
{
_logger.LogError(ex, "Unexpected error fetching guild {GuildId}", guildId);
}
if (!Guid.TryParse(sessionIdText, out var sessionId)) if (!Guid.TryParse(sessionIdText, out var sessionId))
{ {
await Context.Interaction.SendResponseAsync( await Context.Interaction.SendResponseAsync(
@@ -64,54 +100,55 @@ public class DiscordRescheduleCommand : ApplicationCommandModule<SlashCommandCon
return; return;
} }
var resolvedPermissions = GetResolvedPermissions(guild, Context.User.Id); // Defer the response to avoid Discord 3-second interaction timeout
await Context.Interaction.SendResponseAsync(InteractionCallback.DeferredMessage());
try try
{ {
_logger.LogInformation("Initiating reschedule for session {SessionId} in guild {GuildId}", sessionId, guildId);
var result = await _handler.HandleAsync( var result = await _handler.HandleAsync(
guildId: guild.Id.ToString(), guildId: guildId.ToString(),
channelId: Context.Channel.Id.ToString(), channelId: Context.Channel!.Id.ToString(),
userId: Context.User.Id, userId: Context.User.Id,
userDisplayName: Context.User.GlobalName ?? Context.User.Username, userDisplayName: Context.User.GlobalName ?? Context.User.Username,
resolvedPermissions: resolvedPermissions, resolvedPermissions: resolvedPermissions,
guildOwnerId: guild.OwnerId, guildOwnerId: guildOwnerId,
sessionId: sessionId, sessionId: sessionId,
options: parsedOptions, options: parsedOptions,
deadline: deadlineResult.Value, deadline: deadlineResult.Value,
CancellationToken.None); CancellationToken.None);
await Context.Interaction.SendResponseAsync( _logger.LogInformation("Reschedule voting started for session {SessionId}, proposal {ProposalId}", sessionId, result.ProposalId);
InteractionCallback.Message(
$"🗳 Голосование за перенос запущено! Дедлайн: {deadlineResult.Value:yyyy-MM-dd HH:mm} UTC.")); await Context.Interaction.ModifyResponseAsync(message =>
{
message.Content = $"🗳 Голосование за перенос запущено! Дедлайн: {deadlineResult.Value:yyyy-MM-dd HH:mm} UTC.";
});
} }
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
await Context.Interaction.SendResponseAsync( _logger.LogWarning(ex, "Unauthorized reschedule attempt by user {UserId}", Context.User.Id);
InteractionCallback.Message($":no_entry: {ex.Message}")); await Context.Interaction.ModifyResponseAsync(message =>
{
message.Content = $":no_entry: {ex.Message}";
});
} }
catch (InvalidOperationException ex) catch (InvalidOperationException ex)
{ {
await Context.Interaction.SendResponseAsync( _logger.LogWarning(ex, "Invalid reschedule request by user {UserId}", Context.User.Id);
InteractionCallback.Message($":warning: {ex.Message}")); await Context.Interaction.ModifyResponseAsync(message =>
{
message.Content = $":warning: {ex.Message}";
});
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Failed to initiate reschedule for session {SessionId}", sessionId); _logger.LogError(ex, "Failed to initiate reschedule for session {SessionId}", sessionId);
await Context.Interaction.SendResponseAsync( await Context.Interaction.ModifyResponseAsync(message =>
InteractionCallback.Message(":boom: Ошибка при запуске голосования.")); {
message.Content = ":boom: Ошибка при запуске голосования.";
});
} }
} }
private static ulong GetResolvedPermissions(NetCord.Gateway.Guild guild, ulong userId)
{
if (!guild.Users.TryGetValue(userId, out var guildUser))
return 0;
ulong resolved = 0;
foreach (var roleId in guildUser.RoleIds)
{
if (guild.Roles.TryGetValue(roleId, out var role))
resolved |= (ulong)role.Permissions;
}
return resolved;
}
} }
@@ -168,7 +168,7 @@ public sealed class DiscordSessionInteractionModule(
private DiscordSessionInteractionInput CreateInput(Guid sessionId) private DiscordSessionInteractionInput CreateInput(Guid sessionId)
{ {
var guild = Context.Guild var guildId = Context.Interaction.GuildId?.ToString(CultureInfo.InvariantCulture)
?? throw new InvalidOperationException("Session buttons can only be used in a guild."); ?? throw new InvalidOperationException("Session buttons can only be used in a guild.");
var message = Context.Interaction.Message var message = Context.Interaction.Message
?? throw new InvalidOperationException("Session button interaction must include a message."); ?? throw new InvalidOperationException("Session button interaction must include a message.");
@@ -176,7 +176,7 @@ public sealed class DiscordSessionInteractionModule(
return new DiscordSessionInteractionInput( return new DiscordSessionInteractionInput(
SessionId: sessionId, SessionId: sessionId,
InteractionId: Context.Interaction.Id.ToString(System.Globalization.CultureInfo.InvariantCulture), InteractionId: Context.Interaction.Id.ToString(System.Globalization.CultureInfo.InvariantCulture),
GuildId: guild.Id.ToString(CultureInfo.InvariantCulture), GuildId: guildId,
ChannelId: Context.Channel.Id.ToString(CultureInfo.InvariantCulture), ChannelId: Context.Channel.Id.ToString(CultureInfo.InvariantCulture),
MessageId: message.Id.ToString(CultureInfo.InvariantCulture), MessageId: message.Id.ToString(CultureInfo.InvariantCulture),
UserId: Context.User.Id, UserId: Context.User.Id,
+4 -1
View File
@@ -21,6 +21,7 @@ using NetCord.Hosting.Gateway;
using NetCord.Hosting.Services; using NetCord.Hosting.Services;
using NetCord.Hosting.Services.ApplicationCommands; using NetCord.Hosting.Services.ApplicationCommands;
using NetCord.Hosting.Services.ComponentInteractions; using NetCord.Hosting.Services.ComponentInteractions;
using NetCord.Services.ApplicationCommands;
using NetCord.Services.ComponentInteractions; using NetCord.Services.ComponentInteractions;
using Npgsql; using Npgsql;
@@ -35,6 +36,8 @@ discordOptions.Validate();
builder.Services.AddSingleton(discordOptions); builder.Services.AddSingleton(discordOptions);
builder.Logging.AddConsole();
builder.Services.AddSingleton<NpgsqlDataSource>(sp => builder.Services.AddSingleton<NpgsqlDataSource>(sp =>
{ {
var config = sp.GetRequiredService<IConfiguration>(); var config = sp.GetRequiredService<IConfiguration>();
@@ -83,7 +86,7 @@ builder.Services
options.Token = discordOptions.Token; options.Token = discordOptions.Token;
options.Intents = GatewayIntents.Guilds; options.Intents = GatewayIntents.Guilds;
}) })
.AddApplicationCommands() .AddApplicationCommands<SlashCommandInteraction, SlashCommandContext>()
.AddComponentInteractions<ButtonInteraction, ButtonInteractionContext>() .AddComponentInteractions<ButtonInteraction, ButtonInteractionContext>()
.AddGatewayHandlers(typeof(Program).Assembly); .AddGatewayHandlers(typeof(Program).Assembly);
@@ -73,7 +73,7 @@
</button> </button>
</form> </form>
<div class="nav-version">v3.0.2</div> <div class="nav-version">v3.0.8</div>
</div> </div>
</Authorized> </Authorized>
<NotAuthorized> <NotAuthorized>
@@ -145,7 +145,7 @@ public sealed class DiscordNewSessionHandlerTests
var source = File.ReadAllText(commandPath); var source = File.ReadAllText(commandPath);
Assert.Contains("DiscordSessionBatchRenderer.Render", source, StringComparison.Ordinal); Assert.Contains("DiscordSessionBatchRenderer.Render", source, StringComparison.Ordinal);
Assert.Contains("WithEmbeds", source, StringComparison.Ordinal); Assert.Contains("message.Embeds = embeds", source, StringComparison.Ordinal);
} }
private static DateTimeOffset FutureDateAt1930() private static DateTimeOffset FutureDateAt1930()
@@ -61,7 +61,7 @@ public sealed class DiscordProjectStructureTests
var prChecks = File.ReadAllText(Path.Combine(repoRoot, ".gitea", "workflows", "pr-checks.yml")); var prChecks = File.ReadAllText(Path.Combine(repoRoot, ".gitea", "workflows", "pr-checks.yml"));
var deploy = File.ReadAllText(Path.Combine(repoRoot, ".gitea", "workflows", "deploy.yml")); var deploy = File.ReadAllText(Path.Combine(repoRoot, ".gitea", "workflows", "deploy.yml"));
Assert.Contains("gmrelay-discord-bot:3.0.2", compose); Assert.Contains("gmrelay-discord-bot:3.0.8", compose);
Assert.Contains("Discord__Token=${DISCORD_BOT_TOKEN:?Set DISCORD_BOT_TOKEN in .env}", compose); Assert.Contains("Discord__Token=${DISCORD_BOT_TOKEN:?Set DISCORD_BOT_TOKEN in .env}", compose);
Assert.Contains("src/GmRelay.DiscordBot/Dockerfile", deploy); Assert.Contains("src/GmRelay.DiscordBot/Dockerfile", deploy);
Assert.Contains("DISCORD_BOT_TOKEN", deploy); Assert.Contains("DISCORD_BOT_TOKEN", deploy);
@@ -75,13 +75,13 @@ public sealed class DiscordProjectStructureTests
{ {
var repoRoot = GetRepoRoot(); var repoRoot = GetRepoRoot();
Assert.Contains("<Version>3.0.2</Version>", File.ReadAllText(Path.Combine(repoRoot, "Directory.Build.props"))); Assert.Contains("<Version>3.0.8</Version>", File.ReadAllText(Path.Combine(repoRoot, "Directory.Build.props")));
Assert.Contains("VERSION: 3.0.2", File.ReadAllText(Path.Combine(repoRoot, ".gitea", "workflows", "deploy.yml"))); Assert.Contains("VERSION: 3.0.8", File.ReadAllText(Path.Combine(repoRoot, ".gitea", "workflows", "deploy.yml")));
Assert.Contains("gmrelay-bot:3.0.2", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml"))); Assert.Contains("gmrelay-bot:3.0.8", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
Assert.Contains("gmrelay-web:3.0.2", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml"))); Assert.Contains("gmrelay-web:3.0.8", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
Assert.Contains("gmrelay-discord-bot:3.0.2", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml"))); Assert.Contains("gmrelay-discord-bot:3.0.8", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
Assert.Contains( Assert.Contains(
"v3.0.2", "v3.0.8",
File.ReadAllText(Path.Combine(repoRoot, "src", "GmRelay.Web", "Components", "Layout", "NavMenu.razor"))); File.ReadAllText(Path.Combine(repoRoot, "src", "GmRelay.Web", "Components", "Layout", "NavMenu.razor")));
} }
@@ -1,5 +1,8 @@
using System; using System;
using System.IO; using System.IO;
using System.Reflection;
using GmRelay.DiscordBot.Features.Sessions;
using NetCord.Services.ApplicationCommands;
namespace GmRelay.Bot.Tests.Discord; namespace GmRelay.Bot.Tests.Discord;
@@ -50,6 +53,40 @@ public sealed class DiscordStartupTests
Assert.Contains("AddModules(typeof(Program).Assembly)", program); Assert.Contains("AddModules(typeof(Program).Assembly)", program);
} }
[Theory]
[InlineData(typeof(DiscordNewSessionCommand), "newsession")]
[InlineData(typeof(DiscordListSessionsCommand), "listsessions")]
[InlineData(typeof(DiscordRescheduleCommand), "reschedule")]
public void DiscordSessionSlashCommands_ShouldBeDeclaredOnModuleMethods(Type moduleType, string commandName)
{
var executeMethod = moduleType.GetMethod("ExecuteAsync", BindingFlags.Instance | BindingFlags.Public);
Assert.NotNull(executeMethod);
var methodAttribute = Assert.Single(executeMethod.GetCustomAttributes<SlashCommandAttribute>(inherit: false));
var nameProperty = typeof(SlashCommandAttribute).GetProperty("Name")
?? throw new InvalidOperationException("SlashCommandAttribute should expose command name.");
Assert.Equal(commandName, nameProperty.GetValue(methodAttribute));
Assert.Empty(moduleType.GetCustomAttributes<SlashCommandAttribute>(inherit: false));
}
[Fact]
public void DiscordSessionSlashCommands_ShouldBeDiscoverableByNetCordService()
{
var service = new ApplicationCommandService<SlashCommandContext>();
service.AddModules(typeof(DiscordNewSessionCommand).Assembly);
var commandNames = service.GetCommands()
.Select(command => command.Name)
.ToArray();
Assert.Contains("newsession", commandNames);
Assert.Contains("listsessions", commandNames);
Assert.Contains("reschedule", commandNames);
}
[Fact] [Fact]
public void LifecycleLogger_ShouldLogGatewayLifecycleEventsWithoutTokenValues() public void LifecycleLogger_ShouldLogGatewayLifecycleEventsWithoutTokenValues()
{ {