Exemple #1
0
 public override void Execute(IMessage commandmessage)
 {
     if (commandmessage.Channel is SocketGuildChannel)
     {
         if (commandmessage.Author.Id == Program.GetGuildFromChannel(commandmessage.Channel).OwnerId || commandmessage.Author.Id == Program.Master.Id)
         {
             if (Config.Data.PatchNoteSubscribedChannels.Contains(commandmessage.Channel.Id))
             {
                 Config.Data.PatchNoteSubscribedChannels.Remove(commandmessage.Channel.Id);
                 DiscordNETWrapper.SendText("Canceled Patch Note subscription for this channel!", commandmessage.Channel).Wait();
             }
             else
             {
                 Config.Data.PatchNoteSubscribedChannels.Add(commandmessage.Channel.Id);
                 DiscordNETWrapper.SendText("Subscribed to Patch Notes!", commandmessage.Channel).Wait();
             }
         }
         else
         {
             DiscordNETWrapper.SendText("Only the server/bot owner is authorized to use this command!", commandmessage.Channel).Wait();
         }
     }
     else
     {
         DiscordNETWrapper.SendText("You can't use this in DMs", commandmessage.Channel).Wait();
     }
 }
        public override void Execute(IMessage message)
        {
            if (message.Author.Id != Program.Master.Id)
            {
                DiscordNETWrapper.SendText("Sorry but only my Owner is allowed to use this Command.", message.Channel).Wait();
            }
            else
            {
                EmbedBuilder Embed = new EmbedBuilder();
                Embed.WithColor(0, 128, 255);

                Embed.AddFieldDirectly("CurrentDirectory", System.Environment.CurrentDirectory);
                Embed.AddFieldDirectly("Is64BitOperatingSystem", System.Environment.Is64BitOperatingSystem);
                Embed.AddFieldDirectly("MachineName", System.Environment.MachineName);
                Embed.AddFieldDirectly("OSVersion", System.Environment.OSVersion);
                Embed.AddFieldDirectly("ProcessorCount", System.Environment.ProcessorCount);
                Embed.AddFieldDirectly("SystemPageSize", System.Environment.SystemPageSize);
                Embed.AddFieldDirectly("System Start Time", DateTime.Now.Subtract(new TimeSpan(0, 0, 0, 0, System.Environment.TickCount)));
                Embed.AddFieldDirectly("UserDomainName", System.Environment.UserDomainName);
                Embed.AddFieldDirectly("UserInteractive", System.Environment.UserInteractive);
                Embed.AddFieldDirectly("UserName", System.Environment.UserName);
                Embed.AddFieldDirectly("Version", System.Environment.Version);
                Embed.AddFieldDirectly("WorkingSet", System.Environment.WorkingSet);

                DiscordNETWrapper.SendEmbed(Embed, message.Channel).Wait();
            }
        }
        public Bitmap LastP(EditNull n, IMessage m, int messagesToSkip = 0)
        {
            var messages = DiscordNETWrapper.EnumerateMessages(m.Channel).Skip(1 + messagesToSkip);

            foreach (var lm in messages)
            {
                try
                {
                    string pic = null;
                    if (lm.Attachments.Count > 0 && lm.Attachments.ElementAt(0).Size > 0)
                    {
                        if (lm.Attachments.ElementAt(0).Filename.EndsWith(".png") ||
                            lm.Attachments.ElementAt(0).Filename.EndsWith(".jpeg") ||
                            lm.Attachments.ElementAt(0).Filename.EndsWith(".jpg"))
                        {
                            pic = lm.Attachments.ElementAt(0).Url;
                        }
                    }
                    string picLink = lm.Content.GetPictureLinkInMessage();
                    if (string.IsNullOrWhiteSpace(pic) && picLink != null)
                    {
                        pic = picLink;
                    }
                    var b = pic.GetBitmapFromURL();
                    if ((long)b.Width * b.Height > maxImagePixelSize)
                    {
                        var mult = Math.Sqrt(maxImagePixelSize / ((double)b.Width * b.Height));
                        b = PictureCommands.StretchM(b, m, (float)mult, (float)mult);
                    }
                    return(b);
                }
                catch { }
            }
            throw new Exception("Didn't find any");
        }
Exemple #4
0
        public override void Execute(IMessage message)
        {
            string[] split = message.Content.Split(" ").Skip(1).Combine(" ").Split(";");

            if (split.Length == 0)
            {
                DiscordNETWrapper.SendText("Gimme Cowntent >:C", message.Channel).Wait();
            }
            else
            {
                string title = "", desc = "", imgURL = "", author = message.Author.ToString(), thumbURL = "";
                List <Tuple <string, string> > fields = new List <Tuple <string, string> >();
                try
                {
                    title    = split[0].Trim(' ');
                    desc     = split[1].Trim(' ');
                    imgURL   = split[2].Trim(' ');
                    author   = split[3].Trim(' ');
                    thumbURL = split[4].Trim(' ');
                    for (int i = 5;;)
                    {
                        fields.Add(new Tuple <string, string>(split[i++].Trim(' '), split[i++].Trim(' ')));
                    }
                }
                catch { }
                var iauthor = DiscordNETWrapper.ParseUser(author, message.Channel);
                var embed   = DiscordNETWrapper.CreateEmbedBuilder(title, desc, imgURL, iauthor, thumbURL);
                foreach (var f in fields)
                {
                    embed.AddFieldDirectly(f.Item1, f.Item2);
                }
                DiscordNETWrapper.SendEmbed(embed, message.Channel).Wait();
            }
        }
Exemple #5
0
        public override void Execute(IMessage commandmessage)
        {
            string m = commandmessage.Content.ToLower();

            if (m.Split(' ').Length >= 4 && m.Contains("?"))
            {
                if (!m.Contains("why ") && !m.Contains("what ") && !m.Contains("who ") &&
                    !m.Contains("warum ") && !m.Contains("was ") && !m.Contains("wieso ") && !m.Contains("weshalb "))
                {
                    long sum = 0;
                    for (int i = 0; i < m.Length; i++)
                    {
                        sum += m.ToCharArray()[i] << i;
                    }

                    int answerIndex = Math.Abs((int)(sum % answers.Length));
                    DiscordNETWrapper.SendText(commandmessage.Content.Split(' ').First().Remove(0, Program.Prefix.Length) + " says: " + answers[answerIndex], commandmessage.Channel).Wait();
                }
                else
                {
                    DiscordNETWrapper.SendText("I can only answer yes no questions!", commandmessage.Channel).Wait();
                }
            }
            else
            {
                DiscordNETWrapper.SendText("Thats not a question!", commandmessage.Channel).Wait();
            }
        }
Exemple #6
0
 public void OnNonCommandMessageRecieved(IMessage message)
 {
     if (Config.Data.MessagePreviewServers.Contains(Program.GetGuildFromChannel(message.Channel).Id))
     {
         string[] split = message.Content.Split(new char[] { ' ', '\n' });
         foreach (string s in split)
         {
             if (s.StartsWith("https://discord.com/channels/") ||
                 s.StartsWith("https://discordapp.com/channels/"))
             {
                 try
                 {
                     string[] linkSplit = s.Split('/');
                     IMessage m         = (Program.GetGuildFromID(Convert.ToUInt64(linkSplit[4])).
                                           GetChannel(Convert.ToUInt64(linkSplit[5])) as ITextChannel).
                                          GetMessageAsync(Convert.ToUInt64(linkSplit[6])).Result;
                     EmbedBuilder Embed = m.ToEmbed();
                     //Embed.AddFieldDirectly("Preview for: ", s);
                     DiscordNETWrapper.SendEmbed(Embed, message.Channel).Wait();
                 }
                 catch { }
             }
         }
     }
 }
Exemple #7
0
        public override void Execute(IMessage message)
        {
            string[] split = message.Content.Split('\n');
            if (split.Length < 2)
            {
                DiscordNETWrapper.SendText($"Duuude no I need more Information, or different Information\nHave a look into my HelpMenu ({Prefix}help {CommandLine})",
                                           message.Channel).Wait();
                return;
            }
            string[] pollOptions = split[1].Split(',');
            if (pollOptions.Length > 9)
            {
                DiscordNETWrapper.SendText("Duuude thats too many answer possibilities, 9 should be enough\nIf you want more ask the Discord Devs for a 10 Emoji",
                                           message.Channel).Wait();
                return;
            }

            int          i           = 0;
            IUserMessage pollMessage = DiscordNETWrapper.SendEmbed(DiscordNETWrapper.CreateEmbedBuilder($":bar_chart: **{split[0].Remove(0, PrefixAndCommand.Length + 1)}**",
                                                                                                        pollOptions.Select(x => emotes[i++].Name + " " + x).Aggregate((x, y) => x + "\n" + y)),
                                                                   message.Channel).Result.First();

            pollMessage.AddReactionsAsync(emotes.Take(pollOptions.Length).ToArray()).Wait();

            return;
        }
        public override void Execute(IMessage message)
        {
            string[] split = message.Content.Split(new char[] { ' ', '\n' });
            if (split.Length == 1)
            {
                EmbedBuilder Embed = new EmbedBuilder();
                Embed.WithColor(0, 128, 255);
                foreach (PlaceCommand Pcommand in subCommands)
                {
                    Embed.AddFieldDirectly(Prefix + CommandLine + " " + Pcommand.command, Pcommand.desc);
                }
                Embed.WithDescription("Place Commands:");
                DiscordNETWrapper.SendEmbed(Embed, message.Channel).Wait();

                DiscordNETWrapper.SendFile(filePath, message.Channel).Wait();
            }
            else
            {
                foreach (PlaceCommand Pcommand in subCommands)
                {
                    if (split[1] == Pcommand.command && Pcommand.check(split, message.Channel))
                    {
                        Pcommand.execute(message, filePath, split);
                        break;
                    }
                }
            }
        }
Exemple #9
0
 public override void Execute(IMessage message)
 {
     string[] split = message.Content.Split(new char[] { ' ', '\n' });
     if (split.Length == 1)
     {
         EmbedBuilder Embed = new EmbedBuilder();
         Embed.WithColor(0, 128, 255);
         foreach (Reaction react in reactions)
         {
             Embed.AddFieldDirectly(Prefix + CommandLine + " " + react.name, react.desc);
         }
         Embed.WithDescription("Reactions:");
         DiscordNETWrapper.SendEmbed(Embed, message.Channel).Wait();
     }
     else
     {
         string command = split.Skip(1).Aggregate((x, y) => x + " " + y).ToLower();
         int[]  scores  = new int[reactions.Length];
         for (int i = 0; i < reactions.Length; i++)
         {
             scores[i] = command.LevenshteinDistance(reactions[i].name.ToLower());
         }
         int index = Array.IndexOf(scores, scores.Min());
         reactions[index].execute(message);
     }
 }
Exemple #10
0
        public override void Execute(IMessage message)
        {
            SocketGuild g = Program.GetGuildFromChannel(message.Channel);

            EmbedBuilder info = new EmbedBuilder();

            info.WithDescription("Server-Information");

            info.AddFieldDirectly("Channels", g.Channels.Count, true);
            info.AddFieldDirectly("Category Channels", g.CategoryChannels.Count, true);
            info.AddFieldDirectly("Text Channels", g.TextChannels.Count, true);
            info.AddFieldDirectly("Voice Channels", g.VoiceChannels.Count, true);

            info.AddFieldDirectly("Owner", g.Owner.GetDisplayName(), true);
            info.AddFieldDirectly("Created At", g.CreatedAt, true);

            info.AddFieldDirectly("Member Count", g.MemberCount, true);
            info.AddFieldDirectly("Human Count", g.Users.Where(x => !x.IsBot).Count(), true);
            info.AddFieldDirectly("Bot Count", g.Users.Where(x => x.IsBot).Count(), true);

            info.AddFieldDirectly("Emotes", g.Emotes.Count, true);
            info.AddFieldDirectly("Features", g.Features.Value, true);
            info.AddFieldDirectly("Mfa Level", g.MfaLevel, true);
            info.AddFieldDirectly("Icon Url", g.IconUrl, true);
            if (g.SplashUrl != null)
            {
                info.AddFieldDirectly("Splash Url", g.SplashUrl, true);
            }

            info.AddFieldDirectly("Roles:", g.Roles.OrderByDescending(x => x.Position).
                                  Select(x => $"[{x.Members.Count()}]{x.Name.Replace("*", "\\*")}").Aggregate((x, y) => x + "\n" + y), true);

            info.AddFieldDirectly("Verification Level", g.VerificationLevel, true);
            info.AddFieldDirectly("Voice Region Id", g.VoiceRegionId, true);

            info.AddFieldDirectly("User with the most roles:", $"{g.Users.MaxElement(x => x.Roles.Count, out double max)} with {max} Roles" +
                                  (g.Users.Where(x => x.Roles.Count == max).Count() > 1 ?
                                   $"\nbut they share thier first place with: {g.Users.Where(x => x.Roles.Count == max).Skip(1).Select(x => x.GetDisplayName()).Combine(", ")}" :
                                   ""), true);
            info.AddFieldDirectly("User with the longest name:", $"{g.Users.MaxElement(x => x.GetDisplayName().Length, out max)}" +
                                  (g.Users.Where(x => x.GetDisplayName().Length == max).Count() > 1 ?
                                   $"\nbut they share thier first place with: {g.Users.Where(x => x.GetDisplayName().Length == max).Skip(1).Select(x => x.ToString()).Combine(", ")}" :
                                   ""), true);

            try
            {
                // TODO: Many activities many confoos
                info.AddFieldDirectly("Played Games: ", (from user in g.Users
                                                         where user.Activities.Count > 0 && user.Activities.First().Type == ActivityType.Playing
                                                         group user by user.Activities.First().Name into x
                                                         select $"[{x.Count()}]{x.Key}").
                                      Aggregate((x, y) => x + "\n" + y), true);
            }
            catch { }

            DiscordNETWrapper.SendEmbed(info, message.Channel).Wait();

            return;
        }
Exemple #11
0
        private void Program_OnConnected()
        {
            PingEmote   = Emote.Parse("<a:ping:703994951377092661>");
            CancelEmote = new Emoji("❌");

            // Big boi loopi loop
            Task.Factory.StartNew(() =>
            {
                Thread.CurrentThread.Name = "Timer Thread";
                string getTimer(TimeSpan t) => $"{t.Days} Days, {t.Hours} Hours, {t.Minutes} Minutes, {t.Seconds} Seconds";

                while (true)
                {
                    for (int i = 0; i < Config.Data.timers.Count; i++)
                    {
                        var timer = Config.Data.timers[i];

                        try
                        {
                            var eventMessage = (IUserMessage)(Program.GetChannelFromID(timer.ChannelId) as IMessageChannel).GetMessageAsync(timer.MessageId).Result;

                            if (DateTime.Now < timer.EventTime)
                            {
                                eventMessage.ModifyAsync(m => m.Content = $"```fix\n{timer.EventName} in {getTimer(timer.EventTime - DateTime.Now)}```");
                            }
                            else
                            {
                                eventMessage.ModifyAsync(m => m.Content = $"```fix\n{timer.EventName} happened at {timer.EventTime}```");
                                var pingUsers   = eventMessage.GetReactionUsersAsync(PingEmote, 100).FlattenAsync().Result;
                                string mentions = pingUsers.
                                                  Where(x => !x.IsBot && x.Id != timer.AuthorId).
                                                  Append(Program.GetUserFromId(timer.AuthorId)).
                                                  Select(x => x.Mention).Combine(" ");
                                if (pingUsers.Where(x => !x.IsBot).Count() > 0)
                                {
                                    DiscordNETWrapper.SendText($"{mentions} {eventMessage.GetJumpUrl()}", eventMessage.Channel).Wait();
                                }

                                Config.Data.timers.RemoveAt(i);
                                i--;
                            }

                            Thread.Sleep(1000);
                        }
                        catch
                        {
                            if (DateTime.Now > timer.EventTime)
                            {
                                Config.Data.timers.RemoveAt(i--);
                            }

                            Thread.Sleep(1000);
                        }
                    }

                    Thread.Sleep(200);
                }
            });
        }
Exemple #12
0
 public override void Execute(IMessage message)
 {
     if (message.Author.Id == Program.Master.Id)
     {
         DiscordNETWrapper.SendText("Closing...", message.Channel).Wait();
         Program.Exit(0);
     }
 }
Exemple #13
0
        public void SendBoard(IMessage message)
        {
            ChessBoard Board = Boards.Find(x => x.PlayerBottom.UserID == message.Author.Id ||
                                           x.PlayerTop.UserID == message.Author.Id);

            DiscordNETWrapper.SendBitmap(ChessBoardToPicture(Board), message.Channel, $"<@{Board.PlayerWhite.UserID}>(White) " +
                                         $"vs. <@{Board.PlayerBlack.UserID}>(Black)\nCurrently its the {(Board.PlayerWhoHasTheMove() == Board.PlayerWhite ? "White" : "Black")} " +
                                         $"players turn").Wait();
        }
Exemple #14
0
        public override void Execute(IMessage message)
        {
            lock (this)
            {
                try
                {
                    string[] lines = message.Content.Split('\n');
                    for (int i = 0; i < lines.Length; i++)
                    {
                        string[] words = lines[i].Split(' ');
                        foreach (string word in words)
                        {
                            if (word.ContainsOneOf(new string[] { "write", "read", "append", "File", "Handle", "System.", "unsafe", "Windows",
                                                                  "windows", "TCP", "Socket", "socket", "Network.", "Process.", "Compiler.", "Debug.", "Distribution.",
                                                                  "Foreign.", "GHC.", "Trace.", "Type.", "Marshal", ":!" }) || word.Length > 1 && word[0] == ':' && char.IsLetter(word[1]))
                            {
                                DiscordNETWrapper.SendText("Your code contains commands you don't have permission to use!\nAt: " + word + " in line " + i, message.Channel).Wait();
                                return;
                            }
                        }
                    }

                    string haskellInput = message.Content.Remove(0, 5).Trim(' ').Trim('`');
                    if (haskellInput.StartsWith("haskell"))
                    {
                        haskellInput = haskellInput.Remove(0, "haskell".Length);
                    }
                    if (!haskellInput.Contains("main = "))
                    {
                        haskellInput = "main = " + haskellInput;
                    }
                    File.WriteAllText(inputPath, haskellInput);

                    $"runhaskell {inputPath}".RunAsConsoleCommand(3, () => {
                        DiscordNETWrapper.SendText("Haskell timeout!", message.Channel).Wait();
                    }, (s, e) => {
                        string output = string.IsNullOrWhiteSpace(s) ? e : s;
                        output        = output.Insert(0, "```haskell\n").Insert(output.Length + "```haskell\n".Length, "```");

                        if (output.Length >= 2000)
                        {
                            DiscordNETWrapper.SendText("That output was a little too long for Discords 2000 character limit.", message.Channel).Wait();
                        }
                        else if (output.Trim('`').Trim('\n') == "haskell")
                        {
                            DiscordNETWrapper.SendText("Your code didn't create any output!", message.Channel).Wait();
                        }
                        else
                        {
                            DiscordNETWrapper.SendText(output, message.Channel).Wait();
                        }
                    });
                }
                catch (Exception e) { ConsoleWrapper.ConsoleWriteLine(e, ConsoleColor.Red); }
            }
        }
 public override void Execute(IMessage message)
 {
     lock (this)
     {
         Game newgame = new Game();
         newgame.Message = DiscordNETWrapper.SendText(newgame.TextRenderImage(), message.Channel).Result.First();
         newgame.Message.AddReactionsAsync(new IEmote[] { left, up, down, right }).Wait();
         games.Add(newgame);
     }
 }
        public DBGuild GetGuild(IMessage message)
        {
            var curGuild = Program.GetGuildFromChannel(message.Channel);

            if (!File.Exists(GetFilePath(curGuild)))
            {
                DiscordNETWrapper.SendText("I don't have data saved for this server yet :/", message.Channel).Wait();
                return(null);
            }
            return(ParseJson(File.ReadAllText(GetFilePath(curGuild))));
        }
        public override void Execute(IMessage message)
        {
            var code    = message.Content.Split(" ").Skip(1).Combine(" ").Trim('`');
            var handler = new HttpClientHandler
            {
                AutomaticDecompression = ~DecompressionMethods.All
            };

            using var httpClient = new HttpClient(handler);
            using var request    = new HttpRequestMessage(new HttpMethod("POST"), "https://dotnetfiddle.net/Home/Run");

            request.Headers.TryAddWithoutValidation("authority", "dotnetfiddle.net");
            request.Headers.TryAddWithoutValidation("accept", "application/json, text/javascript, */*; q=0.01");
            request.Headers.TryAddWithoutValidation("x-requested-with", "XMLHttpRequest");
            request.Headers.TryAddWithoutValidation("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36");
            request.Headers.TryAddWithoutValidation("origin", "https://dotnetfiddle.net");
            request.Headers.TryAddWithoutValidation("sec-fetch-site", "same-origin");
            request.Headers.TryAddWithoutValidation("sec-fetch-mode", "cors");
            request.Headers.TryAddWithoutValidation("sec-fetch-dest", "empty");
            request.Headers.TryAddWithoutValidation("referer", "https://dotnetfiddle.net/");
            request.Headers.TryAddWithoutValidation("accept-language", "de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7");
            request.Headers.TryAddWithoutValidation("cookie", "AreCookiesResetForPublicMain=true; uvts=95553ad1-9ab5-48ee-6246-9c3da9c33468; NuGetPackageVersionIds=; Language=CSharp; IsAutoRun=false; UseLocalStorage=true; Console=true; OriginalFiddleId=CsScript; ProjectType=Script");
            request.Headers.TryAddWithoutValidation("content-type", "application/json; charset=UTF-8");

            var codeBlock = HttpUtility.HtmlEncode(code);

            if (!codeBlock.Contains("public static void Main", StringComparison.OrdinalIgnoreCase))
            {
                if (codeBlock.Contains("Console.Write"))
                {
                    codeBlock = "using System;\\nusing System.Linq;\\nusing System.Collections.Generic;\\n\\t\\t\\t\\t\\t\\n" +
                                "public class Program\\n{\\n\\tpublic static void Main()\\n\\t{\\n\\t\\t" + codeBlock + "\\n\\t}\\n}";
                }
                else
                {
                    codeBlock = "using System;\\nusing System.Linq;\\nusing System.Collections.Generic;\\n\\t\\t\\t\\t\\t\\n" +
                                "public class Program\\n{\\n\\tpublic static void Main()\\n\\t{\n\t\tConsole.WriteLine(" + codeBlock + ");\n\t}\\n}";
                }
            }

            request.Content = new StringContent("{\"CodeBlock\":\"" + codeBlock + "\",\"OriginalCodeBlock\":\"using System;\\n\\t\\t\\t\\t\\t\\npublic class Program\\n{\\n\\tpublic static void Main()\\n\\t{\\n\\t\\tConsole.WriteLine(\\\"Hello World\\\");\\n\\t}\\n}\",\"Language\":\"CSharp\",\"Compiler\":\"Net45\",\"ProjectType\":\"Console\",\"OriginalFiddleId\":\"CsCons\",\"NuGetPackageVersionIds\":\"\",\"OriginalNuGetPackageVersionIds\":\"\",\"TimeOffset\":\"2\",\"ConsoleInputLines\":[],\"MvcViewEngine\":\"Razor\",\"MvcCodeBlock\":{\"Model\":\"\",\"View\":\"\",\"Controller\":\"\"},\"OriginalMvcCodeBlock\":{\"Model\":\"\",\"View\":\"\",\"Controller\":\"\"},\"UseResultCache\":false}");
            request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=UTF-8");

            var response     = httpClient.SendAsync(request).Result;
            var responseJson = response.Content.ReadAsStringAsync().Result;

            var json = JsonConvert.DeserializeObject <ResponseJson>(responseJson);

            DiscordNETWrapper.SendEmbed(
                DiscordNETWrapper.CreateEmbedBuilder("C# Runner Output", "", "", message.Author).
                AddFieldDirectly("StdOut", $"```{(json.ConsoleOutput.Length == 0 ? "No output was generated" : new string(json.ConsoleOutput.Take(500).ToArray()))}```").
                AddFieldDirectly("Stats", $"CompileTime: {json.Stats.CompileTime}\nCpuUsage: {json.Stats.CpuUsage}\n" +
                                 $"ExecuteTime: {json.Stats.ExecuteTime}\nMemoryUsage: {json.Stats.MemoryUsage}"), message.Channel).Wait();
        }
        public override void Execute(IMessage message)
        {
            var split = message.Content.Split(' ');

            lock (dbLock)
            {
                if (split.Length <= 1)
                {
                    DiscordNETWrapper.SendText(
                        "Hi im a database, I save data. (secretly im just a chonky json file but psssst, tell no one)\n" +
                        "If you want to build a database for the discord server you are writing this message on type `$messageDB build`, " +
                        "but only trained professionals are allowed to use that command because it takes a lot of resources to exectue it\n" +
                        $"Other commands that you can use once a database has been build are: " +
                        $"{commands.Where(x => !string.IsNullOrWhiteSpace(x.name)).Select(x => $"`{x.name}`").Combine(", ")}", message.Channel).Wait();
                    return;
                }
                else if (split[1] == "build")
                {
                    if (message.Author.Id != Program.Master.Id)
                    {
                        DiscordNETWrapper.SendText("I'm sorry Dave, I'm afraid I can't do that", message.Channel).Wait();
                        return;
                    }

                    if (!File.Exists(dbPath))
                    {
                        return;
                    }

                    var     curGuild = Program.GetGuildFromChannel(message.Channel);
                    DBGuild db       = DBFromGuild(curGuild);
                    File.WriteAllText(GetFilePath(db), CreateJson(db));

                    DiscordNETWrapper.SendText("Server db built!", message.Channel).Wait();
                }
                else
                {
                    var command = commands.FirstOrDefault(x => x.name == split[1]);
                    if (command == null)
                    {
                        return;
                    }

                    DBGuild dbGuild = null;
                    if ((dbGuild = GetGuild(message)) == null)
                    {
                        return;
                    }

                    command.doStuffLul(dbGuild, message, split.Skip(2).ToArray());
                }
            }
        }
        public IMessage LastM(EditNull n, IMessage m, int messagesToSkip = 0)
        {
            var messages = DiscordNETWrapper.EnumerateMessages(m.Channel).Skip(1 + messagesToSkip);
            var debug    = messages.Take(50);

            foreach (var lm in debug)
            {
                try { return(lm); }
                catch { }
            }
            throw new Exception("Didn't find any");
        }
Exemple #20
0
            public void PutCardOnTopOfStack(UnoCardType t, UnoColor c, ulong PlayerID, ISocketMessageChannel channel)
            {
                if (PlayerID != TurnPlayerID())
                {
                    DiscordNETWrapper.SendText("It's not your turn :thinking:", channel).Wait();
                    return;
                }
                UnoCard newCard = UnoCards.FirstOrDefault(x => (HasColor(t) ? x.Color == c : x.Color == UnoColor.none) && x.Type == t);
                Tuple <SocketUser, List <UnoCard> > player = Players.Find(x => x.Item1.Id == PlayerID);

                if (!player.Item2.Exists(x => x.Type == t && x.Color == c))
                {
                    DiscordNETWrapper.SendText("You don't even have that card :thinking:", channel).Wait();
                    return;
                }

                if (newCard != null)
                {
                    if (CanPutCardOnTopOfStack(newCard))
                    {
                        player.Item2.Remove(newCard);
                        SendDeck(player);
                        DrawCardOnStack(newCard);
                        TopStackCard = newCard;
                        CurColor     = c;
                        if (newCard.Type == UnoCardType.reverse)
                        {
                            ReversedTurns = !ReversedTurns;
                        }
                        NextPlayer();
                        if (newCard.Type == UnoCardType.skip)
                        {
                            NextPlayer();
                        }
                        if (newCard.Type == UnoCardType.plus2)
                        {
                            DrawCards(2, Players[curPlayerIndex]);
                        }
                        if (newCard.Type == UnoCardType.plus4)
                        {
                            DrawCards(4, Players[curPlayerIndex]);
                        }
                    }
                    else
                    {
                        DiscordNETWrapper.SendText("You can't put that card on top of the stack :thinking:", channel).Wait();
                    }
                }
                else
                {
                    DiscordNETWrapper.SendText("Oi that card doesn't exist!", channel).Wait();
                }
            }
Exemple #21
0
        void germanWikiNeighbor(string charLink, HtmlWeb web, IMessage message)
        {
            try
            {
                var charDoc = web.Load("https://animalcrossingwiki.de" + charLink);

                var table        = charDoc.DocumentNode.SelectSingleNode("//table[contains(@class, 'inline')]");
                var charName     = table.SelectSingleNode("//th[contains(@class, 'col0 centeralign')]").InnerText.Trim(' ');
                var tableEntries = table.ChildNodes.Where(x => x.Name == "tr");
                var charImg      = "https://animalcrossingwiki.de" + tableEntries.First().
                                   ChildNodes.ElementAt(1).
                                   ChildNodes.ElementAt(1).
                                   GetAttributeValue("src", "");
                if (charImg.Contains("?"))
                {
                    charImg = charImg.GetEverythingBetween("", "?");
                }
                var tierart     = tableEntries.ElementAt(1).ChildNodes.ElementAt(2).InnerText.Trim(' ');
                var personality = tableEntries.ElementAt(2).ChildNodes.ElementAt(2).InnerText.Trim(' ');
                var gender      = tableEntries.ElementAt(3).ChildNodes.ElementAt(2).InnerText.Trim(' ');
                var birthday    = tableEntries.ElementAt(4).ChildNodes.ElementAt(2).InnerText.Trim(' ');
                var floskel     = tableEntries.ElementAt(5).ChildNodes.ElementAt(2).InnerText.Trim(' ');
                var fotospruch  = tableEntries.ElementAt(6).ChildNodes.ElementAt(2).InnerText.Trim(' ');
                var auftreten   = tableEntries.ElementAt(7).ChildNodes.ElementAt(2).InnerText.Trim(' ').Split('\n').Combine(", ");

                var    otherNamesTitle = charDoc.GetElementbyId("name-in-anderen-sprachen");
                var    namesTable      = otherNamesTitle.NextSibling.NextSibling.ChildNodes.ElementAt(1).FirstChild;
                var    nameEntries     = namesTable.ChildNodes.Where(x => x.Name == "tr");
                string names           = nameEntries.Select(x => x.ChildNodes.ElementAt(1).InnerText + " - " + x.ChildNodes.ElementAt(2).InnerText).Combine("\n");
                names = names.Replace("Englisch", ":flag_gb: Englisch").
                        Replace("Japanisch", ":flag_jp: Japanisch").
                        Replace("Spanisch", ":flag_es: Spanisch").
                        Replace("Französisch", ":flag_fr: Französisch").
                        Replace("Italienisch", ":flag_it: Italienisch");

                DiscordNETWrapper.SendEmbed(DiscordNETWrapper.
                                            CreateEmbedBuilder(charName, $"[page link]({"https://animalcrossingwiki.de" + charLink})\n\n{names}", charImg, null, "").
                                            AddFieldDirectly("Tierart", HttpUtility.HtmlDecode(tierart), true).
                                            AddFieldDirectly("Persönlichkeit", HttpUtility.HtmlDecode(personality), true).
                                            AddFieldDirectly("Geschlecht", HttpUtility.HtmlDecode(gender), true).
                                            AddFieldDirectly("Geburtstag", HttpUtility.HtmlDecode(birthday), true).
                                            AddFieldDirectly("Floskel", HttpUtility.HtmlDecode(floskel), true).
                                            AddFieldDirectly("Fotospruch", HttpUtility.HtmlDecode(fotospruch), true).
                                            AddFieldDirectly("Auftreten", HttpUtility.HtmlDecode(auftreten), true),
                                            message.Channel).Wait();
            }
            catch
            {
                DiscordNETWrapper.SendText("Error parsing the villager page", message.Channel).Wait();
                return;
            }
        }
Exemple #22
0
        public Timer() : base("timer", "Posts a updating message for some event", isExperimental: false, isHidden: false)
        {
            Program.OnConnected          += Program_OnConnected;
            Program.OnEmojiReactionAdded += Program_OnEmojiReactionAdded;
            Program.OnMessageDeleted     += Program_OnMessageDeleted;

            HelpMenu = DiscordNETWrapper.CreateEmbedBuilder("Timer",
                                                            "Usage example: \n" +
                                                            "\"$timer in 02:59:00 ;pokemon\"\n" +
                                                            "\"$timer at 04:20:00 blaze it\"\n\n" +
                                                            $"Note that the bot currently runs in the `{TimeZoneInfo.Local.StandardName}` time zone (GMT/UTC offset {TimeZoneInfo.Local.GetUtcOffset(DateTime.Now)})" +
                                                            $"when adding total times using the `at` keyword");
        }
Exemple #23
0
        public override void Execute(IMessage message)
        {
            lock (this)
            {
                string latex = message.Content.Split(new char[] { ' ', '\n' }).Skip(1).Aggregate((x, y) => x + " " + y);

                if (!latex.StartsWith("\\documentclass"))
                {
                    latex = "\\documentclass[preview,border=12pt]{standalone}\n\\usepackage{amsmath}\n\\usepackage{tikz}\n\\begin{document}\n" + latex + "\\end{document}";
                }

                if (!File.Exists(inputPath))
                {
                    File.Create(inputPath).Dispose();
                }
                File.WriteAllText(inputPath, latex);

                batchPath.RunAsConsoleCommand(3, () => { }, (s, e) => { }, (StreamWriter s) => {
                    Thread.Sleep(500);
                    s.WriteLine("return");
                });

                string[] outputFilePaths = Directory.GetFiles(folderPath).Where(x => Path.GetFileNameWithoutExtension(x).Contains("output") && x.EndsWith(".png")).ToArray();

                if (outputFilePaths.Length == 0)
                {
                    DiscordNETWrapper.SendText("That didn't work.", message.Channel).Wait();
                    return;
                }

                foreach (string outputPath in outputFilePaths)
                {
                    Bitmap output = null;
                    using (Bitmap latexOutput = new Bitmap(outputPath))
                    {
                        output = new Bitmap(latexOutput.Width, latexOutput.Height);
                        using (Graphics graphics = Graphics.FromImage(output))
                        {
                            graphics.FillRectangle(Brushes.White, new Rectangle(0, 0, latexOutput.Width, latexOutput.Height));
                            graphics.DrawImage(latexOutput, new Point(0, 0));
                        }
                    }
                    DiscordNETWrapper.SendBitmap(output, message.Channel).Wait();
                    output.Dispose();
                }

                outputFilePaths.Select(x => { File.Delete(x); return(x); }).ToArray();
            }

            return;
        }
        public override void Execute(IMessage message)
        {
            string[] split = message.Content.Split(new char[] { ' ', '\n' });

            try
            {
                string output = MarkovHelper.GetString(split.Length > 1 ? split.Skip(1).Aggregate((x, y) => { return(x + " " + y); }) : "", 5, 2000);
                DiscordNETWrapper.SendText(output, message.Channel).Wait();
            }
            catch (NoEmptyElementException)
            {
                DiscordNETWrapper.SendText("Markow isn't ready yet!", message.Channel).Wait();
            }
        }
        public string LastT(EditNull n, IMessage m, int messagesToSkip = 0)
        {
            var messages = DiscordNETWrapper.EnumerateMessages(m.Channel).Skip(1 + messagesToSkip);

            foreach (var lm in messages)
            {
                if (!string.IsNullOrWhiteSpace(lm.Content))
                {
                    try { return(lm.Content); }
                    catch { }
                }
            }
            throw new Exception("Didn't find any");
        }
        public Gif LastG(EditNull n, IMessage m, int messagesToSkip = 0)
        {
            var messages = DiscordNETWrapper.EnumerateMessages(m.Channel).Skip(1 + messagesToSkip);

            foreach (var lm in messages)
            {
                try
                {
                    return(GetPictureLinkFromMessage(lm, "").GetBitmapsAndTimingsFromGIFURL());
                }
                catch { }
            }
            throw new Exception("Didn't find any");
        }
        public Csharp() : base("c#", "Run csharp code", isExperimental: false, isHidden: true)
        {
            HelpMenu = DiscordNETWrapper.CreateEmbedBuilder("C# Help",
                                                            "You can either post a C# expression, content for a Main() method or a whole program with one class having a Main() Function.\n" +
                                                            "System, System.Linq and System.Collections.Generic are imported by default").
                       AddFieldDirectly("Program Template:", @"```
public class Program
{
	public static void Main()
	{
		Console.WriteLine(""Hello World"");
    }
}```");
        }
Exemple #28
0
        public override void Execute(IMessage message)
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            var gameMode = GetGamemodeJson("https://overwatcharcade.today/api/overwatch/arcademodes".GetHTMLfromURL());
            var today    = GetTodayJson("https://overwatcharcade.today/api/overwatch/today".GetHTMLfromURL());

            DiscordNETWrapper.SendText($"Updated at {today.CreatedAt.UtcDateTime.ToLongDateString()}, " +
                                       $"{today.CreatedAt.UtcDateTime.ToShortTimeString()} by {today.User.Battletag}", message.Channel).Wait();
            foreach (Tile t in today.Modes.Tiles())
            {
                DiscordNETWrapper.SendEmbed(DiscordNETWrapper.CreateEmbedBuilder(t.Name, t.Label == null ? t.Players : $"{t.Players} - {t.Label}",
                                                                                 "", null, gameMode.FirstOrDefault(x => x.Id == t.Id)?.Image), message.Channel).Wait();
            }
        }
Exemple #29
0
        public override async void Execute(IMessage message)
        {
            if (!message.Content.Contains(" "))
            {
                DiscordNETWrapper.SendEmbed(HelpMenu, message.Channel).Wait();
                return;
            }

            SocketGuild         g       = Program.GetGuildFromChannel(message.Channel);
            ISocketAudioChannel channel = g.VoiceChannels.FirstOrDefault(x => x.Users.Select(y => y.Id).Contains(message.Author.Id));

            string videoURL = message.Content.Split(' ')[1];

            if (!videoURL.StartsWith("https://www.youtube.com/watch?"))
            {
                DiscordNETWrapper.SendText("That doesn't look like a youtube video link :thinking:", message.Channel).Wait();
                return;
            }

            if (channel != null)
            {
                try { channel.DisconnectAsync().Wait(); } catch { }

                IAudioClient client = await channel.ConnectAsync();

                using (Process P = MultiMediaHelper.GetAudioStreamFromYouTubeVideo(videoURL, "mp3"))
                    using (MemoryStream mem = new MemoryStream())
                    {
                        while (true)
                        {
                            Task.Delay(1001).Wait();
                            if (string.IsNullOrWhiteSpace(P.StandardError.ReadLine()))
                            {
                                break;
                            }
                        }
                        P.StandardOutput.BaseStream.CopyTo(mem);
                        using (WaveStream naudioStream = WaveFormatConversionStream.CreatePcmStream(new StreamMediaFoundationReader(mem)))
                            MultiMediaHelper.SendAudioAsync(client, naudioStream).Wait();
                    }

                try { channel.DisconnectAsync().Wait(); } catch { }
            }
            else
            {
                DiscordNETWrapper.SendText("You are not in an AudioChannel on this server!", message.Channel).Wait();
                return;
            }
        }
        public override void Execute(IMessage message)
        {
            if (message.Author.Id == Program.Master.Id)
            {
                Rectangle AllScreenBounds = new Rectangle(-1360, 0, 1360 + 1600, 900);

                using (Bitmap bmp = new Bitmap(AllScreenBounds.Width, AllScreenBounds.Height, PixelFormat.Format32bppArgb))
                {
                    using (Graphics graphics = Graphics.FromImage(bmp))
                        graphics.CopyFromScreen(AllScreenBounds.X, AllScreenBounds.Y, 0, 0, new Size(AllScreenBounds.Width, AllScreenBounds.Height), CopyPixelOperation.SourceCopy);

                    DiscordNETWrapper.SendBitmap(bmp, message.Channel).Wait();
                }
            }
        }