Esempio n. 1
0
        public static void Main(string[] args)
        {
            YugiohPricesSearcher searcher = new YugiohPricesSearcher();

            ///Invalid card
            Console.WriteLine("--Testing with invalid card--");
            try
            {
                var result = searcher.GetCardByName("m8").Result;
                Console.WriteLine($"{result.Name}. {result.Description}");
            }
            catch (AggregateException ex)
            {
                ex.Handle((x) =>
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Exception: " + x.Message);
                    Console.ForegroundColor = ConsoleColor.White;
                    return(true);
                });
            }

            Console.WriteLine("\n--Testing with valid card--");
            try
            {
                var result = searcher.GetCardByName("Dark Magician").Result;
                Console.WriteLine($"{result.Name}. {result.Description}");
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Exception: " + ex.Message);
                Console.ForegroundColor = ConsoleColor.White;
            }

            Console.WriteLine("\n\nPress enter to exit..");
            Console.ReadLine();
        }
Esempio n. 2
0
        public override void Install(CommandsManager manager)
        {
            manager.AddCommand(new CommandStub("ygo", "Retrieves information for a Yu-Gi-Oh card from the YugiohPrices database.",
                                               "Card names are (unfortunately) case sensitive.\n\n**Valid:** Dark Magician\n**Invalid: **dark magician", PermissionType.User, 1, cmdArgs =>
            {
                if (cmdArgs.Args.Count > 0)
                {
                    YugiohPricesSearcher searcher = new YugiohPricesSearcher();
                    try
                    {
                        cmdArgs.Channel.SimulateTyping();
                        var card = searcher.GetCardByName(cmdArgs.Args[0]).Result;
                        if (card.Name != "<NULL CARD>")
                        {
                            card.CardImage.Save("ygotemp.png");
                            string message = $"**{card.Name}**";
                            if (card.Type == CardType.Monster)
                            {
                                message += $" Level: {card.Level} Attribute: {card.Attribute}\n";
                            }
                            else
                            {
                                message += "\n";
                            }
                            message += $"**Description:** {card.Description}";
                            if (card.Type == CardType.Monster)
                            {
                                message += $"\n**Type:** {card.MonsterType}\n**ATK/DEF:** {card.Attack}/{card.Defense}";
                            }

                            manager.Client.AttachFile(cmdArgs.Channel, message, "ygotemp.png");
                        }
                        else
                        {
                            cmdArgs.Channel.SendMessage("Couldn't find that specified card!");
                        }
                    }
                    catch (AggregateException ex)
                    {
                        ex.Handle((x) =>
                        {
                            cmdArgs.Channel.SendMessage("Couldn't find that specified card! (" + x.Message + ")");
                            return(true);
                        });
                    }
                }
            }), this);
        }
Esempio n. 3
0
        private void SetupCommands()
        {
            #region Owner only
            CommandsManager.AddCommand(new CommandStub("selfdestruct", "Shuts the bot down.", "", PermissionType.Owner, cmdArgs =>
            {
                Exit();
            }));
            CommandsManager.AddCommand(new CommandStub("joinvoice", "Joins a specified voice channel", "Arg is case insensitive voice channel name to join.", PermissionType.Owner, 1, cmdArgs =>
            {
                DiscordChannel channelToJoin = cmdArgs.Channel.parent.channels.Find(x => x.Name.ToLower() == cmdArgs.Args[0].ToLower() && x.Type == ChannelType.Voice);
                if (channelToJoin != null)
                {
                    DiscordVoiceConfig config = new DiscordVoiceConfig
                    {
                        FrameLengthMs = 20,
                        Channels      = 1,
                        OpusMode      = Discord.Audio.Opus.OpusApplication.LowLatency,
                        SendOnly      = true
                    };

                    waveFormat = new WaveFormat(48000, 16, config.Channels);

                    if (!config.SendOnly)
                    {
                        waveCallbackInfo = WaveCallbackInfo.FunctionCallback();
                        outputDevice     = new WaveOut();
                    }

                    client.ConnectToVoiceChannel(channelToJoin, config);
                }
                else
                {
                    cmdArgs.Channel.SendMessage("Couldn't find the specified channel as a voice channel!");
                }
            }));
            CommandsManager.AddCommand(new CommandStub("disconnect", "Disconnects from voice", "", PermissionType.Owner, 1, cmdArgs =>
            {
                client.DisconnectFromVoice();
            }));
            CommandsManager.AddCommand(new CommandStub("testvoice", "Broadcasts specified file over voice.", "", PermissionType.Owner, 1, cmdArgs =>
            {
                if (File.Exists(cmdArgs.Args[0]))
                {
                    if (client.ConnectedToVoice())
                    {
                        SendVoice(cmdArgs.Args[0]);
                    }
                    else
                    {
                        cmdArgs.Channel.SendMessage("Not connected to voice!");
                    }
                }
                else
                {
                    cmdArgs.Channel.SendMessage("Couldn't broadcast specified file! It doesn't exist!");
                }
            }));
            CommandsManager.AddCommand(new CommandStub("statusof", "`Status` test", "", PermissionType.Owner, 1, cmdArgs =>
            {
                string id = cmdArgs.Args[0].Trim(new char[] { '<', '@', '>' });
                if (!string.IsNullOrEmpty(id))
                {
                    DiscordMember member = cmdArgs.Channel.parent.members.Find(x => x.ID == id);
                    if (member != null)
                    {
                        string msg = $"Status of `{member.Username}`\n{member.Status}";
                        if (!string.IsNullOrEmpty(member.CurrentGame))
                        {
                            msg += $"\nPlaying: *{member.CurrentGame}*";
                        }
                        cmdArgs.Channel.SendMessage(msg);
                    }
                }
            }));
            CommandsManager.AddCommand(new CommandStub("changepic", "Changes the bot's guild pic test.", "Test", PermissionType.Owner, 1, cmdArgs =>
            {
                Regex linkParser = new Regex(@"\b(?:https?://|www\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                string rawString = $"{cmdArgs.Args[0]}";
                if (linkParser.Matches(rawString).Count > 0)
                {
                    string url = linkParser.Matches(rawString)[0].ToString();
                    using (WebClient wc = new WebClient())
                    {
                        byte[] data = wc.DownloadData(url);
                        using (MemoryStream mem = new MemoryStream(data))
                        {
                            using (var image = System.Drawing.Image.FromStream(mem))
                            {
                                client.ChangeClientAvatar(new Bitmap(image));
                            }
                        }
                    }
                }
            }));
            CommandsManager.AddCommand(new CommandStub("sendchanneltest", "`Client.SendMessageToChannel` Test", "", PermissionType.Owner, cmdArgs =>
            {
                client.SendMessageToChannel("Works!", cmdArgs.Channel);
            }));
            CommandsManager.AddCommand(new CommandStub("setplaying", "Sets the current game the bot is playing.", "", PermissionType.Owner, 1, cmdArgs =>
            {
                client.UpdateCurrentGame(cmdArgs.Args[0]);
            }));
            CommandsManager.AddCommand(new CommandStub("join", "Joins a specified server", "", PermissionType.Owner, 1, cmdArgs =>
            {
                string substring = cmdArgs.Args[0].Substring(cmdArgs.Args[0].LastIndexOf('/') + 1);
                client.AcceptInvite(substring);
            }));
            CommandsManager.AddCommand(new CommandStub("changeprefix", "Changes the command prefix to a specified character.", "", PermissionType.Owner, 1, cmdArgs =>
            {
                if (cmdArgs.Args.Count > 0)
                {
                    char newPrefix       = cmdArgs.Args[0][0];
                    config.CommandPrefix = newPrefix;
                    cmdArgs.Channel.SendMessage($"Command prefix changed to **{config.CommandPrefix}** successfully!");
                }
                else
                {
                    cmdArgs.Channel.SendMessage("What prefix?");
                }
            }));
            CommandsManager.AddCommand(new CommandStub("giveperm", "Gives the perm to the specified user (bot scope)", "", PermissionType.Owner, 2, e =>
            {
                //giveperm Admin <@2309208509852>
                if (e.Args.Count > 1)
                {
                    string permString   = e.Args[0];
                    PermissionType type = PermissionType.User;
                    switch (permString.ToLower())
                    {
                    case "admin":
                        type = PermissionType.Admin;
                        break;

                    case "mod":
                        type = PermissionType.Mod;
                        break;

                    case "none":
                        type = PermissionType.None;
                        break;

                    case "user":
                        type = PermissionType.User;
                        break;
                    }
                    string id = e.Args[1].Trim(new char[] { '<', '@', '>' });
                    CommandsManager.AddPermission(id, type);
                    e.Channel.SendMessage($"Given permission {type.ToString().Substring(type.ToString().IndexOf('.') + 1)} to <@{id}>!");
                }
            }));
            CommandsManager.AddCommand(new CommandStub("prune", "Prune test", "", PermissionType.Owner, 1, cmdArgs =>
            {
                int messageCount = 0;
                if (int.TryParse(cmdArgs.Args[0], out messageCount))
                {
                    var messagesToPrune = client.GetMessageHistory(cmdArgs.Channel, messageCount);
                    foreach (var msg in messagesToPrune)
                    {
                        client.DeleteMessage(msg);
                        Thread.Sleep(100);
                    }
                    cmdArgs.Channel.SendMessage($"Attempted pruning of {messageCount} messages.");
                }
            }));
            #endregion
            #region Admin
            CommandsManager.AddCommand(new CommandStub("eval", "Evaluates real-time C# code. Be careful with this",
                                                       "Evaluates C# code that is dynamically compiled.\n\nThe following namespaces are available for use:\n * DiscordSharp\n * System.Threading\n * DiscordSharp.Objects\n\n\nMake sure your function returns a string value.\nYou can reference the DiscordSharp client by using `discordClient`.", PermissionType.Admin, 1, e =>
            {
                string whatToEval = e.Args[0];
                if (whatToEval.StartsWith("`") && whatToEval.EndsWith("`"))
                {
                    whatToEval = whatToEval.Trim('`');
                }
                try
                {
                    var eval   = EvalProvider.CreateEvalMethod <DiscordClient, string>(whatToEval, new string[] { "DiscordSharp", "System.Threading", "DiscordSharp.Objects" }, new string[] { "DiscordSharp.dll" });
                    string res = "";
                    Thread.Sleep(1000);
                    Thread executionThread = null;
                    Task evalTask          = new Task(() =>
                    {
                        executionThread = Thread.CurrentThread;
                        if (eval != null)
                        {
                            res = eval(client);
                        }
                        else
                        {
                            string errors = "Errors While Compiling: \n";
                            if (EvalProvider.errors != null)
                            {
                                if (EvalProvider.errors.Count > 0)
                                {
                                    foreach (var error in EvalProvider.errors)
                                    {
                                        errors += $"{error.ToString()}\n\n";
                                    }
                                }
                                e.Channel.SendMessage($"```\n{errors}\n```");
                            }
                            else
                            {
                                e.Channel.SendMessage("Errors!");
                            }
                        }
                    });
                    evalTask.Start();
                    evalTask.Wait(10 * 1000);
                    if (executionThread != null)
                    {
                        executionThread.Abort();
                    }
                    if (res == null || res == "")
                    {
                        e.Channel.SendMessage("Terminated after 10 second timeout.");
                    }
                    else
                    {
                        e.Channel.SendMessage($"**Result**\n```\n{res}\n```");
                    }
                }
                catch (Exception ex)
                {
                    string errors = "Errors While Compiling: \n";
                    if (EvalProvider.errors != null)
                    {
                        if (EvalProvider.errors.Count > 0)
                        {
                            foreach (var error in EvalProvider.errors)
                            {
                                errors += $"{error.ToString()}\n\n";
                            }
                        }
                        else
                        {
                            errors += ex.Message;
                        }
                        e.Channel.SendMessage($"```\n{errors}\n```");
                    }
                    else
                    {
                        e.Channel.SendMessage("Errors!");
                    }
                }
            }));
            #endregion
            #region Anyone, but limited to server mods
            CommandsManager.AddCommand(new CommandStub("gtfo", "Makes the bot leave the server", "", PermissionType.User, cmdArgs =>
            {
                bool canExecute = false;
                foreach (var roll in cmdArgs.Author.Roles)
                {
                    if (roll.permissions.HasPermission(DiscordSpecialPermissions.ManageServer))
                    {
                        canExecute = true;
                    }
                }
                if (canExecute)
                {
                    client.LeaveServer(cmdArgs.Channel.parent);
                }
                else
                {
                    cmdArgs.Channel.SendMessage("You don't have the proper permissions to do this! You need the ManagerServer permission.");
                }
            }));
            #endregion
            #region Literally anyone
            CommandsManager.AddCommand(new CommandStub("cmdinfo", "Displays help for a command.", "Help", PermissionType.User, 2, e =>
            {
                if (!String.IsNullOrEmpty(e.Args[0]))
                {
                    ICommand stub = CommandsManager.Commands.Find(x => x.CommandName == e.Args[0]);
                    if (stub != null)
                    {
                        string msg = "**Help for " + stub.CommandName + "**";
                        msg       += $"\n{stub.Description}";
                        if (!String.IsNullOrEmpty(stub.HelpTag))
                        {
                            msg += $"\n\n{stub.HelpTag}";
                        }
                        e.Channel.SendMessage(msg);
                    }
                    else
                    {
                        e.Channel.SendMessage("What command?");
                    }
                }
                else
                {
                    e.Channel.SendMessage("What command?");
                }
            }));
            CommandsManager.AddCommand(new CommandStub("about", "Shows bot information", "", cmdArgs =>
            {
                string message = "**About Luigibot**\n";
                message       += "Owner: " + owner.Username + "\n";
                message       += $"Library: DiscordSharp {typeof(DiscordClient).Assembly.GetName().Version.ToString()}\n";
                var uptime     = (DateTime.Now - loginDate);
                message       += $"Uptime: {uptime.Days} days, {uptime.Hours} hours, {uptime.Minutes} minutes.\n";
                message       += "Runtime: ";

                if (runningOnMono)
                {
                    message += "Mono\n";
                }
                else
                {
                    message += ".Net\n";
                }

                message      += $"OS: {osString}\n";
                long memUsage = GetMemoryUsage();
                if (memUsage > 0)
                {
                    message += "Memory Usage: " + (memUsage / 1024) / 2 + "mb\n";
                }
                message += "Commands: " + CommandsManager.Commands.Count + "\n";
                message += "Command Prefix: " + config.CommandPrefix + "\n";
                message += "Total Servers: " + client.GetServersList().Count + "\n";
                cmdArgs.Channel.SendMessage(message);
            }));
            CommandsManager.AddCommand(new CommandStub("ygo", "Retrieves information for a Yu-Gi-Oh card from the YugiohPrices database.",
                                                       "Card names are (unfortunately) case sensitive.\n\n**Valid:** Dark Magician\n**Invalid: **dark magician", PermissionType.User, 1, cmdArgs =>
            {
                if (cmdArgs.Args.Count > 0)
                {
                    YugiohPricesSearcher searcher = new YugiohPricesSearcher();
                    try
                    {
                        var card = searcher.GetCardByName(cmdArgs.Args[0]).Result;
                        if (card.Name != "<NULL CARD>")
                        {
                            card.CardImage.Save("ygotemp.png");
                            string message = $"**{card.Name}**";
                            if (card.Type == CardType.Monster)
                            {
                                message += $" Level: {card.Level} Attribute: {card.Attribute}\n";
                            }
                            else
                            {
                                message += "\n";
                            }
                            message += $"**Description:** {card.Description}";
                            if (card.Type == CardType.Monster)
                            {
                                message += $"\n**Type:** {card.MonsterType}\n**ATK/DEF:** {card.Attack}/{card.Defense}";
                            }

                            client.AttachFile(cmdArgs.Channel, message, "ygotemp.png");
                        }
                        else
                        {
                            cmdArgs.Channel.SendMessage("Couldn't find that specified card!");
                        }
                    }
                    catch (HttpRequestException ex)
                    {
                        cmdArgs.Channel.SendMessage("Couldn't find that specified card! (" + ex.Message + ")");
                    }
                }
            }));
            CommandsManager.AddCommand(new CommandStub("khaled", "Anotha one.", "", cmdArgs =>
            {
                if (rng == null)
                {
                    Console.WriteLine("RNG null?!");
                    rng = new Random((int)DateTime.Now.Ticks);
                }
                cmdArgs.Channel.SendMessage($"***{KhaledQuotes[rng.Next(0, KhaledQuotes.Length - 1)]}***");
            }));
            #endregion
        }