listen for text response in YesNoPrompt interactive

This commit is contained in:
spiral
2021-07-02 06:35:25 -04:00
parent af801e2b01
commit 2b15815825
3 changed files with 88 additions and 10 deletions

View File

@@ -1,7 +1,15 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Myriad.Gateway;
using Myriad.Rest.Types;
using Myriad.Types;
using PluralKit.Core;
using Autofac;
namespace PluralKit.Bot.Interactive
{
public class YesNoPrompt: BaseInteractive
@@ -20,7 +28,13 @@ namespace PluralKit.Bot.Interactive
{
AddButton(ctx => OnButtonClick(ctx, true), AcceptLabel, AcceptStyle);
AddButton(ctx => OnButtonClick(ctx, false), CancelLabel, CancelStyle);
await Send(Message);
AllowedMentions mentions = null;
if (User != _ctx.Author.Id)
mentions = new AllowedMentions {Users = new[] {User!.Value}};
await Send(Message, mentions: mentions);
}
private async Task OnButtonClick(InteractionContext ctx, bool result)
@@ -35,6 +49,58 @@ namespace PluralKit.Bot.Interactive
await Finish(ctx);
}
private bool MessagePredicate(MessageCreateEvent e)
{
if (e.ChannelId != _ctx.Channel.Id) return false;
if (e.Author.Id != User) return false;
var response = e.Content.ToLowerInvariant();
if (response == "y" || response == "yes")
{
Result = true;
return true;
}
if (response == "n" || response == "no")
{
Result = false;
return true;
}
return false;
}
public new async Task Run()
{
// todo: can we split this up somehow so it doesn't need to be *completely* copied from BaseInteractive?
var cts = new CancellationTokenSource(Timeout.ToTimeSpan());
if (_running)
throw new InvalidOperationException("Action is already running");
_running = true;
var queue = _ctx.Services.Resolve<HandlerQueue<MessageCreateEvent>>();
var messageDispatch = queue.WaitFor(MessagePredicate, Timeout, cts.Token);
await Start();
cts.Token.Register(() => _tcs.TrySetException(new TimeoutException("Action timed out")));
try
{
var doneTask = await Task.WhenAny(_tcs.Task, messageDispatch);
if (doneTask == messageDispatch)
await Finish();
}
finally
{
Cleanup();
}
}
public YesNoPrompt(Context ctx): base(ctx)
{
User = ctx.Author.Id;