Skip to content

Commit

Permalink
Add Timeout to pastebin
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaoxiao921 committed Sep 25, 2020
1 parent 333b302 commit 3a4e63a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
18 changes: 15 additions & 3 deletions CHEF/Components/Watcher/Watcher.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CHEF.Components.Commands.Ignore;
using CHEF.Extensions;
using Discord.WebSocket;
using Microsoft.EntityFrameworkCore;
using Sentry;
Expand All @@ -23,7 +26,6 @@ public override async Task SetupAsync()
using (var context = new IgnoreContext())
{
await context.Database.MigrateAsync();
Logger.Log("Done migrating ignore table.");
}

Client.MessageReceived += MsgWatcherAsync;
Expand All @@ -42,12 +44,12 @@ private Task MsgWatcherAsync(SocketMessage msg)
if (!string.IsNullOrEmpty(pasteBinRes))
await msg.Channel.SendMessageAsync(pasteBinRes);
var yandexRes = await _imageParser.Try(msg);
var yandexRes = await _imageParser.Try(msg).WithTimeout(TimeSpan.FromSeconds(10), CancellationToken.None);
if (!string.IsNullOrEmpty(yandexRes))
await msg.Channel.SendMessageAsync(yandexRes);
if (msg.Content.Contains("can i ask", StringComparison.InvariantCultureIgnoreCase))
if (msg.Content.Length < 26 && ContainsAny("can i ask", "can someone help", "can anyone help"))
{
await msg.Channel.SendMessageAsync($"{msg.Author.Mention} https://dontasktoask.com/");
}
Expand All @@ -57,5 +59,15 @@ private Task MsgWatcherAsync(SocketMessage msg)

return Task.CompletedTask;
}

private static bool ContainsAny(string text, params string[] testStrings)
{
return testStrings.Any(testStr => text.Contains(testStr, StringComparison.InvariantCultureIgnoreCase));
}

private static bool ContainsAll(string text, params string[] testStrings)
{
return testStrings.All(testStr => text.Contains(testStr, StringComparison.InvariantCultureIgnoreCase));
}
}
}
27 changes: 27 additions & 0 deletions CHEF/Extensions/TaskExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using System;
using System.Threading;
using System.Threading.Tasks;

namespace CHEF.Extensions
{
internal static class TaskExtensions
{
/// <summary>
/// Returns true if the task finished in time, false if the task timed out.
/// </summary>
public static Task<T> WithTimeout<T>(this Task<T> task, TimeSpan timeout, CancellationToken cancellationToken)
{
return Task.WhenAny(task, Task.Delay(timeout, cancellationToken)).ContinueWith(resultTask =>
{
cancellationToken.ThrowIfCancellationRequested();
if (resultTask != task)
{
return default;
}
return task.Result;
}, cancellationToken);
}
}
}

0 comments on commit 3a4e63a

Please sign in to comment.