1
0
Fork 1
mirror of https://github.com/TeamOctolings/Octobot.git synced 2025-04-30 19:19:54 +03:00

Added /ping command

Closes #29

Signed-off-by: Octol1ttle <l1ttleofficial@outlook.com>
This commit is contained in:
Octol1ttle 2023-07-02 13:55:49 +05:00
parent 17c43be878
commit 3f957b375b
Signed by: Octol1ttle
GPG key ID: B77C34313AEE1FFF
4 changed files with 91 additions and 13 deletions

View file

@ -78,7 +78,8 @@ public class Boyfriend {
.WithCommandGroup<BanCommandGroup>() .WithCommandGroup<BanCommandGroup>()
.WithCommandGroup<ClearCommandGroup>() .WithCommandGroup<ClearCommandGroup>()
.WithCommandGroup<KickCommandGroup>() .WithCommandGroup<KickCommandGroup>()
.WithCommandGroup<MuteCommandGroup>(); .WithCommandGroup<MuteCommandGroup>()
.WithCommandGroup<PingCommandGroup>();
var responderTypes = typeof(Boyfriend).Assembly var responderTypes = typeof(Boyfriend).Assembly
.GetExportedTypes() .GetExportedTypes()
.Where(t => t.IsResponder()); .Where(t => t.IsResponder());

View file

@ -0,0 +1,79 @@
using System.ComponentModel;
using Boyfriend.Services.Data;
using Remora.Commands.Attributes;
using Remora.Commands.Groups;
using Remora.Discord.API.Abstractions.Rest;
using Remora.Discord.Commands.Contexts;
using Remora.Discord.Commands.Feedback.Services;
using Remora.Discord.Extensions.Embeds;
using Remora.Discord.Gateway;
using Remora.Results;
// ReSharper disable ClassNeverInstantiated.Global
// ReSharper disable UnusedMember.Global
namespace Boyfriend.Commands;
/// <summary>
/// Handles the command to get the time taken for the gateway to respond to the last heartbeat: /ping
/// </summary>
public class PingCommandGroup : CommandGroup {
private readonly IDiscordRestChannelAPI _channelApi;
private readonly DiscordGatewayClient _client;
private readonly ICommandContext _context;
private readonly GuildDataService _dataService;
private readonly FeedbackService _feedbackService;
private readonly IDiscordRestUserAPI _userApi;
public PingCommandGroup(
IDiscordRestChannelAPI channelApi, ICommandContext context, DiscordGatewayClient client,
GuildDataService dataService, FeedbackService feedbackService, IDiscordRestUserAPI userApi) {
_channelApi = channelApi;
_context = context;
_client = client;
_dataService = dataService;
_feedbackService = feedbackService;
_userApi = userApi;
}
[Command("ping", "пинг")]
[Description("получает задержку")]
public async Task<Result> GetPingAsync() {
if (!_context.TryGetContextIDs(out var guildId, out var channelId, out _))
return Result.FromError(
new ArgumentNullError(nameof(_context), "Unable to retrieve necessary IDs from command context"));
var currentUserResult = await _userApi.GetCurrentUserAsync(CancellationToken);
if (!currentUserResult.IsDefined(out var currentUser))
return Result.FromError(currentUserResult);
var cfg = await _dataService.GetConfiguration(guildId.Value);
Messages.Culture = cfg.GetCulture();
var latency = _client.Latency.TotalMilliseconds;
if (latency is 0) {
// No heartbeat has occurred, estimate latency from local time and "Boyfriend is thinking..." message
var lastMessageResult = await _channelApi.GetChannelMessagesAsync(
channelId.Value, limit: 1, ct: CancellationToken);
if (!lastMessageResult.IsDefined(out var lastMessage))
return Result.FromError(lastMessageResult);
latency = DateTimeOffset.UtcNow.Subtract(lastMessage.Single().Timestamp).TotalMilliseconds;
}
// var embed = new EmbedBuilder().WithTitle($"Beep{Random.Shared.Next(1, 4)}".Localized())
// .WithDescription($"{latency:F0}{Messages.Milliseconds}")
// .WithColour(ColorsList.Green)
// .WithUserFooter(currentUser)
// .WithCurrentTimestamp()
// .Build();
var embed = new EmbedBuilder().WithSmallTitle(currentUser.GetTag(), currentUser)
.WithTitle($"Beep{Random.Shared.Next(1, 4)}".Localized())
.WithDescription($"{latency:F0}{Messages.Milliseconds}")
.WithColour(latency < 250 ? ColorsList.Green : latency < 500 ? ColorsList.Yellow : ColorsList.Red)
.WithCurrentTimestamp()
.Build();
if (!embed.IsDefined(out var built)) return Result.FromError(embed);
return (Result)await _feedbackService.SendContextualEmbedAsync(built, ct: CancellationToken);
}
}

View file

@ -54,10 +54,9 @@ public class GuildCreateResponder : IResponder<IGuildCreate> {
Messages.Culture = guildConfig.GetCulture(); Messages.Culture = guildConfig.GetCulture();
var i = Random.Shared.Next(1, 4); var i = Random.Shared.Next(1, 4);
var embed = new EmbedBuilder() var embed = new EmbedBuilder().WithSmallTitle(currentUser.GetTag(), currentUser)
.WithTitle($"Beep{i}".Localized()) .WithTitle($"Beep{i}".Localized())
.WithDescription(Messages.Ready) .WithDescription(Messages.Ready)
.WithUserFooter(currentUser)
.WithCurrentTimestamp() .WithCurrentTimestamp()
.WithColour(ColorsList.Blue) .WithColour(ColorsList.Blue)
.Build(); .Build();

View file

@ -1,6 +1,5 @@
using Boyfriend.Data; using Boyfriend.Data;
using Boyfriend.Services.Data; using Boyfriend.Services.Data;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Remora.Discord.API.Abstractions.Objects; using Remora.Discord.API.Abstractions.Objects;
@ -34,26 +33,27 @@ public class GuildUpdateService : BackgroundService {
private readonly List<Activity> _activityList = new(1) { new Activity("with Remora.Discord", ActivityType.Game) }; private readonly List<Activity> _activityList = new(1) { new Activity("with Remora.Discord", ActivityType.Game) };
private readonly IDiscordRestChannelAPI _channelApi; private readonly IDiscordRestChannelAPI _channelApi;
private readonly DiscordGatewayClient _client;
private readonly GuildDataService _dataService; private readonly GuildDataService _dataService;
private readonly IDiscordRestGuildScheduledEventAPI _eventApi; private readonly IDiscordRestGuildScheduledEventAPI _eventApi;
private readonly IDiscordRestGuildAPI _guildApi; private readonly IDiscordRestGuildAPI _guildApi;
private readonly ILogger<GuildUpdateService> _logger; private readonly ILogger<GuildUpdateService> _logger;
private readonly IServiceProvider _provider;
private readonly IDiscordRestUserAPI _userApi; private readonly IDiscordRestUserAPI _userApi;
private readonly UtilityService _utility; private readonly UtilityService _utility;
private DateTimeOffset _nextSongAt = DateTimeOffset.MinValue;
private uint _nextSongIndex; private DateTimeOffset _nextSongAt = DateTimeOffset.MinValue;
private uint _nextSongIndex;
public GuildUpdateService( public GuildUpdateService(
IDiscordRestChannelAPI channelApi, GuildDataService dataService, IDiscordRestGuildScheduledEventAPI eventApi, IDiscordRestChannelAPI channelApi, DiscordGatewayClient client, GuildDataService dataService,
IDiscordRestGuildAPI guildApi, ILogger<GuildUpdateService> logger, IServiceProvider provider, IDiscordRestGuildScheduledEventAPI eventApi, IDiscordRestGuildAPI guildApi, ILogger<GuildUpdateService> logger,
IDiscordRestUserAPI userApi, UtilityService utility) { IDiscordRestUserAPI userApi, UtilityService utility) {
_channelApi = channelApi; _channelApi = channelApi;
_client = client;
_dataService = dataService; _dataService = dataService;
_eventApi = eventApi; _eventApi = eventApi;
_guildApi = guildApi; _guildApi = guildApi;
_logger = logger; _logger = logger;
_provider = provider;
_userApi = userApi; _userApi = userApi;
_utility = utility; _utility = utility;
} }
@ -73,8 +73,7 @@ public class GuildUpdateService : BackgroundService {
if (guildIds.Count > 0 && DateTimeOffset.UtcNow >= _nextSongAt) { if (guildIds.Count > 0 && DateTimeOffset.UtcNow >= _nextSongAt) {
var nextSong = SongList[_nextSongIndex]; var nextSong = SongList[_nextSongIndex];
_activityList[0] = new Activity(nextSong.Name, ActivityType.Listening); _activityList[0] = new Activity(nextSong.Name, ActivityType.Listening);
var client = _provider.GetRequiredService<DiscordGatewayClient>(); _client.SubmitCommand(
client.SubmitCommand(
new UpdatePresence( new UpdatePresence(
UserStatus.Online, false, DateTimeOffset.UtcNow, _activityList)); UserStatus.Online, false, DateTimeOffset.UtcNow, _activityList));
_nextSongAt = DateTimeOffset.UtcNow.Add(nextSong.Duration); _nextSongAt = DateTimeOffset.UtcNow.Add(nextSong.Duration);