当前位置: 首页>>代码示例>>C#>>正文


C# Commands.CreateCommand方法代码示例

本文整理汇总了C#中Commands.CreateCommand方法的典型用法代码示例。如果您正苦于以下问题:C# Commands.CreateCommand方法的具体用法?C# Commands.CreateCommand怎么用?C# Commands.CreateCommand使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Commands的用法示例。


在下文中一共展示了Commands.CreateCommand方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: AddCommands

 internal static void AddCommands(Commands.CommandGroupBuilder group)
 {
     group.CreateCommand("bot")
         .Alias("chatbot")
         .Parameter("on or off", Commands.ParameterType.Optional)
         .Parameter("type (clever or jabberwacky)", Commands.ParameterType.Optional)
         .MinPermissions(3)
         .Description("I'll turn on/off the chatbot for this channel.\nIf no args, I'll tell you if there's a bot on for this channel.")
         .Do(async e =>
         {
             bool botstatus = chatbots.ContainsKey(e.Channel.Id);
             if (e.Args.Count() != 0)
             {
                 bool on = e.Args[0] == "on";
                 bool off = !on && e.Args[0] == "off";
                 if (on || off)
                 {
                     if (botstatus == on || botstatus != off)
                         await Program.client.SendMessage(e.Channel, "The bot is already " + (botstatus ? "on" : "off") + $" for {e.Channel}");
                     else
                     {
                         int bottype = -1;
                         if (botstatus)
                             chatbots.Remove(e.Channel.Id);
                         else
                         {
                             bottype = GetBotType(e.Args.Count() == 1 ? "" : e.Args[0]);
                             chatbots[e.Channel.Id] = CreateBotSession((ChatterBotType)bottype);
                         }
                         await Program.client.SendMessage(e.Channel, "The bot is now " + (!botstatus ? "on" : "off") + $" for {e.Channel}");
                         SQL.ExecuteNonQuery(SQL.ExecuteScalarPos($"select count(channel) from flags where channel = '{e.Channel.Id}'")
                             ? $"update flags set chatbot={bottype} where channel='{e.Channel.Id}'"
                             : $"insert into flags values ('{e.Channel.Id}', 0, 0, 0, {bottype})");
                     }
                 }
                 else await Program.client.SendMessage(e.Channel, "First argument must be on or off.");
             }
             else await Program.client.SendMessage(e.Channel, "The bot is currently " + (botstatus ? "on" : "off") + $" for {e.Channel}.");
         });
 }
开发者ID:Lirusaito,项目名称:Nekobot,代码行数:40,代码来源:Chatbot.cs

示例2: AddCommands

        internal static void AddCommands(Commands.CommandGroupBuilder group)
        {
            CreateLewdCommand(group, "neko");
            CreateLewdCommand(group, "qt");
            CreateLewdCommand(group, "kitsune");
            CreateLewdCommand(group, "lewd");

            var imagedir = Program.config["images"].ToString();
            if (imagedir.Length == 0) imagedir = "images";
            if (System.IO.Directory.Exists(imagedir))
            {
                string[] imgexts = { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
                foreach (var subdir in System.IO.Directory.EnumerateDirectories(imagedir))
                {
                    var data = Helpers.GetJsonFileIfExists($"{subdir}/command.json");
                    Func<Commands.CommandEventArgs, Task> cmd_body = async e =>
                    {
                        var files = from file in System.IO.Directory.EnumerateFiles([email protected]"{subdir}", "*.*").Where(s => imgexts.Contains(System.IO.Path.GetExtension(s.ToLower()))) select new { File = file };
                        await e.Channel.SendFile(files.ElementAt(new Random().Next(0, files.Count())).File);
                    };
                    if (data == null) group.CreateCommand(Helpers.FileWithoutPath(subdir)).Do(cmd_body);
                    else Helpers.CreateJsonCommand(group, data.ToObject<Dictionary<string, JToken>>().First(), (cmd,cmd_data) =>
                        cmd.FlagNsfw(cmd_data["nsfw"].ToObject<bool>()).Do(cmd_body));
                }
            }

            group.CreateCommand("img")
                .Parameter("search query", Commands.ParameterType.Required)
                .Parameter("extended query", Commands.ParameterType.Multiple)
                .Description("I'll get a random image from Google!")
                .AddCheck((h, i, d) => false).Hide() // Until we can  update this to work
                .Do(e =>
                {
                    Random rnd = new Random();
                    var request = new RestRequest($"images?v=1.0&q={string.Join(" ", e.Args)}&rsz=8&start={rnd.Next(1, 12)}&safe=active", Method.GET);
                    JObject result = JObject.Parse(Helpers.GetRestClient("https://ajax.googleapis.com/ajax/services/search").Execute(request).Content);
                    List<string> images = new List<string>();
                    foreach (var element in result["responseData"]["results"])
                        images.Add(element["unescapedUrl"].ToString());
                    e.Channel.SendMessage(images[rnd.Next(images.Count())].ToString());
                });

            group.CreateCommand("imgur")
                .Parameter("Reddit Board", Commands.ParameterType.Required)
                .Description("I'll pick out a random image from the day's best on an imgur reddit!")
                .Do(e =>
                {
                    try
                    {
                        var result = JObject.Parse(Helpers.GetRestClient("http://imgur.com/r/").Execute(new RestRequest($"{e.Args[0]}/top/day.json", Method.GET)).Content)["data"].First;
                        for (var i = new Random().Next(result.Parent.Count - 1); i != 0; --i, result = result.Next);
                        var part = $"imgur.com/{result["hash"]}";
                        e.Channel.SendMessage($"**http://{part}** http://i.{part}{result["ext"]}");
                    }
                    catch { e.Channel.SendMessage("Imgur says nope~"); }
                });

            CreateBooruCommand(group, "safebooru");
            CreateBooruCommand(group, "gelbooru"); // Disabled without auth, which can't be done through api. (Resurrected cause API no longer requires login for now.)
            CreateBooruCommand(group, "rule34");
            CreateBooruCommand(group, "konachan", "kona");
            CreateBooruCommand(group, "yandere");
            CreateBooruCommand(group, "lolibooru", "loli");
            if (Helpers.FieldExists("Booru", "sankaku"))
                CreateBooruCommand(group, "sankaku", new[]{"sankakuchan", "schan"});
            //CreateBooruCommand(group, "sankakuidol", "sidol"); // Idol disables their API for some reason.
            CreateBooruCommand(group, "e621", "furry");

            group.CreateCommand("meme")
                .Parameter("Meme type (see memelist)")
                .Parameter("Top][/Bottom", Commands.ParameterType.MultipleUnparsed)
                .Description("http://memegen.link/xy/MakeAllTheMemes.jpg")
                .Do(e => e.Channel.SendMessage($"http://memegen.link/{e.Args[0]}{(e.Args.Length == 1 ? "" : $"/{Uri.EscapeDataString(string.Join("-", e.Args, 1, e.Args.Length - 1))}")}.jpg"));

            group.CreateCommand("meme templates")
                .Alias("memelist")
                .Description("See what memes are on the menu. (I'll tell you in PM)")
                .Do(async e =>
                {
                    var json = JObject.Parse(Helpers.GetRestClient("http://memegen.link").Execute(new RestRequest("templates")).Content);
                    var outputs = new List<string>();
                    var i = -1;
                    foreach (var pair in json)
                    {
                        var s = pair.Value.ToString();
                        s = $"{pair.Key}: `{s.Substring(s.LastIndexOf('/') + 1)}`\n";
                        if (outputs.Count == 0 || s.Length + outputs[i].Length > 2000)
                        {
                            outputs.Add(s);
                            ++i;
                        }
                        else outputs[i] += s;
                    }
                    var chan = await e.User.CreatePMChannel();
                    foreach (var output in outputs)
                        await chan.SendMessage(output);
                });
        }
开发者ID:Kusoneko,项目名称:Nekobot,代码行数:98,代码来源:Image.cs

示例3: CreateBooruCommand

 static void CreateBooruCommand(Commands.CommandGroupBuilder group, string booru, string[] aliases = null)
 {
     var cmd = group.CreateCommand(booru);
     cmd.Parameter("[-]tag1", Commands.ParameterType.Optional)
         .Parameter("[-]tag2", Commands.ParameterType.Optional)
         .Parameter("[-]tagn", Commands.ParameterType.Multiple)
         .FlagNsfw(true)
         .Description($"I'll give you a random image from {booru} (optionally with tags)");
     if (aliases != null) foreach (var alias in aliases) cmd.Alias(alias);
     cmd.Do(e => Task.Run(() => Board.Execute(booru, e)));
 }
开发者ID:Kusoneko,项目名称:Nekobot,代码行数:11,代码来源:Image.cs

示例4: CreateLewdCommand

 static void CreateLewdCommand(Commands.CommandGroupBuilder group, string chan)
 {
     group.CreateCommand(chan)
         .FlagNsfw(true)
         .Description($"I'll give you a random image from https://lewdchan.com/{chan}/")
         .Do(async e => await LewdSX(chan, e.Channel));
 }
开发者ID:Kusoneko,项目名称:Nekobot,代码行数:7,代码来源:Image.cs

示例5: AddDelayedCommands

        internal static void AddDelayedCommands(Commands.CommandGroupBuilder group)
        {
            var creds = Program.config["CleverBot"];
            if (!Helpers.FieldExists(creds, "user")) // no credentials
              return;

            // Create the handler
            var handler = new Handler(group.Service.Client.CurrentUser.Id, creds["user"].ToString(), creds["key"].ToString());

            group.CreateCommand("bot")
                .Alias("chatbot")
                .Parameter("on or off", Commands.ParameterType.Optional)
                .MinPermissions(3)
                .Description("I'll turn on/off the chatbot for this channel.\nIf no args, I'll tell you if there's a bot on for this channel.")
                .Do(e =>
                {
                    bool botstatus = handler.HasBot(e.Channel.Id);
                    if (e.Args.Any())
                    {
                        Helpers.OnOffCmd(e, on =>
                        {
                            if (botstatus == on)
                                e.Channel.SendMessage("The bot is already " + (botstatus ? "on" : "off") + $" for {e.Channel}");
                            else
                            {
                                if (botstatus)
                                    handler.RemoveBot(e.Channel.Id);
                                else
                                    handler.CreateBot(group.Service.Client.CurrentUser.Id.ToString(), e.Channel.Id.ToString());
                                e.Channel.SendMessage("The bot is now " + (!botstatus ? "on" : "off") + $" for {e.Channel}");
                                SQL.AddOrUpdateFlag(e.Channel.Id, "chatbot", botstatus ? "-1" : "0");
                            }
                        });
                    }
                    else e.Channel.SendMessage("The bot is currently " + (botstatus ? "on" : "off") + $" for {e.Channel}.");
                });
        }
开发者ID:Kusoneko,项目名称:Nekobot,代码行数:37,代码来源:Chatbot.cs

示例6: AddCommands

        internal static void AddCommands(Commands.CommandGroupBuilder group)
        {
            group.CreateCommand("ping")
                .Description("I'll reply with 'Pong!'")
                .Do(e => e.Channel.SendMessage($"{e.User.Mention}, Pong!{DoPing(e.Message)}"));

            group.CreateCommand("pong")
                .Hide() // More of an easter egg, don't show in help.
                .Description("I'll reply with 'Ping?'")
                .Do(e => e.Channel.SendMessage($"{e.User.Mention}, Ping?{DoPing(e.Message)}"));

            group.CreateCommand("uptime")
                .Description("I'll tell you how long I've been awake~")
                .Do(e => e.Channel.SendMessage(Format.Code(Helpers.Uptime().ToString())));

            Func<Role, string> role_info = r =>
            {
                string ret = $"{r.Name} is id {r.Id}, has {r.Members.Count()} members, color is {r.Color}, perms are {r.Permissions.RawValue}, and position is {r.Position}";
                if (r.IsManaged) ret += "; it is managed by the server";
                return $"{ret}.\n";
            };
            group.CreateCommand("whois")
                .Alias("getinfo")
                .Parameter("[@User1] [@User2] [...]", Commands.ParameterType.Unparsed)
                .Description("I'll give you information about the mentioned user(s).")
                .Do(async e =>
                {
                    if (e.Args[0].Length == 0 || (!e.Message.MentionedUsers.Any() && !e.Message.MentionedRoles.Any())) return;
                    string reply = "";
                    bool oniicheck = e.User.Id == 63299786798796800;
                    foreach (User u in e.Message.MentionedUsers)
                    {
                        bool onii = oniicheck && u.Id == 63296013791666176;
                        string possessive = onii ? "his" : "their";
                        reply += u.Name;
                        if (!string.IsNullOrEmpty(u.Nickname)) reply += $" (Nick: {u.Nickname})";
                        reply += $"{(onii ? " is your onii-chan <3 and his" : "'s")} id is {u.Id}, {possessive} discriminator is {u.Discriminator} and {possessive} permission level is {Helpers.GetPermissions(u, e.Channel)}.";
                        if (u.IsBot) reply += " Also, they are a bot!";
                        reply += '\n';
                    }
                    foreach (Role r in e.Message.MentionedRoles)
                        reply += role_info(r);
                    await e.Channel.SendMessage('\n' + reply);
                });

            group.CreateCommand("whois role")
                .Alias("getinfo role")
                .Parameter("role(s)", Commands.ParameterType.Unparsed)
                .Description("I'll give you info on particular roles by name (comma separated)")
                .Do(e =>
                {
                    string reply = "";
                    if (e.Args[0].Length == 0)
                        reply = "You need to provide at least one role name!";
                    else Helpers.CommaSeparateRoleNames(e, (roles, str) =>
                    {
                        foreach (var r in roles)
                            reply += role_info(r);
                    });
                    e.Channel.SendMessage(reply);
                });
            
            Music.AddCommands(group);

            Image.AddCommands(group);

            Action<Commands.CommandEventArgs, Func<string, string>> lookup_cmd = (e, f) =>
            {
                var args = e.Args[0];
                e.Channel.SendMessage(args.Length == 0 ? "I cannot lookup nothing, silly!" : f(args));
            };

            group.CreateCommand("urban")
                .Alias("urbandictionary")
                .Alias("ud")
                .Parameter("phrase", Commands.ParameterType.Unparsed)
                .Description("I'll give you the urban dictionary definition of a phrase.")
                .Do(e => lookup_cmd(e, args =>
                {
                    var req = new RestRequest("define", Method.GET);
                    req.AddQueryParameter("term", args);
                    var json = JObject.Parse(Helpers.GetRestClient("http://api.urbandictionary.com/v0").Execute(req).Content);
                    var list = json["list"];
                    if (!list.HasValues) return "No results found.";
                    var resp = list[0];
                    return $"{resp["word"]}: {resp["definition"]}\n⬆{resp["thumbs_up"]} ⬇{resp["thumbs_down"]} <{resp["permalink"]}>```{resp["example"]}```";
                }));

            if (Helpers.FieldExists("WolframAlpha", "appid"))
            {
                group.CreateCommand("wolfram")
                    .Parameter("input", Commands.ParameterType.Unparsed)
                    .Description("I'll look something up for you on ")
                    .Do(e => lookup_cmd(e, args =>
                    {
                        var rc = Helpers.GetRestClient("http://api.wolframalpha.com/v2/"); // TODO: Do we want this static?
                        rc.AddDefaultParameter("appid", Program.config["WolframAlpha"]["appid"]);
                        var req = new RestRequest("query", Method.GET);
                        req.AddQueryParameter("input", args);
                        string ret = "";
//.........这里部分代码省略.........
开发者ID:Kusoneko,项目名称:Nekobot,代码行数:101,代码来源:Common.cs

示例7: AddCommands

        internal static void AddCommands(Commands.CommandGroupBuilder group)
        {
            group.CreateCommand("rand")
                .Parameter("min", Commands.ParameterType.Optional)
                .Parameter("max", Commands.ParameterType.Optional)
                .Description("I'll give you a random number between *min* and *max*. Both are optional. If only one is given, it's *max*. (defaults: 1-100)")
                .Do(async e =>
                {
                    foreach (string s in e.Args)
                    {
                        int dummy = 0;
                        if (!int.TryParse(s, out dummy))
                        {
                            await e.Channel.SendMessage($"{s} is not a number!");
                            return;
                        }
                    }
                    int min = e.Args.Length > 1 ? int.Parse(e.Args[0]) : 1;
                    int max = e.Args.Length > 0 ? int.Parse(e.Args[e.Args.Length == 1 ? 0 : 1]) : 100;
                    if (min == max)
                    {
                        await e.Channel.SendMessage($"You're joking right? It's {min}.");
                        return;
                    }
                    if (min > max)
                    {
                        int z = min;
                        min = max;
                        max = z;
                    }
                    await e.Channel.SendMessage($"Your number is **{new Random().Next(min,max+1)}**.");
                });

            var dd = new DiceKernel().Init().Get<Dice>();
            group.CreateCommand("roll")
                .Parameter("[times]t [dice expressions]", Commands.ParameterType.Unparsed)
                .Description("I'll roll a dice expression([count]d[sides]k[kept][mods...]...) as many `times` as you ask(default 1). (If empty or just `times`, will roll default: 1d6.)")
                .Do(async e =>
                {
                    var chan = e.Channel;
                    if (e.Args[0].ToLower() == "rick")
                    {
                        await chan.SendMessage("https://youtu.be/dQw4w9WgXcQ");
                        return;
                    }
                    var args = string.Join(" ", e.Args);
                    int times;
                    if ((times = args.IndexOf("t")) != -1)
                    {
                        int t = times;
                        if (int.TryParse(args.Substring(0, t), out times))
                        {
                            if (times <= 0)
                            {
                                await chan.SendMessage($"0, baka!");
                                return;
                            }
                            args = args.Substring(t+1);
                        }
                        else times = 1;
                    }
                    else times = 1;

                    string response = "";
                    double? total = times > 1 ? (int?)0 : null;
                    bool do_default = args.Length == 0; // Default roll.
                    for (; times != 0; --times)
                    {
                        double val;
                        if (do_default)
                        {
                            val = dd.Roll().d6();
                            response += $"{val} {(total == null ? "" : times == 1 ? "=" : "+")} ";
                        }
                        else
                        {
                            try
                            {
                                var roll = dd.ReplaceRollsWithSum(args);
                                var eval = dd.Evaluate(roll);
                                val = Utils.ChangeType<double>(eval);
                                if (response != "") response += '\n';
                                var str = Utils.BooleanOrType<double>(eval);
                                if (roll != str) response += $"{Discord.Format.Code(roll)} = ";
                                response += $"**{str}**.";
                            }
                            catch (Exception ex)
                            {
                                await chan.SendMessage($"Invalid Arguments: {ex.Message}");
                                return;
                            }
                        }
                        if (total != null) total += val;
                    }
                    if (total != null)
                    {
                        if (!do_default) response += "\nTotal Result = ";
                        response += $"**{total}**.";
                    }
                    await chan.SendMessage(response);
//.........这里部分代码省略.........
开发者ID:Kusoneko,项目名称:Nekobot,代码行数:101,代码来源:RPG.cs

示例8: AddCommands

        internal static void AddCommands(Commands.CommandGroupBuilder group)
        {
            group.CreateCommand("nsfw status")
                .Alias("canlewd status")
                .Description("I'll tell you if this channel allows nsfw commands.")
                .Do(async e =>
                {
                    bool nsfw = GetNsfw(e.Channel);
                    if (nsfw)
                        await Program.client.SendMessage(e.Channel, "This channel allows nsfw commands.");
                    else
                        await Program.client.SendMessage(e.Channel, "This channel doesn't allow nsfw commands.");
                });

            // Moderator Commands
            group.CreateCommand("nsfw")
                .Alias("canlewd")
                .Parameter("on/off", Commands.ParameterType.Required)
                .MinPermissions(1)
                .Description("I'll set a channel's nsfw flag to on or off.")
                .Do(async e =>
                {
                    bool on = e.Args[0] == "on";
                    bool off = !on && e.Args[0] == "off";
                    if (on || off)
                    {
                        bool nsfw = GetNsfw(e.Channel);
                        string status = on ? "allow" : "disallow";
                        if (nsfw == on || nsfw != off)
                            await Program.client.SendMessage(e.Channel, $"<@{e.User.Id}>, this channel is already {status}ing nsfw commands.");
                        else
                        {
                            await SQL.ExecuteNonQueryAsync(off ? $"update flags set nsfw=0 where channel='{e.Channel.Id}'"
                                : SQL.ExecuteScalarPos($"select count(channel) from flags where channel='{e.Channel.Id}'")
                                ? $"update flags set nsfw=1 where channel='{e.Channel.Id}'"
                                : $"insert into flags values ('{e.Channel.Id}', 1, 0, 0, -1)");
                            await Program.client.SendMessage(e.Channel, $"I've set this channel to {status} nsfw commands.");
                        }
                    }
                    else await Program.client.SendMessage(e.Channel, $"<@{e.User.Id}>, '{String.Join(" ", e.Args)}' isn't a valid argument. Please use on or off instead.");
                });

            // Administrator Commands
            group.CreateCommand("ignore")
                .Parameter("channel", Commands.ParameterType.Optional)
                .Parameter("user", Commands.ParameterType.Optional)
                .Parameter("...", Commands.ParameterType.Multiple)
                .MinPermissions(1)
                .Description("I'll ignore commands coming from a particular channel or user")
                .Do(async e =>
                {
                    if (e.Message.MentionedChannels.Count() > 0 || e.Message.MentionedUsers.Count() > 0)
                    {
                        int perms = Program.GetPermissions(e.User, e.Channel);
                        string reply = "";
                        foreach (Channel c in e.Message.MentionedChannels)
                            reply += (reply != "" ? "\n" : "") + await SetIgnored("channel", "flags", c.Id, "0, 0, 1, -1", '#', perms);
                        foreach (User u in e.Message.MentionedUsers)
                            reply += (reply != "" ? "\n" : "") + await SetIgnored("user", "users", u.Id, "0, 1", '@', perms, Program.GetPermissions(u, e.Channel));
                        await Program.client.SendMessage(e.Channel, reply);
                    }
                    else
                    {
                        await Program.client.SendMessage(e.Channel, "You need to mention at least one user or channel!");
                    }
                });
        }
开发者ID:Lirusaito,项目名称:Nekobot,代码行数:67,代码来源:Flags.cs


注:本文中的Commands.CreateCommand方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。