Beispiel #1
0
        public static async Task <IDisposable> EnterTypingState(this ISocketMessageChannel self, int seconds)
        {
            IDisposable state      = self.EnterTypingState();
            Timer       stateTimer = null;

            stateTimer = new Timer((e) => {
                if (state != null)
                {
                    state.Dispose();
                }
                stateTimer.Dispose();
                stateTimer = null;
            }, state, MathService.TimeUnitToMilli(TimeUnit.Seconds, seconds), 0);
            await Task.CompletedTask;

            return(state);
        }
Beispiel #2
0
        public async Task Execute(ISocketMessageChannel channel)
        {
            using (channel.EnterTypingState())
            {
                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName               = "/bin/bash",
                        Arguments              = $"-c \"{executionCommand.Replace("\"", "\\\"")}\"",
                        UseShellExecute        = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true,
                        CreateNoWindow         = false
                    }
                };

                process.Start();
                process.WaitForExit();

                var temp = "";

                var output = new List <string>();
                while ((temp = process.StandardOutput.ReadLine()) != null)
                {
                    output.Add(temp);
                }

                var errorOutput = new List <string>();
                while ((temp = process.StandardError.ReadLine()) != null)
                {
                    errorOutput.Add(temp);
                }

                int exitCode = process.ExitCode;
                process.Close();

                //string commandText = $"/bin/bash -c \"{executionCommand.Replace("\"", "\\\"")}\"";
                string message = $"Command: `{executionCommand}`\nExit Code: `{exitCode}`\nOutput: ```{(output.Count > 0 ? string.Join("\n", output) : " ")}```\nError: ```{(errorOutput.Count > 0 ? string.Join("\n", errorOutput) : " ")}```";

                await channel.SendMessageAsync(message);
            }
        }
Beispiel #3
0
        private async Task SendResponse(CompiledRule rule, ISocketMessageChannel channel)
        {
            var msg = rule.GetRandomMessage();

            if (msg == null)
            {
                return;
            }

            // looks as if the bot is typing
            var isTypingState = channel.EnterTypingState();
            // calculate some average typing speed
            // float kph = 15000; // 15k keystrokes per hour
            // float kpm = kph / 60; // keystrokes per minute
            // float kps = kpm / 60; // keystrokes per second.
            float keysPerSec = 6.0f;
            float timeToWait = (1f / keysPerSec) * msg.Length;

            await Task.Delay(TimeSpan.FromSeconds(timeToWait));

            isTypingState.Dispose();
            msg = placeholderHandler.Replace(msg, this);
            await channel.SendMessageAsync(msg);
        }
        public async Task InlineCardSearch(SocketMessage message)
        {
            if (message.Author.IsBot)
            {
                return;
            }

            string content = message?.Content;

            if (string.IsNullOrEmpty(content))
            {
                return;
            }

            ISocketMessageChannel channel = message.Channel;
            MatchCollection       m       = Regex.Matches(content, InlinePattern);
            Stopwatch             stopwatch;

            if (m.Count != 0 && m.Count < 4)
            {
                stopwatch = new Stopwatch();
                stopwatch.Start();

                try
                {
                    using (channel.EnterTypingState())
                    {
                        if (channel is SocketGuildChannel)
                        {
                            await AltConsole.PrintAsync("Service", "Chat", $"{(channel as SocketGuildChannel).Guild.Name}");
                        }

                        await AltConsole.PrintAsync("Service", "Chat", $"Inline card recieved, message was: {content}");

                        //had to use m.OfType<Match>() due to matches not implementing generic IEnumerable
                        //thanks stackoverflow :D
                        Parallel.ForEach(m.OfType <Match>(), async(match) =>
                        {
                            string cardName = match.ToString();
                            cardName        = cardName.Substring(2, cardName.Length - 4).ToLower(); //lose the brackets

                            if (string.IsNullOrEmpty(cardName))                                     //return if there is no input
                            {
                                return;
                            }

                            var input = cardName.Split(' ');

                            //check if the card list contains anything from the input and return that instead
                            //ex. kaiju slumber would return Interrupted Kaiju Slumber
                            //note: it has problems such as "red eyes" will return Hundred Eyes Dragon instead of Red-Eyes Dragon
                            //how to accurately solve this problem is not easy
                            string closestCard = CacheService.CardNames.AsParallel().FirstOrDefault(card => card.ToLower() == cardName);

                            if (string.IsNullOrEmpty(closestCard))
                            {
                                closestCard = CacheService.CardNames.AsParallel().FirstOrDefault(card => input.All(i => card.ToLower().Contains(i)));

                                if (string.IsNullOrEmpty(closestCard))
                                {
                                    closestCard = CacheService.CardNames.AsParallel().MinBy(card => Compute(card.ToLower(), cardName));
                                }
                            }

                            bool minimal;

                            if (channel is SocketGuildChannel)
                            {
                                if (GuildServices.MinimalSettings.TryGetValue((channel as SocketGuildChannel).Guild.Id, out minimal))
                                {
                                }
                                else
                                {
                                    minimal = false;
                                }
                            }
                            else
                            {
                                minimal = false;
                            }

                            if (CacheService.CardCache.TryGetValue(closestCard.ToLower(), out EmbedBuilder eBuilder))
                            {
                                try
                                {
                                    await channel.SendMessageAsync("", embed: await AddPriceAndImage(eBuilder, minimal));
                                }
                                catch { await AltConsole.PrintAsync("Service", "Chat", "No permission to send message"); }
                            }
                        });
                    }

                    stopwatch.Stop();
                    await AltConsole.PrintAsync("Command", "Stopwatch", $"Inline search completed in {stopwatch.Elapsed.TotalSeconds} seconds");
                }
                catch (Exception e)
                {
                    await AltConsole.PrintAsync("Service", "Chat", "", e);
                }
            }
            else if (m.Count > 3)
            {
                await channel.SendMessageAsync("Too many cards searched at once.");
            }
        }