summaryrefslogtreecommitdiff
path: root/DiscoBot/Auxiliary/CommandExtension.cs
blob: 5d07f6c9571b7be844484d8ced648284eb2bf2c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
namespace DiscoBot.Auxiliary
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;

    using Discord;
    using Discord.Commands;

    public static class CommandExtension
    {
        public static async Task ReplyTimedAsync(this ModuleBase m, string message, TimeSpan time)
        {
            var token = message.GetHashCode();
            var send = m.Context.Channel.SendMessageAsync($"#{token}\n```xl\n{message}```", false);

            var barInvoker = new BackgroundWorker();
            barInvoker.DoWork += delegate
                {
                    Thread.Sleep(time);
                    Delete(token, m);
                };

            await send;
            barInvoker.RunWorkerAsync();
        }

        private static void Delete(int token, ModuleBase m)
        {
            var messagesAsync = m.Context.Channel.GetMessagesAsync();
            Task.WaitAll(messagesAsync.ToArray());
            var list = messagesAsync.ToEnumerable().ToList();
            var messages = new List<IMessage>();
            foreach (var task in list)
            {
                messages.AddRange(task.ToList());
            }

            m.Context.Channel.DeleteMessagesAsync(
                messages.Where(x => x.Content.StartsWith($"#{token}\n") && x.Author.IsBot));
        }


    }
}