internal override void Init(CommandGroupBuilder cgb)
        {
            cgb.CreateCommand(Module.Prefix + "typestart")
            .Description("Starts a typing contest.")
            .Do(DoFunc());

            cgb.CreateCommand(Module.Prefix + "typestop")
            .Description("Stops a typing contest on the current channel.")
            .Do(QuitFunc());

            cgb.CreateCommand(Module.Prefix + "typeadd")
            .Description("Adds a new article to the typing contest. Owner only.")
            .Parameter("text", ParameterType.Unparsed)
            .Do(async e =>
            {
                if (!WizBot.IsOwner(e.User.Id) || string.IsNullOrWhiteSpace(e.GetArg("text")))
                {
                    return;
                }

                DbHandler.Instance.InsertData(new TypingArticle
                {
                    Text      = e.GetArg("text"),
                    DateAdded = DateTime.Now
                });

                await e.Channel.SendMessage("Added new article for typing game.").ConfigureAwait(false);
            });

            //todo add user submissions
        }
Beispiel #2
0
 public static Func <Command, User, Channel, bool> OwnerOnly() =>
 (com, user, ch) => WizBot.IsOwner(user.Id);
Beispiel #3
0
        public override void Install(ModuleManager manager)
        {
            var rng = new Random();

            manager.CreateCommands("", cgb =>
            {
                cgb.AddCheck(PermissionChecker.Instance);

                cgb.CreateCommand("..")
                .Description("Adds a new quote with the specified name (single word) and message (no limit).\n**Usage**: .. abc My message")
                .Parameter("keyword", ParameterType.Required)
                .Parameter("text", ParameterType.Unparsed)
                .Do(async e =>
                {
                    var text = e.GetArg("text");
                    if (string.IsNullOrWhiteSpace(text))
                    {
                        return;
                    }
                    await Task.Run(() =>
                                   Classes.DbHandler.Instance.InsertData(new DataModels.UserQuote()
                    {
                        DateAdded = DateTime.Now,
                        Keyword   = e.GetArg("keyword").ToLowerInvariant(),
                        Text      = text,
                        UserName  = e.User.Name,
                    })).ConfigureAwait(false);

                    await e.Channel.SendMessage("`New quote added.`").ConfigureAwait(false);
                });

                cgb.CreateCommand("...")
                .Description("Shows a random quote with a specified name.\n**Usage**: .. abc")
                .Parameter("keyword", ParameterType.Required)
                .Do(async e =>
                {
                    var keyword = e.GetArg("keyword")?.ToLowerInvariant();
                    if (string.IsNullOrWhiteSpace(keyword))
                    {
                        return;
                    }

                    var quote =
                        Classes.DbHandler.Instance.GetRandom <DataModels.UserQuote>(
                            uqm => uqm.Keyword == keyword);

                    if (quote != null)
                    {
                        await e.Channel.SendMessage($"📣 {quote.Text}").ConfigureAwait(false);
                    }
                    else
                    {
                        await e.Channel.SendMessage("💢`No quote found.`").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand("..qdel")
                .Alias("..quotedelete")
                .Description("Deletes all quotes with the specified keyword. You have to either be bot owner or the creator of the quote to delete it.\n**Usage**: `..qdel abc`")
                .Parameter("quote", ParameterType.Required)
                .Do(async e =>
                {
                    var text = e.GetArg("quote")?.Trim();
                    if (string.IsNullOrWhiteSpace(text))
                    {
                        return;
                    }
                    await Task.Run(() =>
                    {
                        if (WizBot.IsOwner(e.User.Id))
                        {
                            Classes.DbHandler.Instance.DeleteWhere <UserQuote>(uq => uq.Keyword == text);
                        }
                        else
                        {
                            Classes.DbHandler.Instance.DeleteWhere <UserQuote>(uq => uq.Keyword == text && uq.UserName == e.User.Name);
                        }
                    }).ConfigureAwait(false);

                    await e.Channel.SendMessage("`Done.`").ConfigureAwait(false);
                });
            });

            manager.CreateCommands(WizBot.BotMention, cgb =>
            {
                var client = manager.Client;

                cgb.AddCheck(PermissionChecker.Instance);

                commands.ForEach(cmd => cmd.Init(cgb));

                cgb.CreateCommand("uptime")
                .Description("Shows how long WizBot has been running for.")
                .Do(async e =>
                {
                    var time = (DateTime.Now - Process.GetCurrentProcess().StartTime);
                    var str  = string.Format("I have been running for {0} days, {1} hours, and {2} minutes.", time.Days, time.Hours, time.Minutes);
                    await e.Channel.SendMessage(str).ConfigureAwait(false);
                });

                cgb.CreateCommand("die")
                .Description("Works only for the owner. Shuts the bot down.")
                .Do(async e =>
                {
                    if (WizBot.IsOwner(e.User.Id))
                    {
                        await e.Channel.SendMessage(e.User.Mention + ", Yes, my love.").ConfigureAwait(false);
                        await Task.Delay(5000).ConfigureAwait(false);
                        Environment.Exit(0);
                    }
                    else
                    {
                        await e.Channel.SendMessage(e.User.Mention + ", No.").ConfigureAwait(false);
                    }
                });

                var randServerSw = new Stopwatch();
                randServerSw.Start();

                cgb.CreateCommand("do you love me")
                .Description("Replies with positive answer only to the bot owner.")
                .Do(async e =>
                {
                    if (WizBot.IsOwner(e.User.Id))
                    {
                        await e.Channel.SendMessage(e.User.Mention + ", Of course I do, my Master.").ConfigureAwait(false);
                    }
                    else
                    {
                        await e.Channel.SendMessage(e.User.Mention + ", Don't be silly.").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand("how are you")
                .Alias("how are you?")
                .Description("Replies positive only if bot owner is online.")
                .Do(async e =>
                {
                    if (WizBot.IsOwner(e.User.Id))
                    {
                        await e.Channel.SendMessage(e.User.Mention + " I am great as long as you are here.").ConfigureAwait(false);
                        return;
                    }
                    var kw = e.Server.GetUser(WizBot.Creds.OwnerIds[0]);
                    if (kw != null && kw.Status == UserStatus.Online)
                    {
                        await e.Channel.SendMessage(e.User.Mention + " I am great as long as " + kw.Mention + " is with me.").ConfigureAwait(false);
                    }
                    else
                    {
                        await e.Channel.SendMessage(e.User.Mention + " I am sad. My Master is not with me.").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand("fire")
                .Description("Shows a unicode fire message. Optional parameter [x] tells her how many times to repeat the fire.\n**Usage**: @Wiz-Bot fire [x]")
                .Parameter("times", ParameterType.Optional)
                .Do(async e =>
                {
                    var count = 1;
                    int.TryParse(e.Args[0], out count);
                    if (count == 0)
                    {
                        count = 1;
                    }
                    if (count < 1 || count > 12)
                    {
                        await e.Channel.SendMessage("Number must be between 0 and 12").ConfigureAwait(false);
                        return;
                    }

                    var str = "";
                    for (var i = 0; i < count; i++)
                    {
                        str += firestr;
                    }
                    await e.Channel.SendMessage(str).ConfigureAwait(false);
                });

                cgb.CreateCommand("rip")
                .Description("Shows a grave image of someone with a start year\n**Usage**: @Wiz-Bot rip @Someone 2000")
                .Parameter("user", ParameterType.Required)
                .Parameter("year", ParameterType.Optional)
                .Do(async e =>
                {
                    if (string.IsNullOrWhiteSpace(e.GetArg("user")))
                    {
                        return;
                    }
                    var usr  = e.Channel.FindUsers(e.GetArg("user")).FirstOrDefault();
                    var text = "";
                    text     = usr?.Name ?? e.GetArg("user");
                    await e.Channel.SendFile("ripzor_m8.png",
                                             RipName(text, string.IsNullOrWhiteSpace(e.GetArg("year"))
                                ? null
                                : e.GetArg("year")))
                    .ConfigureAwait(false);
                });
                if (!WizBot.Config.DontJoinServers)
                {
                    cgb.CreateCommand("j")
                    .Description("Joins a server using a code.")
                    .Parameter("id", ParameterType.Required)
                    .Do(async e =>
                    {
                        var invite = await client.GetInvite(e.Args[0]).ConfigureAwait(false);
                        if (invite != null)
                        {
                            try
                            {
                                await invite.Accept().ConfigureAwait(false);
                            }
                            catch
                            {
                                await e.Channel.SendMessage("Failed to accept invite.").ConfigureAwait(false);
                            }
                            await e.Channel.SendMessage("I got in!").ConfigureAwait(false);
                            return;
                        }
                        await e.Channel.SendMessage("Invalid code.").ConfigureAwait(false);
                    });
                }

                cgb.CreateCommand("slm")
                .Description("Shows the message where you were last mentioned in this channel (checks last 10k messages)")
                .Do(async e =>
                {
                    Message msg = null;
                    var msgs    = (await e.Channel.DownloadMessages(100).ConfigureAwait(false))
                                  .Where(m => m.MentionedUsers.Contains(e.User))
                                  .OrderByDescending(m => m.Timestamp);
                    if (msgs.Any())
                    {
                        msg = msgs.First();
                    }
                    else
                    {
                        var attempt         = 0;
                        Message lastMessage = null;
                        while (msg == null && attempt++ < 5)
                        {
                            var msgsarr = await e.Channel.DownloadMessages(100, lastMessage?.Id).ConfigureAwait(false);
                            msg         = msgsarr
                                          .Where(m => m.MentionedUsers.Contains(e.User))
                                          .OrderByDescending(m => m.Timestamp)
                                          .FirstOrDefault();
                            lastMessage = msgsarr.OrderBy(m => m.Timestamp).First();
                        }
                    }
                    if (msg != null)
                    {
                        await e.Channel.SendMessage($"Last message mentioning you was at {msg.Timestamp}\n**Message from {msg.User.Name}:** {msg.RawText}")
                        .ConfigureAwait(false);
                    }
                    else
                    {
                        await e.Channel.SendMessage("I can't find a message mentioning you.").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand("hide")
                .Description("Hides WizBot in plain sight!11!!")
                .Do(async e =>
                {
                    using (var ms = Resources.hidden.ToStream(ImageFormat.Png))
                    {
                        await client.CurrentUser.Edit(WizBot.Creds.Password, avatar: ms).ConfigureAwait(false);
                    }
                    await e.Channel.SendMessage("*hides*").ConfigureAwait(false);
                });

                cgb.CreateCommand("unhide")
                .Description("Unhides WizBot in plain sight!1!!1")
                .Do(async e =>
                {
                    using (var fs = new FileStream("data/avatar.png", FileMode.Open))
                    {
                        await client.CurrentUser.Edit(WizBot.Creds.Password, avatar: fs).ConfigureAwait(false);
                    }
                    await e.Channel.SendMessage("*unhides*").ConfigureAwait(false);
                });

                cgb.CreateCommand("dump")
                .Description("Dumps all of the invites it can to dump.txt.** Owner Only.**")
                .Do(async e =>
                {
                    if (!WizBot.IsOwner(e.User.Id))
                    {
                        return;
                    }
                    var i       = 0;
                    var j       = 0;
                    var invites = "";
                    foreach (var s in client.Servers)
                    {
                        try
                        {
                            var invite = await s.CreateInvite(0).ConfigureAwait(false);
                            invites   += invite.Url + "\n";
                            i++;
                        }
                        catch
                        {
                            j++;
                            continue;
                        }
                    }
                    File.WriteAllText("dump.txt", invites);
                    await e.Channel.SendMessage($"Got invites for {i} servers and failed to get invites for {j} servers")
                    .ConfigureAwait(false);
                });

                cgb.CreateCommand("ab")
                .Description("Try to get 'abalabahaha'")
                .Do(async e =>
                {
                    string[] strings = { "ba", "la", "ha" };
                    var construct    = "@a";
                    var cnt          = rng.Next(4, 7);
                    while (cnt-- > 0)
                    {
                        construct += strings[rng.Next(0, strings.Length)];
                    }
                    await e.Channel.SendMessage(construct).ConfigureAwait(false);
                });

                cgb.CreateCommand("av")
                .Alias("avatar")
                .Parameter("mention", ParameterType.Required)
                .Description("Shows a mentioned person's avatar.\n**Usage**: ~av @X")
                .Do(async e =>
                {
                    var usr = e.Channel.FindUsers(e.GetArg("mention")).FirstOrDefault();
                    if (usr == null)
                    {
                        await e.Channel.SendMessage("Invalid user specified.").ConfigureAwait(false);
                        return;
                    }
                    await e.Channel.SendMessage(await usr.AvatarUrl.ShortenUrl()).ConfigureAwait(false);
                });
            });
        }
        public override void Install(ModuleManager manager)
        {
            var client = manager.Client;

            var serializer = new ManateeSerializer();

            TrelloConfiguration.Serializer         = serializer;
            TrelloConfiguration.Deserializer       = serializer;
            TrelloConfiguration.JsonFactory        = new ManateeFactory();
            TrelloConfiguration.RestClientProvider = new Manatee.Trello.WebApi.WebApiClientProvider();
            TrelloAuthorization.Default.AppKey     = WizBot.Creds.TrelloAppKey;
            //TrelloAuthorization.Default.UserToken = "[your user token]";

            Discord.Channel bound = null;
            Board           board = null;

            List <string> last5ActionIDs = null;

            t.Elapsed += async(s, e) =>
            {
                try
                {
                    if (board == null || bound == null)
                    {
                        return; //do nothing if there is no bound board
                    }
                    board.Refresh();
                    var cur5Actions      = board.Actions.Take(board.Actions.Count() < 5 ? board.Actions.Count() : 5);
                    var cur5ActionsArray = cur5Actions as Action[] ?? cur5Actions.ToArray();

                    if (last5ActionIDs == null)
                    {
                        last5ActionIDs = cur5ActionsArray.Select(a => a.Id).ToList();
                        return;
                    }

                    foreach (var a in cur5ActionsArray.Where(ca => !last5ActionIDs.Contains(ca.Id)))
                    {
                        await bound.Send("**--TRELLO NOTIFICATION--**\n" + a.ToString()).ConfigureAwait(false);
                    }
                    last5ActionIDs.Clear();
                    last5ActionIDs.AddRange(cur5ActionsArray.Select(a => a.Id));
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Timer failed " + ex.ToString());
                }
            };

            manager.CreateCommands("trello ", cgb =>
            {
                cgb.AddCheck(PermissionChecker.Instance);

                cgb.CreateCommand("join")
                .Alias("j")
                .Description("Joins a server")
                .Parameter("code", Discord.Commands.ParameterType.Required)
                .Do(async e =>
                {
                    if (!WizBot.IsOwner(e.User.Id) || WizBot.IsBot)
                    {
                        return;
                    }
                    try
                    {
                        await(await client.GetInvite(e.GetArg("code")).ConfigureAwait(false)).Accept()
                        .ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                });

                cgb.CreateCommand("bind")
                .Description("Bind a trello bot to a single channel. " +
                             "You will receive notifications from your board when something is added or edited." +
                             "\n**Usage**: bind [board_id]")
                .Parameter("board_id", Discord.Commands.ParameterType.Required)
                .Do(async e =>
                {
                    if (!WizBot.IsOwner(e.User.Id))
                    {
                        return;
                    }
                    if (bound != null)
                    {
                        return;
                    }
                    try
                    {
                        bound = e.Channel;
                        board = new Board(e.GetArg("board_id").Trim());
                        board.Refresh();
                        await e.Channel.SendMessage("Successfully bound to this channel and board " + board.Name);
                        t.Start();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Failed to join the board. " + ex.ToString());
                    }
                });

                cgb.CreateCommand("unbind")
                .Description("Unbinds a bot from the channel and board.")
                .Do(async e =>
                {
                    if (!WizBot.IsOwner(e.User.Id))
                    {
                        return;
                    }
                    if (bound == null || bound != e.Channel)
                    {
                        return;
                    }
                    t.Stop();
                    bound = null;
                    board = null;
                    await e.Channel.SendMessage("Successfully unbound trello from this channel.").ConfigureAwait(false);
                });

                cgb.CreateCommand("lists")
                .Alias("list")
                .Description("Lists all lists yo ;)")
                .Do(async e =>
                {
                    if (!WizBot.IsOwner(e.User.Id))
                    {
                        return;
                    }
                    if (bound == null || board == null || bound != e.Channel)
                    {
                        return;
                    }
                    await e.Channel.SendMessage("Lists for a board '" + board.Name + "'\n" + string.Join("\n", board.Lists.Select(l => "**• " + l.ToString() + "**")))
                    .ConfigureAwait(false);
                });

                cgb.CreateCommand("cards")
                .Description("Lists all cards from the supplied list. You can supply either a name or an index.")
                .Parameter("list_name", Discord.Commands.ParameterType.Unparsed)
                .Do(async e =>
                {
                    if (!WizBot.IsOwner(e.User.Id))
                    {
                        return;
                    }
                    if (bound == null || board == null || bound != e.Channel || e.GetArg("list_name") == null)
                    {
                        return;
                    }

                    int num;
                    var success = int.TryParse(e.GetArg("list_name"), out num);
                    List list   = null;
                    if (success && num <= board.Lists.Count() && num > 0)
                    {
                        list = board.Lists[num - 1];
                    }
                    else
                    {
                        list = board.Lists.FirstOrDefault(l => l.Name == e.GetArg("list_name"));
                    }


                    if (list != null)
                    {
                        await e.Channel.SendMessage("There are " + list.Cards.Count() + " cards in a **" + list.Name + "** list\n" + string.Join("\n", list.Cards.Select(c => "**• " + c.ToString() + "**")))
                        .ConfigureAwait(false);
                    }
                    else
                    {
                        await e.Channel.SendMessage("No such list.")
                        .ConfigureAwait(false);
                    }
                });
            });
        }
Beispiel #5
0
        public override void Install(ModuleManager manager)
        {
            var client = WizBot.Client;

            manager.CreateCommands("", cgb =>
            {
                cgb.AddCheck(PermissionChecker.Instance);

                commands.ForEach(cmd => cmd.Init(cgb));

                cgb.CreateCommand(Prefix + "next")
                .Alias(Prefix + "n")
                .Alias(Prefix + "skip")
                .Description($"Goes to the next song in the queue. You have to be in the same voice channel as the bot. | `{Prefix}n`")
                .Do(e =>
                {
                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        return;
                    }
                    if (musicPlayer.PlaybackVoiceChannel == e.User.VoiceChannel)
                    {
                        musicPlayer.Next();
                    }
                });

                cgb.CreateCommand(Prefix + "stop")
                .Alias(Prefix + "s")
                .Description($"Stops the music and clears the playlist. Stays in the channel. | `{Prefix}s`")
                .Do(e =>
                {
                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        return;
                    }
                    if (e.User.VoiceChannel == musicPlayer.PlaybackVoiceChannel)
                    {
                        musicPlayer.Autoplay = false;
                        musicPlayer.Stop();
                    }
                });

                cgb.CreateCommand(Prefix + "destroy")
                .Alias(Prefix + "d")
                .Description("Completely stops the music and unbinds the bot from the channel. " +
                             $"(may cause weird behaviour) | `{Prefix}d`")
                .Do(e =>
                {
                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryRemove(e.Server, out musicPlayer))
                    {
                        return;
                    }
                    if (e.User.VoiceChannel == musicPlayer.PlaybackVoiceChannel)
                    {
                        musicPlayer.Destroy();
                    }
                });

                cgb.CreateCommand(Prefix + "pause")
                .Alias(Prefix + "p")
                .Description($"Pauses or Unpauses the song. | `{Prefix}p`")
                .Do(async e =>
                {
                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        return;
                    }
                    if (e.User.VoiceChannel != musicPlayer.PlaybackVoiceChannel)
                    {
                        return;
                    }
                    musicPlayer.TogglePause();
                    if (musicPlayer.Paused)
                    {
                        await e.Channel.SendMessage("🎵`Music Player paused.`").ConfigureAwait(false);
                    }
                    else
                    {
                        await e.Channel.SendMessage("🎵`Music Player unpaused.`").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "queue")
                .Alias(Prefix + "q")
                .Alias(Prefix + "yq")
                .Description("Queue a song using keywords or a link. Bot will join your voice channel." +
                             $"**You must be in a voice channel**. | `{Prefix}q Dream Of Venice`")
                .Parameter("query", ParameterType.Unparsed)
                .Do(async e =>
                {
                    await QueueSong(e.User, e.Channel, e.User.VoiceChannel, e.GetArg("query")).ConfigureAwait(false);
                    if (e.Server.CurrentUser.GetPermissions(e.Channel).ManageMessages)
                    {
                        await Task.Delay(10000).ConfigureAwait(false);
                        await e.Message.Delete().ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "soundcloudqueue")
                .Alias(Prefix + "sq")
                .Description("Queue a soundcloud song using keywords. Bot will join your voice channel." +
                             $"**You must be in a voice channel**. | `{Prefix}sq Dream Of Venice`")
                .Parameter("query", ParameterType.Unparsed)
                .Do(async e =>
                {
                    await QueueSong(e.User, e.Channel, e.User.VoiceChannel, e.GetArg("query"), musicType: MusicType.Soundcloud).ConfigureAwait(false);
                    if (e.Server.CurrentUser.GetPermissions(e.Channel).ManageMessages)
                    {
                        await Task.Delay(10000).ConfigureAwait(false);
                        await e.Message.Delete().ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "listqueue")
                .Alias(Prefix + "lq")
                .Description($"Lists 15 currently queued songs per page. Default page is 1. | `{Prefix}lq` or `{Prefix}lq 2`")
                .Parameter("page", ParameterType.Optional)
                .Do(async e =>
                {
                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        await e.Channel.SendMessage("🎵 No active music player.").ConfigureAwait(false);
                        return;
                    }

                    int page;
                    if (!int.TryParse(e.GetArg("page"), out page) || page <= 0)
                    {
                        page = 1;
                    }

                    var currentSong = musicPlayer.CurrentSong;
                    if (currentSong == null)
                    {
                        return;
                    }
                    var toSend = $"🎵`Now Playing` {currentSong.PrettyName} " + $"{currentSong.PrettyCurrentTime()}\n";
                    if (musicPlayer.RepeatSong)
                    {
                        toSend += "🔂";
                    }
                    else if (musicPlayer.RepeatPlaylist)
                    {
                        toSend += "🔁";
                    }
                    toSend += $" **{musicPlayer.Playlist.Count}** `tracks currently queued. Showing page {page}` ";
                    if (musicPlayer.MaxQueueSize != 0 && musicPlayer.Playlist.Count >= musicPlayer.MaxQueueSize)
                    {
                        toSend += "**Song queue is full!**\n";
                    }
                    else
                    {
                        toSend += "\n";
                    }
                    const int itemsPerPage = 15;
                    int startAt            = itemsPerPage * (page - 1);
                    var number             = 1 + startAt;
                    await e.Channel.SendMessage(toSend + string.Join("\n", musicPlayer.Playlist.Skip(startAt).Take(15).Select(v => $"`{number++}.` {v.PrettyName}"))).ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "nowplaying")
                .Alias(Prefix + "np")
                .Description($"Shows the song currently playing. | `{Prefix}np`")
                .Do(async e =>
                {
                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        return;
                    }
                    var currentSong = musicPlayer.CurrentSong;
                    if (currentSong == null)
                    {
                        return;
                    }
                    await e.Channel.SendMessage($"🎵`Now Playing` {currentSong.PrettyName} " +
                                                $"{currentSong.PrettyCurrentTime()}").ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "volume")
                .Alias(Prefix + "vol")
                .Description($"Sets the music volume 0-100% | `{Prefix}vol 50`")
                .Parameter("val", ParameterType.Required)
                .Do(async e =>
                {
                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        return;
                    }
                    if (e.User.VoiceChannel != musicPlayer.PlaybackVoiceChannel)
                    {
                        return;
                    }
                    var arg = e.GetArg("val");
                    int volume;
                    if (!int.TryParse(arg, out volume))
                    {
                        await e.Channel.SendMessage("Volume number invalid.").ConfigureAwait(false);
                        return;
                    }
                    volume = musicPlayer.SetVolume(volume);
                    await e.Channel.SendMessage($"🎵 `Volume set to {volume}%`").ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "defvol")
                .Alias(Prefix + "dv")
                .Description("Sets the default music volume when music playback is started (0-100)." +
                             $" Persists through restarts. | `{Prefix}dv 80`")
                .Parameter("val", ParameterType.Required)
                .Do(async e =>
                {
                    var arg = e.GetArg("val");
                    float volume;
                    if (!float.TryParse(arg, out volume) || volume < 0 || volume > 100)
                    {
                        await e.Channel.SendMessage("Volume number invalid.").ConfigureAwait(false);
                        return;
                    }
                    var conf = SpecificConfigurations.Default.Of(e.Server.Id);
                    conf.DefaultMusicVolume = volume / 100;
                    await e.Channel.SendMessage($"🎵 `Default volume set to {volume}%`").ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "mute")
                .Alias(Prefix + "min")
                .Description($"Sets the music volume to 0% | `{Prefix}min`")
                .Do(e =>
                {
                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        return;
                    }
                    if (e.User.VoiceChannel != musicPlayer.PlaybackVoiceChannel)
                    {
                        return;
                    }
                    musicPlayer.SetVolume(0);
                });

                cgb.CreateCommand(Prefix + "max")
                .Description($"Sets the music volume to 100%. | `{Prefix}max`")
                .Do(e =>
                {
                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        return;
                    }
                    if (e.User.VoiceChannel != musicPlayer.PlaybackVoiceChannel)
                    {
                        return;
                    }
                    musicPlayer.SetVolume(100);
                });

                cgb.CreateCommand(Prefix + "half")
                .Description($"Sets the music volume to 50%. | `{Prefix}half`")
                .Do(e =>
                {
                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        return;
                    }
                    if (e.User.VoiceChannel != musicPlayer.PlaybackVoiceChannel)
                    {
                        return;
                    }
                    musicPlayer.SetVolume(50);
                });

                cgb.CreateCommand(Prefix + "shuffle")
                .Alias(Prefix + "sh")
                .Description($"Shuffles the current playlist. | `{Prefix}sh`")
                .Do(async e =>
                {
                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        return;
                    }
                    if (e.User.VoiceChannel != musicPlayer.PlaybackVoiceChannel)
                    {
                        return;
                    }
                    if (musicPlayer.Playlist.Count < 2)
                    {
                        await e.Channel.SendMessage("💢 Not enough songs in order to perform the shuffle.").ConfigureAwait(false);
                        return;
                    }

                    musicPlayer.Shuffle();
                    await e.Channel.SendMessage("🎵 `Songs shuffled.`").ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "playlist")
                .Alias(Prefix + "pl")
                .Description($"Queues up to 500 songs from a youtube playlist specified by a link, or keywords. | `{Prefix}pl playlist link or name`")
                .Parameter("playlist", ParameterType.Unparsed)
                .Do(async e =>
                {
                    var arg = e.GetArg("playlist");
                    if (string.IsNullOrWhiteSpace(arg))
                    {
                        return;
                    }
                    if (e.User.VoiceChannel?.Server != e.Server)
                    {
                        await e.Channel.SendMessage("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining it.").ConfigureAwait(false);
                        return;
                    }
                    var plId = await SearchHelper.GetPlaylistIdByKeyword(arg).ConfigureAwait(false);
                    if (plId == null)
                    {
                        await e.Channel.SendMessage("No search results for that query.");
                        return;
                    }
                    var ids = await SearchHelper.GetVideoIDs(plId, 500).ConfigureAwait(false);
                    if (ids == null || ids.Count == 0)
                    {
                        await e.Channel.SendMessage($"🎵 `Failed to find any songs.`").ConfigureAwait(false);
                        return;
                    }
                    var idArray = ids as string[] ?? ids.ToArray();
                    var count   = idArray.Length;
                    var msg     =
                        await e.Channel.SendMessage($"🎵 `Attempting to queue {count} songs".SnPl(count) + "...`").ConfigureAwait(false);
                    foreach (var id in idArray)
                    {
                        try
                        {
                            await QueueSong(e.User, e.Channel, e.User.VoiceChannel, id, true).ConfigureAwait(false);
                        }
                        catch (PlaylistFullException)
                        { break; }
                        catch { }
                    }
                    await msg.Edit("🎵 `Playlist queue complete.`").ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "soundcloudpl")
                .Alias(Prefix + "scpl")
                .Description($"Queue a soundcloud playlist using a link. | `{Prefix}scpl soundcloudseturl`")
                .Parameter("pl", ParameterType.Unparsed)
                .Do(async e =>
                {
                    var pl = e.GetArg("pl")?.Trim();

                    if (string.IsNullOrWhiteSpace(pl))
                    {
                        return;
                    }

                    var scvids = JObject.Parse(await SearchHelper.GetResponseStringAsync($"http://api.soundcloud.com/resolve?url={pl}&client_id={WizBot.Creds.SoundCloudClientID}").ConfigureAwait(false))["tracks"].ToObject <SoundCloudVideo[]>();
                    await QueueSong(e.User, e.Channel, e.User.VoiceChannel, scvids[0].TrackLink).ConfigureAwait(false);

                    MusicPlayer mp;
                    if (!MusicPlayers.TryGetValue(e.Server, out mp))
                    {
                        return;
                    }

                    foreach (var svideo in scvids.Skip(1))
                    {
                        try
                        {
                            mp.AddSong(new Song(new Classes.SongInfo
                            {
                                Title        = svideo.FullName,
                                Provider     = "SoundCloud",
                                Uri          = svideo.StreamLink,
                                ProviderType = MusicType.Normal,
                                Query        = svideo.TrackLink,
                            }), e.User.Name);
                        }
                        catch (PlaylistFullException) { break; }
                    }
                });

                cgb.CreateCommand(Prefix + "localplaylst")
                .Alias(Prefix + "lopl")
                .Description($"Queues all songs from a directory. **Bot Owner Only!** | `{Prefix}lopl C:/music/classical`")
                .Parameter("directory", ParameterType.Unparsed)
                .AddCheck(SimpleCheckers.OwnerOnly())
                .Do(async e =>
                {
                    var arg = e.GetArg("directory");
                    if (string.IsNullOrWhiteSpace(arg))
                    {
                        return;
                    }
                    try
                    {
                        var fileEnum = new DirectoryInfo(arg).GetFiles()
                                       .Where(x => !x.Attributes.HasFlag(FileAttributes.Hidden | FileAttributes.System));
                        foreach (var file in fileEnum)
                        {
                            try
                            {
                                await QueueSong(e.User, e.Channel, e.User.VoiceChannel, file.FullName, true, MusicType.Local).ConfigureAwait(false);
                            }
                            catch (PlaylistFullException)
                            {
                                break;
                            }
                            catch { }
                        }
                        await e.Channel.SendMessage("🎵 `Directory queue complete.`").ConfigureAwait(false);
                    }
                    catch { }
                });

                cgb.CreateCommand(Prefix + "radio").Alias(Prefix + "ra")
                .Description($"Queues a radio stream from a link. It can be a direct mp3 radio stream, .m3u, .pls .asx or .xspf (Usage Video: <https://streamable.com/al54>) | `{Prefix}ra radio link here`")
                .Parameter("radio_link", ParameterType.Required)
                .Do(async e =>
                {
                    if (e.User.VoiceChannel?.Server != e.Server)
                    {
                        await e.Channel.SendMessage("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining it.").ConfigureAwait(false);
                        return;
                    }
                    await QueueSong(e.User, e.Channel, e.User.VoiceChannel, e.GetArg("radio_link"), musicType: MusicType.Radio).ConfigureAwait(false);
                    if (e.Server.CurrentUser.GetPermissions(e.Channel).ManageMessages)
                    {
                        await Task.Delay(10000).ConfigureAwait(false);
                        await e.Message.Delete().ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "local")
                .Alias(Prefix + "lo")
                .Description($"Queues a local file by specifying a full path. **Bot Owner Only!** | `{Prefix}lo C:/music/mysong.mp3`")
                .Parameter("path", ParameterType.Unparsed)
                .AddCheck(SimpleCheckers.OwnerOnly())
                .Do(async e =>
                {
                    var arg = e.GetArg("path");
                    if (string.IsNullOrWhiteSpace(arg))
                    {
                        return;
                    }
                    await QueueSong(e.User, e.Channel, e.User.VoiceChannel, e.GetArg("path"), musicType: MusicType.Local).ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "move")
                .Alias(Prefix + "mv")
                .Description($"Moves the bot to your voice channel. (works only if music is already playing) | `{Prefix}mv`")
                .Do(e =>
                {
                    MusicPlayer musicPlayer;
                    var voiceChannel = e.User.VoiceChannel;
                    if (voiceChannel == null || voiceChannel.Server != e.Server || !MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        return;
                    }
                    musicPlayer.MoveToVoiceChannel(voiceChannel);
                });

                cgb.CreateCommand(Prefix + "remove")
                .Alias(Prefix + "rm")
                .Description($"Remove a song by its # in the queue, or 'all' to remove whole queue. | `{Prefix}rm 5`")
                .Parameter("num", ParameterType.Required)
                .Do(async e =>
                {
                    var arg = e.GetArg("num");
                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        return;
                    }
                    if (e.User.VoiceChannel != musicPlayer.PlaybackVoiceChannel)
                    {
                        return;
                    }
                    if (arg?.ToLower() == "all")
                    {
                        musicPlayer.ClearQueue();
                        await e.Channel.SendMessage($"🎵`Queue cleared!`").ConfigureAwait(false);
                        return;
                    }
                    int num;
                    if (!int.TryParse(arg, out num))
                    {
                        return;
                    }
                    if (num <= 0 || num > musicPlayer.Playlist.Count)
                    {
                        return;
                    }
                    var song = (musicPlayer.Playlist as List <Song>)?[num - 1];
                    musicPlayer.RemoveSongAt(num - 1);
                    await e.Channel.SendMessage($"🎵**Track {song.PrettyName} at position `#{num}` has been removed.**").ConfigureAwait(false);
                });

                //var msRegex = new Regex(@"(?<n1>\d+)>(?<n2>\d+)", RegexOptions.Compiled);
                cgb.CreateCommand(Prefix + "movesong")
                .Alias(Prefix + "ms")
                .Description($"Moves a song from one position to another. | `{Prefix} ms 5>3`")
                .Parameter("fromto")
                .Do(async e =>
                {
                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        return;
                    }
                    var fromto    = e.GetArg("fromto").Trim();
                    var fromtoArr = fromto.Split('>');

                    int n1;
                    int n2;

                    var playlist = musicPlayer.Playlist as List <Song> ?? musicPlayer.Playlist.ToList();

                    if (fromtoArr.Length != 2 || !int.TryParse(fromtoArr[0], out n1) ||
                        !int.TryParse(fromtoArr[1], out n2) || n1 <1 || n2 <1 || n1 == n2 ||
                                                                            n1> playlist.Count || n2> playlist.Count)
                    {
                        await e.Channel.SendMessage("`Invalid input.`").ConfigureAwait(false);
                        return;
                    }

                    var s = playlist[n1 - 1];
                    playlist.Insert(n2 - 1, s);
                    var nn1 = n2 < n1 ? n1 : n1 - 1;
                    playlist.RemoveAt(nn1);

                    await e.Channel.SendMessage($"🎵`Moved` {s.PrettyName} `from #{n1} to #{n2}`").ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "setmaxqueue")
                .Alias(Prefix + "smq")
                .Description($"Sets a maximum queue size. Supply 0 or no argument to have no limit.  | `{Prefix}smq 50` or `{Prefix}smq`")
                .Parameter("size", ParameterType.Unparsed)
                .Do(async e =>
                {
                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        return;
                    }

                    var sizeStr = e.GetArg("size")?.Trim();
                    uint size   = 0;
                    if (string.IsNullOrWhiteSpace(sizeStr) || !uint.TryParse(sizeStr, out size))
                    {
                        size = 0;
                    }

                    musicPlayer.MaxQueueSize = size;
                    await e.Channel.SendMessage($"🎵 `Max queue set to {(size == 0 ? ("unlimited") : size + " tracks")}`");
                });

                cgb.CreateCommand(Prefix + "cleanup")
                .Description($"Cleans up hanging voice connections. **Bot Owner Only!** | `{Prefix}cleanup`")
                .AddCheck(SimpleCheckers.OwnerOnly())
                .Do(e =>
                {
                    foreach (var kvp in MusicPlayers)
                    {
                        var songs       = kvp.Value.Playlist;
                        var currentSong = kvp.Value.CurrentSong;
                        if (songs.Count == 0 && currentSong == null)
                        {
                            MusicPlayer throwaway;
                            MusicPlayers.TryRemove(kvp.Key, out throwaway);
                            throwaway.Destroy();
                        }
                    }
                });

                cgb.CreateCommand(Prefix + "reptcursong")
                .Alias(Prefix + "rcs")
                .Description($"Toggles repeat of current song. | `{Prefix}rcs`")
                .Do(async e =>
                {
                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        return;
                    }
                    var currentSong = musicPlayer.CurrentSong;
                    if (currentSong == null)
                    {
                        return;
                    }
                    var currentValue = musicPlayer.ToggleRepeatSong();
                    await e.Channel.SendMessage(currentValue ?
                                                $"🎵🔂`Repeating track:`{currentSong.PrettyName}" :
                                                $"🎵🔂`Current track repeat stopped.`")
                    .ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "rpeatplaylst")
                .Alias(Prefix + "rpl")
                .Description($"Toggles repeat of all songs in the queue (every song that finishes is added to the end of the queue). | `{Prefix}rpl`")
                .Do(async e =>
                {
                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        return;
                    }
                    var currentValue = musicPlayer.ToggleRepeatPlaylist();
                    await e.Channel.SendMessage($"🎵🔁`Repeat playlist {(currentValue ? "enabled" : "disabled")}`").ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "save")
                .Description($"Saves a playlist under a certain name. Name must be no longer than 20 characters and mustn't contain dashes. | `{Prefix}save classical1`")
                .Parameter("name", ParameterType.Unparsed)
                .Do(async e =>
                {
                    var name = e.GetArg("name")?.Trim();

                    if (string.IsNullOrWhiteSpace(name) ||
                        name.Length > 20 ||
                        name.Contains("-"))
                    {
                        return;
                    }

                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        return;
                    }

                    //to avoid concurrency issues
                    var currentPlaylist = new List <Song>(musicPlayer.Playlist);
                    var curSong         = musicPlayer.CurrentSong;
                    if (curSong != null)
                    {
                        currentPlaylist.Insert(0, curSong);
                    }

                    if (!currentPlaylist.Any())
                    {
                        return;
                    }


                    var songInfos = currentPlaylist.Select(s => new DataModels.SongInfo
                    {
                        Provider     = s.SongInfo.Provider,
                        ProviderType = (int)s.SongInfo.ProviderType,
                        Title        = s.SongInfo.Title,
                        Uri          = s.SongInfo.Uri,
                        Query        = s.SongInfo.Query,
                    }).ToList();

                    var playlist = new MusicPlaylist
                    {
                        CreatorId   = (long)e.User.Id,
                        CreatorName = e.User.Name,
                        Name        = name.ToLowerInvariant(),
                    };
                    DbHandler.Instance.SaveAll(songInfos);
                    DbHandler.Instance.Save(playlist);
                    DbHandler.Instance.Connection.InsertAll(songInfos.Select(s => new PlaylistSongInfo
                    {
                        PlaylistId = playlist.Id.Value,
                        SongInfoId = s.Id.Value
                    }), typeof(PlaylistSongInfo));

                    await e.Channel.SendMessage($"🎵 `Saved playlist as {name}-{playlist.Id}`").ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "load")
                .Description($"Loads a playlist under a certain name.  | `{Prefix}load classical-1`")
                .Parameter("name", ParameterType.Unparsed)
                .Do(async e =>
                {
                    var voiceCh = e.User.VoiceChannel;
                    var textCh  = e.Channel;
                    if (voiceCh == null || voiceCh.Server != textCh.Server)
                    {
                        await textCh.SendMessage("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining.").ConfigureAwait(false);
                        return;
                    }
                    var name = e.GetArg("name")?.Trim().ToLowerInvariant();

                    if (string.IsNullOrWhiteSpace(name))
                    {
                        return;
                    }

                    var parts = name.Split('-');
                    if (parts.Length != 2)
                    {
                        return;
                    }
                    var playlistName = parts[0];

                    int playlistNumber;
                    if (!int.TryParse(parts[1], out playlistNumber))
                    {
                        return;
                    }

                    var playlist = DbHandler.Instance.FindOne <MusicPlaylist>(
                        p => p.Id == playlistNumber);

                    if (playlist == null)
                    {
                        await e.Channel.SendMessage("Can't find playlist under that name.").ConfigureAwait(false);
                        return;
                    }

                    var psis = DbHandler.Instance.FindAll <PlaylistSongInfo>(psi =>
                                                                             psi.PlaylistId == playlist.Id);

                    var songInfos = psis.Select(psi => DbHandler.Instance
                                                .FindOne <DataModels.SongInfo>(si => si.Id == psi.SongInfoId));

                    await e.Channel.SendMessage($"`Attempting to load {songInfos.Count()} songs`").ConfigureAwait(false);
                    foreach (var si in songInfos)
                    {
                        try
                        {
                            await QueueSong(e.User, textCh, voiceCh, si.Query, true, (MusicType)si.ProviderType).ConfigureAwait(false);
                        }
                        catch (PlaylistFullException)
                        {
                            break;
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"Failed QueueSong in load playlist. {ex}");
                        }
                    }
                });

                cgb.CreateCommand(Prefix + "playlists")
                .Alias(Prefix + "pls")
                .Description($"Lists all playlists. Paginated. 20 per page. Default page is 0. |`{Prefix}pls 1`")
                .Parameter("num", ParameterType.Optional)
                .Do(e =>
                {
                    int num = 0;
                    int.TryParse(e.GetArg("num"), out num);
                    if (num < 0)
                    {
                        return;
                    }
                    var result = DbHandler.Instance.GetPlaylistData(num);
                    if (result.Count == 0)
                    {
                        e.Channel.SendMessage($"`No saved playlists found on page {num}`").ConfigureAwait(false);
                    }
                    else
                    {
                        e.Channel.SendMessage($"```js\n--- List of saved playlists ---\n\n" + string.Join("\n", result.Select(r => $"'{r.Name}-{r.Id}' by {r.Creator} ({r.SongCnt} songs)")) + $"\n\n        --- Page {num} ---```").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "deleteplaylist")
                .Alias(Prefix + "delpls")
                .Description($"Deletes a saved playlist. Only if you made it or if you are the bot owner. | `{Prefix}delpls animu-5`")
                .Parameter("pl", ParameterType.Required)
                .Do(async e =>
                {
                    var pl = e.GetArg("pl").Trim().Split('-')[1];
                    if (string.IsNullOrWhiteSpace(pl))
                    {
                        return;
                    }
                    var plnum = int.Parse(pl);
                    if (WizBot.IsOwner(e.User.Id))
                    {
                        DbHandler.Instance.Delete <MusicPlaylist>(plnum);
                    }
                    else
                    {
                        DbHandler.Instance.DeleteWhere <MusicPlaylist>(mp => mp.Id == plnum && (long)e.User.Id == mp.CreatorId);
                    }
                    await e.Channel.SendMessage("`Ok.` :ok:").ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "goto")
                .Description($"Goes to a specific time in seconds in a song. | `{Prefix}goto 30`")
                .Parameter("time")
                .Do(async e =>
                {
                    var skipToStr = e.GetArg("time")?.Trim();
                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        return;
                    }
                    if (e.User.VoiceChannel != musicPlayer.PlaybackVoiceChannel)
                    {
                        return;
                    }
                    int skipTo;
                    if (!int.TryParse(skipToStr, out skipTo) || skipTo < 0)
                    {
                        return;
                    }

                    var currentSong = musicPlayer.CurrentSong;

                    if (currentSong == null)
                    {
                        return;
                    }

                    //currentSong.PrintStatusMessage = false;
                    var gotoSong    = currentSong.Clone();
                    gotoSong.SkipTo = skipTo;
                    musicPlayer.AddSong(gotoSong, 0);
                    musicPlayer.Next();

                    var minutes = (skipTo / 60).ToString();
                    var seconds = (skipTo % 60).ToString();

                    if (minutes.Length == 1)
                    {
                        minutes = "0" + minutes;
                    }
                    if (seconds.Length == 1)
                    {
                        seconds = "0" + seconds;
                    }

                    await e.Channel.SendMessage($"`Skipped to {minutes}:{seconds}`").ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "getlink")
                .Alias(Prefix + "gl")
                .Description($"Shows a link to the song in the queue by index, or the currently playing song by default. | `{Prefix}gl`")
                .Parameter("index", ParameterType.Optional)
                .Do(async e =>
                {
                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        return;
                    }
                    int index;
                    string arg = e.GetArg("index")?.Trim();
                    if (!string.IsNullOrEmpty(arg) && int.TryParse(arg, out index))
                    {
                        var selSong = musicPlayer.Playlist.DefaultIfEmpty(null).ElementAtOrDefault(index - 1);
                        if (selSong == null)
                        {
                            await e.Channel.SendMessage("Could not select song, likely wrong index");
                        }
                        else
                        {
                            await e.Channel.SendMessage($"🎶`Selected song {selSong.SongInfo.Title}:` <{selSong.SongInfo.Query}>").ConfigureAwait(false);
                        }
                    }
                    else
                    {
                        var curSong = musicPlayer.CurrentSong;
                        if (curSong == null)
                        {
                            return;
                        }
                        await e.Channel.SendMessage($"🎶`Current song:` <{curSong.SongInfo.Query}>").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "autoplay")
                .Alias(Prefix + "ap")
                .Description($"Toggles autoplay - When the song is finished, automatically queue a related youtube song. (Works only for youtube songs and when queue is empty) | `{Prefix}ap`")
                .Do(async e =>
                {
                    MusicPlayer musicPlayer;
                    if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
                    {
                        return;
                    }

                    if (!musicPlayer.ToggleAutoplay())
                    {
                        await e.Channel.SendMessage("🎶`Autoplay disabled.`").ConfigureAwait(false);
                    }
                    else
                    {
                        await e.Channel.SendMessage("🎶`Autoplay enabled.`").ConfigureAwait(false);
                    }
                });
            });
        }
Beispiel #6
0
        public override void Install(ModuleManager manager)
        {
            manager.CreateCommands("", cgb =>
            {
                cgb.AddCheck(PermissionChecker.Instance);

                var client = manager.Client;

                commands.ForEach(cmd => cmd.Init(cgb));

                cgb.CreateCommand(Prefix + "delmsgoncmd")
                .Description($"Toggles the automatic deletion of user's successful command message to prevent chat flood. **Server Manager Only.** | `{Prefix}delmsgoncmd`")
                .AddCheck(SimpleCheckers.ManageServer())
                .Do(async e =>
                {
                    var conf = SpecificConfigurations.Default.Of(e.Server.Id);
                    conf.AutoDeleteMessagesOnCommand = !conf.AutoDeleteMessagesOnCommand;
                    await Classes.JSONModels.ConfigHandler.SaveConfig().ConfigureAwait(false);
                    if (conf.AutoDeleteMessagesOnCommand)
                    {
                        await e.Channel.SendMessage("❗`Now automatically deleting successful command invokations.`");
                    }
                    else
                    {
                        await e.Channel.SendMessage("❗`Stopped automatic deletion of successful command invokations.`");
                    }
                });

                cgb.CreateCommand(Prefix + "restart")
                .Description($"Restarts the bot. Might not work. **Bot Owner Only** | `{Prefix}restart`")
                .AddCheck(SimpleCheckers.OwnerOnly())
                .Do(async e =>
                {
                    await e.Channel.SendMessage("`Restarting in 2 seconds...`");
                    await Task.Delay(2000);
                    System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location);
                    Environment.Exit(0);
                });

                cgb.CreateCommand(Prefix + "setrole").Alias(Prefix + "sr")
                .Description($"Sets a role for a given user. **Needs Manage Roles Permissions.**| `{Prefix}sr @User Guest`")
                .Parameter("user_name", ParameterType.Required)
                .Parameter("role_name", ParameterType.Unparsed)
                .AddCheck(SimpleCheckers.CanManageRoles)
                .Do(async e =>
                {
                    var userName = e.GetArg("user_name");
                    var roleName = e.GetArg("role_name");

                    if (string.IsNullOrWhiteSpace(roleName))
                    {
                        return;
                    }

                    if (!e.User.ServerPermissions.ManageRoles)
                    {
                        await e.Channel.SendMessage("You have insufficient permissions.").ConfigureAwait(false);
                    }

                    var usr = e.Server.FindUsers(userName).FirstOrDefault();
                    if (usr == null)
                    {
                        await e.Channel.SendMessage("You failed to supply a valid username").ConfigureAwait(false);
                        return;
                    }

                    var role = e.Server.FindRoles(roleName).FirstOrDefault();
                    if (role == null)
                    {
                        await e.Channel.SendMessage("You failed to supply a valid role").ConfigureAwait(false);
                        return;
                    }

                    try
                    {
                        await usr.AddRoles(role).ConfigureAwait(false);
                        await e.Channel.SendMessage($"Successfully added role **{role.Name}** to user **{usr.Name}**").ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        await e.Channel.SendMessage("Failed to add roles. Bot has insufficient permissions.\n").ConfigureAwait(false);
                        Console.WriteLine(ex.ToString());
                    }
                });

                cgb.CreateCommand(Prefix + "removerole").Alias(Prefix + "rr")
                .Description($"Removes a role from a given user. **Needs Manage Roles Permissions.**| `{Prefix}rr @User Admin`")
                .Parameter("user_name", ParameterType.Required)
                .Parameter("role_name", ParameterType.Unparsed)
                .AddCheck(SimpleCheckers.CanManageRoles)
                .Do(async e =>
                {
                    var userName = e.GetArg("user_name");
                    var roleName = e.GetArg("role_name");

                    if (string.IsNullOrWhiteSpace(roleName))
                    {
                        return;
                    }

                    var usr = e.Server.FindUsers(userName).FirstOrDefault();
                    if (usr == null)
                    {
                        await e.Channel.SendMessage("You failed to supply a valid username").ConfigureAwait(false);
                        return;
                    }

                    var role = e.Server.FindRoles(roleName).FirstOrDefault();
                    if (role == null)
                    {
                        await e.Channel.SendMessage("You failed to supply a valid role").ConfigureAwait(false);
                        return;
                    }

                    try
                    {
                        await usr.RemoveRoles(role).ConfigureAwait(false);
                        await e.Channel.SendMessage($"Successfully removed role **{role.Name}** from user **{usr.Name}**").ConfigureAwait(false);
                    }
                    catch
                    {
                        await e.Channel.SendMessage("Failed to remove roles. Most likely reason: Insufficient permissions.").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "renamerole")
                .Alias(Prefix + "renr")
                .Description($"Renames a role. Roles you are renaming must be lower than bot's highest role. **Manage Roles Permissions.** | `{Prefix}renr \"First role\" SecondRole`")
                .Parameter("r1", ParameterType.Required)
                .Parameter("r2", ParameterType.Required)
                .AddCheck(new SimpleCheckers.ManageRoles())
                .Do(async e =>
                {
                    var r1 = e.GetArg("r1").Trim();
                    var r2 = e.GetArg("r2").Trim();

                    var roleToEdit = e.Server.FindRoles(r1).FirstOrDefault();
                    if (roleToEdit == null)
                    {
                        await e.Channel.SendMessage("Can't find that role.").ConfigureAwait(false);
                        return;
                    }

                    try
                    {
                        if (roleToEdit.Position > e.Server.CurrentUser.Roles.Max(r => r.Position))
                        {
                            await e.Channel.SendMessage("I can't edit roles higher than my highest role.").ConfigureAwait(false);
                            return;
                        }
                        await roleToEdit.Edit(r2);
                        await e.Channel.SendMessage("Role renamed.").ConfigureAwait(false);
                    }
                    catch (Exception)
                    {
                        await e.Channel.SendMessage("Failed to rename role. Probably insufficient permissions.").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "removeallroles").Alias(Prefix + "rar")
                .Description($"Removes all roles from a mentioned user. **Needs Manage Roles Permissions.**| `{Prefix}rar @User`")
                .Parameter("user_name", ParameterType.Unparsed)
                .AddCheck(SimpleCheckers.CanManageRoles)
                .Do(async e =>
                {
                    var userName = e.GetArg("user_name");

                    var usr = e.Server.FindUsers(userName).FirstOrDefault();
                    if (usr == null)
                    {
                        await e.Channel.SendMessage("You failed to supply a valid username").ConfigureAwait(false);
                        return;
                    }

                    try
                    {
                        await usr.RemoveRoles(usr.Roles.ToArray()).ConfigureAwait(false);
                        await e.Channel.SendMessage($"Successfully removed **all** roles from user **{usr.Name}**").ConfigureAwait(false);
                    }
                    catch
                    {
                        await e.Channel.SendMessage("Failed to remove roles. Most likely reason: Insufficient permissions.").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "createrole").Alias(Prefix + "cr")
                .Description($"Creates a role with a given name. **Needs Manage Roles Permissions.**| `{Prefix}cr Awesome Role`")
                .Parameter("role_name", ParameterType.Unparsed)
                .AddCheck(SimpleCheckers.CanManageRoles)
                .Do(async e =>
                {
                    if (string.IsNullOrWhiteSpace(e.GetArg("role_name")))
                    {
                        return;
                    }
                    try
                    {
                        var r = await e.Server.CreateRole(e.GetArg("role_name")).ConfigureAwait(false);
                        await e.Channel.SendMessage($"Successfully created role **{r.Name}**.").ConfigureAwait(false);
                    }
                    catch (Exception)
                    {
                        await e.Channel.SendMessage(":warning: Unspecified error.").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "rolecolor").Alias(Prefix + "rc")
                .Parameter("role_name", ParameterType.Required)
                .Parameter("r", ParameterType.Optional)
                .Parameter("g", ParameterType.Optional)
                .Parameter("b", ParameterType.Optional)
                .Description($"Set a role's color to the hex or 0-255 rgb color value provided. **Needs Manage Roles Permissions.** | `{Prefix}rc Admin 255 200 100` or `{Prefix}rc Admin ffba55`")
                .Do(async e =>
                {
                    if (!e.User.ServerPermissions.ManageRoles)
                    {
                        await e.Channel.SendMessage("You don't have permission to use this!").ConfigureAwait(false);
                        return;
                    }

                    var args = e.Args.Where(s => s != string.Empty);

                    if (args.Count() != 2 && args.Count() != 4)
                    {
                        await e.Channel.SendMessage("The parameters are invalid.").ConfigureAwait(false);
                        return;
                    }

                    var role = e.Server.FindRoles(e.Args[0]).FirstOrDefault();

                    if (role == null)
                    {
                        await e.Channel.SendMessage("That role does not exist.").ConfigureAwait(false);
                        return;
                    }
                    try
                    {
                        var rgb  = args.Count() == 4;
                        var arg1 = e.Args[1].Replace("#", "");

                        var red   = Convert.ToByte(rgb ? int.Parse(arg1) : Convert.ToInt32(arg1.Substring(0, 2), 16));
                        var green = Convert.ToByte(rgb ? int.Parse(e.Args[2]) : Convert.ToInt32(arg1.Substring(2, 2), 16));
                        var blue  = Convert.ToByte(rgb ? int.Parse(e.Args[3]) : Convert.ToInt32(arg1.Substring(4, 2), 16));

                        await role.Edit(color: new Color(red, green, blue)).ConfigureAwait(false);
                        await e.Channel.SendMessage($"Role {role.Name}'s color has been changed.").ConfigureAwait(false);
                    }
                    catch (Exception)
                    {
                        await e.Channel.SendMessage("Error occured, most likely invalid parameters or insufficient permissions.").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "ban").Alias(Prefix + "b")
                .Parameter("user", ParameterType.Required)
                .Parameter("msg", ParameterType.Unparsed)
                .Description($"Bans a user by id or name with an optional message. **Needs Ban Permissions.**| `{Prefix}b \"@some Guy\" Your behaviour is toxic.`")
                .Do(async e =>
                {
                    var msg  = e.GetArg("msg");
                    var user = e.GetArg("user");
                    if (e.User.ServerPermissions.BanMembers)
                    {
                        var usr = e.Server.FindUsers(user).FirstOrDefault();
                        if (usr == null)
                        {
                            await e.Channel.SendMessage("User not found.").ConfigureAwait(false);
                            return;
                        }
                        if (!string.IsNullOrWhiteSpace(msg))
                        {
                            await usr.SendMessage($"**You have been BANNED from `{e.Server.Name}` server.**\n" +
                                                  $"Reason: {msg}").ConfigureAwait(false);
                            await Task.Delay(2000).ConfigureAwait(false);         // temp solution; give time for a message to be send, fu volt
                        }
                        try
                        {
                            await e.Server.Ban(usr, 7).ConfigureAwait(false);

                            await e.Channel.SendMessage("Banned user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false);
                        }
                        catch
                        {
                            await e.Channel.SendMessage("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false);
                        }
                    }
                });

                cgb.CreateCommand(Prefix + "softban").Alias(Prefix + "sb")
                .Parameter("user", ParameterType.Required)
                .Parameter("msg", ParameterType.Unparsed)
                .Description($"Bans and then unbans a user by id or name with an optional message. **Needs Ban Permissions.**| `{Prefix}sb \"@some Guy\" Your behaviour is toxic.`")
                .Do(async e =>
                {
                    var msg  = e.GetArg("msg");
                    var user = e.GetArg("user");
                    if (e.User.ServerPermissions.BanMembers)
                    {
                        var usr = e.Server.FindUsers(user).FirstOrDefault();
                        if (usr == null)
                        {
                            await e.Channel.SendMessage("User not found.").ConfigureAwait(false);
                            return;
                        }
                        if (!string.IsNullOrWhiteSpace(msg))
                        {
                            await usr.SendMessage($"**You have been SOFT-BANNED from `{e.Server.Name}` server.**\n" +
                                                  $"Reason: {msg}").ConfigureAwait(false);
                            await Task.Delay(2000).ConfigureAwait(false);         // temp solution; give time for a message to be send, fu volt
                        }
                        try
                        {
                            await e.Server.Ban(usr, 7).ConfigureAwait(false);
                            await e.Server.Unban(usr).ConfigureAwait(false);

                            await e.Channel.SendMessage("Soft-Banned user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false);
                        }
                        catch
                        {
                            await e.Channel.SendMessage("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false);
                        }
                    }
                });

                cgb.CreateCommand(Prefix + "kick").Alias(Prefix + "k")
                .Parameter("user")
                .Parameter("msg", ParameterType.Unparsed)
                .Description($"Kicks a mentioned user. **Needs Kick Permissions.**| `{Prefix}k \"@some Guy\" Your behaviour is toxic.`")
                .Do(async e =>
                {
                    var msg  = e.GetArg("msg");
                    var user = e.GetArg("user");
                    if (e.User.ServerPermissions.KickMembers)
                    {
                        var usr = e.Server.FindUsers(user).FirstOrDefault();
                        if (usr == null)
                        {
                            await e.Channel.SendMessage("User not found.").ConfigureAwait(false);
                            return;
                        }
                        if (!string.IsNullOrWhiteSpace(msg))
                        {
                            await usr.SendMessage($"**You have been KICKED from `{e.Server.Name}` server.**\n" +
                                                  $"Reason: {msg}").ConfigureAwait(false);
                            await Task.Delay(2000).ConfigureAwait(false);     // temp solution; give time for a message to be send, fu volt
                        }
                        try
                        {
                            await usr.Kick().ConfigureAwait(false);
                            await e.Channel.SendMessage("Kicked user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false);
                        }
                        catch
                        {
                            await e.Channel.SendMessage("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false);
                        }
                    }
                });
                cgb.CreateCommand(Prefix + "mute")
                .Description($"Mutes mentioned user or users. **Needs Mute Permissions.**| `{Prefix}mute \"@Someguy\"` or `{Prefix}mute \"@Someguy\" \"@Someguy\"`")
                .Parameter("throwaway", ParameterType.Unparsed)
                .Do(async e =>
                {
                    if (!e.User.ServerPermissions.MuteMembers)
                    {
                        await e.Channel.SendMessage("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
                        return;
                    }
                    if (!e.Message.MentionedUsers.Any())
                    {
                        return;
                    }
                    try
                    {
                        foreach (var u in e.Message.MentionedUsers)
                        {
                            await u.Edit(isMuted: true).ConfigureAwait(false);
                        }
                        await e.Channel.SendMessage("Mute successful").ConfigureAwait(false);
                    }
                    catch
                    {
                        await e.Channel.SendMessage("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "unmute")
                .Description($"Unmutes mentioned user or users. **Needs Mute Permissions.**| `{Prefix}unmute \"@Someguy\"` or `{Prefix}unmute \"@Someguy\" \"@Someguy\"`")
                .Parameter("throwaway", ParameterType.Unparsed)
                .Do(async e =>
                {
                    if (!e.User.ServerPermissions.MuteMembers)
                    {
                        await e.Channel.SendMessage("You do not have permission to do that.").ConfigureAwait(false);
                        return;
                    }
                    if (!e.Message.MentionedUsers.Any())
                    {
                        return;
                    }
                    try
                    {
                        foreach (var u in e.Message.MentionedUsers)
                        {
                            await u.Edit(isMuted: false).ConfigureAwait(false);
                        }
                        await e.Channel.SendMessage("Unmute successful").ConfigureAwait(false);
                    }
                    catch
                    {
                        await e.Channel.SendMessage("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "deafen")
                .Alias(Prefix + "deaf")
                .Description($"Deafens mentioned user or users. **Needs Deafen Permissions.**| `{Prefix}deaf \"@Someguy\"` or `{Prefix}deaf \"@Someguy\" \"@Someguy\"`")
                .Parameter("throwaway", ParameterType.Unparsed)
                .Do(async e =>
                {
                    if (!e.User.ServerPermissions.DeafenMembers)
                    {
                        await e.Channel.SendMessage("You do not have permission to do that.").ConfigureAwait(false);
                        return;
                    }
                    if (!e.Message.MentionedUsers.Any())
                    {
                        return;
                    }
                    try
                    {
                        foreach (var u in e.Message.MentionedUsers)
                        {
                            await u.Edit(isDeafened: true).ConfigureAwait(false);
                        }
                        await e.Channel.SendMessage("Deafen successful").ConfigureAwait(false);
                    }
                    catch
                    {
                        await e.Channel.SendMessage("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "undeafen")
                .Alias(Prefix + "undef")
                .Description($"Undeafens mentioned user or users. **Needs Deafen Permissions.** | `{Prefix}undef \"@Someguy\"` or `{Prefix}undef \"@Someguy\" \"@Someguy\"`")
                .Parameter("throwaway", ParameterType.Unparsed)
                .Do(async e =>
                {
                    if (!e.User.ServerPermissions.DeafenMembers)
                    {
                        await e.Channel.SendMessage("You do not have permission to do that.").ConfigureAwait(false);
                        return;
                    }
                    if (!e.Message.MentionedUsers.Any())
                    {
                        return;
                    }
                    try
                    {
                        foreach (var u in e.Message.MentionedUsers)
                        {
                            await u.Edit(isDeafened: false).ConfigureAwait(false);
                        }
                        await e.Channel.SendMessage("Undeafen successful").ConfigureAwait(false);
                    }
                    catch
                    {
                        await e.Channel.SendMessage("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "delvoichanl")
                .Alias(Prefix + "dvch")
                .Description($"Deletes a voice channel with a given name. **Needs Manage Channel Permissions.**| `{Prefix}dvch VoiceChannelName`")
                .Parameter("channel_name", ParameterType.Required)
                .Do(async e =>
                {
                    try
                    {
                        if (e.User.ServerPermissions.ManageChannels)
                        {
                            var ch = e.Server.FindChannels(e.GetArg("channel_name"), ChannelType.Voice).FirstOrDefault();
                            if (ch == null)
                            {
                                return;
                            }
                            await ch.Delete().ConfigureAwait(false);
                            await e.Channel.SendMessage($"Removed channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false);
                        }
                    }
                    catch
                    {
                        await e.Channel.SendMessage("Insufficient permissions.");
                    }
                });

                cgb.CreateCommand(Prefix + "creatvoichanl")
                .Alias(Prefix + "cvch")
                .Description($"Creates a new voice channel with a given name. **Needs Manage Channel Permissions.** | `{Prefix}cvch VoiceChannelName`")
                .Parameter("channel_name", ParameterType.Required)
                .Do(async e =>
                {
                    try
                    {
                        if (e.User.ServerPermissions.ManageChannels)
                        {
                            await e.Server.CreateChannel(e.GetArg("channel_name"), ChannelType.Voice).ConfigureAwait(false);
                            await e.Channel.SendMessage($"Created voice channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false);
                        }
                    }
                    catch
                    {
                        await e.Channel.SendMessage("Insufficient permissions.").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "deltxtchanl")
                .Alias(Prefix + "dtch")
                .Description($"Deletes a text channel with a given name. **Needs Manage Channel Permissions.** | `{Prefix}dtch TextChannelName`")
                .Parameter("channel_name", ParameterType.Required)
                .Do(async e =>
                {
                    try
                    {
                        if (e.User.ServerPermissions.ManageChannels)
                        {
                            var channel = e.Server.FindChannels(e.GetArg("channel_name"), ChannelType.Text).FirstOrDefault();
                            if (channel == null)
                            {
                                return;
                            }
                            await channel.Delete().ConfigureAwait(false);
                            await e.Channel.SendMessage($"Removed text channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false);
                        }
                    }
                    catch
                    {
                        await e.Channel.SendMessage("Insufficient permissions.").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "creatxtchanl")
                .Alias(Prefix + "ctch")
                .Description($"Creates a new text channel with a given name. **Needs Manage Channel Permissions.** | `{Prefix}ctch TextChannelName`")
                .Parameter("channel_name", ParameterType.Required)
                .Do(async e =>
                {
                    try
                    {
                        if (e.User.ServerPermissions.ManageChannels)
                        {
                            await e.Server.CreateChannel(e.GetArg("channel_name"), ChannelType.Text).ConfigureAwait(false);
                            await e.Channel.SendMessage($"Added text channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false);
                        }
                    }
                    catch
                    {
                        await e.Channel.SendMessage("Insufficient permissions.").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "settopic")
                .Alias(Prefix + "st")
                .Description($"Sets a topic on the current channel. **Needs Manage Channel Permissions.** | `{Prefix}st My new topic`")
                .AddCheck(SimpleCheckers.ManageChannels())
                .Parameter("topic", ParameterType.Unparsed)
                .Do(async e =>
                {
                    var topic = e.GetArg("topic")?.Trim() ?? "";
                    await e.Channel.Edit(topic: topic).ConfigureAwait(false);
                    await e.Channel.SendMessage(":ok: **New channel topic set.**").ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "setchanlname")
                .Alias(Prefix + "schn")
                .Description($"Changed the name of the current channel. **Needs Manage Channel Permissions.**| `{Prefix}schn NewName`")
                .AddCheck(SimpleCheckers.ManageChannels())
                .Parameter("name", ParameterType.Unparsed)
                .Do(async e =>
                {
                    var name = e.GetArg("name");
                    if (string.IsNullOrWhiteSpace(name))
                    {
                        return;
                    }
                    await e.Channel.Edit(name: name).ConfigureAwait(false);
                    await e.Channel.SendMessage(":ok: **New channel name set.**").ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "heap")
                .Description($"Shows allocated memory - **Bot Owner Only!** | `{Prefix}heap`")
                .AddCheck(SimpleCheckers.OwnerOnly())
                .Do(async e =>
                {
                    var heap = await Task.Run(() => WizStats.Instance.Heap()).ConfigureAwait(false);
                    await e.Channel.SendMessage($"`Heap Size:` {heap}").ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "prune")
                .Alias(Prefix + "clr")
                .Description(
                    "`.prune` removes all WizBot's messages in the last 100 messages.`.prune X` removes last X messages from the channel (up to 100)`.prune @Someone` removes all Someone's messages in the last 100 messages.`.prune @Someone X` removes last X 'Someone's' messages in the channel. **Needs Manage Messages Permissions**" +
                    $"| `{Prefix}prune` or `{Prefix}prune 5` or `{Prefix}prune @Someone` or `{Prefix}prune @Someone X`")
                .Parameter("user_or_num", ParameterType.Optional)
                .Parameter("num", ParameterType.Optional)
                .Do(async e =>
                {
                    if (string.IsNullOrWhiteSpace(e.GetArg("user_or_num")))     // if nothing is set, clear WizBot's messages, no permissions required
                    {
                        var msgs = (await e.Channel.DownloadMessages(100).ConfigureAwait(false)).Where(m => m.User?.Id == e.Server.CurrentUser.Id)?.ToArray();
                        if (msgs == null || !msgs.Any())
                        {
                            return;
                        }
                        var toDelete = msgs as Message[] ?? msgs.ToArray();
                        await e.Channel.DeleteMessages(toDelete).ConfigureAwait(false);
                        return;
                    }
                    if (!e.User.GetPermissions(e.Channel).ManageMessages)
                    {
                        return;
                    }
                    else if (!e.Server.CurrentUser.GetPermissions(e.Channel).ManageMessages)
                    {
                        await e.Channel.SendMessage("💢I don't have the permission to manage messages.");
                        return;
                    }
                    int val;
                    if (int.TryParse(e.GetArg("user_or_num"), out val))     // if num is set in the first argument,
                                                                            //delete that number of messages.
                    {
                        if (val <= 0)
                        {
                            return;
                        }
                        val++;
                        await e.Channel.DeleteMessages((await e.Channel.DownloadMessages(val).ConfigureAwait(false)).ToArray()).ConfigureAwait(false);
                        return;
                    }
                    //else if first argument is user
                    var usr = e.Server.FindUsers(e.GetArg("user_or_num")).FirstOrDefault();
                    if (usr == null)
                    {
                        return;
                    }
                    val = 100;
                    if (!int.TryParse(e.GetArg("num"), out val))
                    {
                        val = 100;
                    }
                    var mesgs = (await e.Channel.DownloadMessages(100).ConfigureAwait(false)).Where(m => m.User?.Id == usr.Id).Take(val);
                    if (mesgs == null || !mesgs.Any())
                    {
                        return;
                    }
                    await e.Channel.DeleteMessages(mesgs as Message[] ?? mesgs.ToArray()).ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "die")
                .Description($"Shuts the bot down and notifies users about the restart. **Bot Owner Only!** | `{Prefix}die`")
                .AddCheck(SimpleCheckers.OwnerOnly())
                .Do(async e =>
                {
                    await e.Channel.SendMessage("`Shutting down.`").ConfigureAwait(false);
                    await Task.Delay(2000).ConfigureAwait(false);
                    Environment.Exit(0);
                });

                cgb.CreateCommand(Prefix + "setname")
                .Alias(Prefix + "newnm")
                .Description($"Give the bot a new name. **Bot Owner Only!** | `{Prefix}newnm BotName`")
                .Parameter("new_name", ParameterType.Unparsed)
                .AddCheck(SimpleCheckers.OwnerOnly())
                .Do(async e =>
                {
                    if (e.GetArg("new_name") == null)
                    {
                        return;
                    }

                    await client.CurrentUser.Edit("", e.GetArg("new_name")).ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "newavatar")
                .Alias(Prefix + "setavatar")
                .Description($"Sets a new avatar image for the WizBot. Argument is a direct link to an image. **Bot Owner Only!** | `{Prefix}setavatar http://i.imgur.com/xTG3a1I.jpg`")
                .Parameter("img", ParameterType.Unparsed)
                .AddCheck(SimpleCheckers.OwnerOnly())
                .Do(async e =>
                {
                    if (string.IsNullOrWhiteSpace(e.GetArg("img")))
                    {
                        return;
                    }
                    // Gather user provided URL.
                    var avatarAddress = e.GetArg("img");
                    var imageStream   = await SearchHelper.GetResponseStreamAsync(avatarAddress).ConfigureAwait(false);
                    var image         = System.Drawing.Image.FromStream(imageStream);
                    await client.CurrentUser.Edit("", avatar: image.ToStream()).ConfigureAwait(false);

                    // Send confirm.
                    await e.Channel.SendMessage("New avatar set.").ConfigureAwait(false);

                    // Save the image to disk.
                    image.Save("data/avatar.png", System.Drawing.Imaging.ImageFormat.Png);
                });

                cgb.CreateCommand(Prefix + "setgame")
                .Description($"Sets the bots game. **Bot Owner Only!** | `{Prefix}setgame Playing with Wizkiller96`")
                .Parameter("set_game", ParameterType.Unparsed)
                .Do(e =>
                {
                    if (!WizBot.IsOwner(e.User.Id) || e.GetArg("set_game") == null)
                    {
                        return;
                    }

                    client.SetGame(e.GetArg("set_game"));
                });

                cgb.CreateCommand(Prefix + "send")
                .Description($"Send a message to someone on a different server through the bot. **Bot Owner Only!** | `{Prefix}send sid|u:uid Hello user!` or `{Prefix}send sid|c:cid Message to channel!` (cid = channel id, sid = server id)")
                .Parameter("ids", ParameterType.Required)
                .Parameter("msg", ParameterType.Unparsed)
                .AddCheck(SimpleCheckers.OwnerOnly())
                .Do(async e =>
                {
                    var msg = e.GetArg("msg")?.Trim();

                    if (string.IsNullOrWhiteSpace(msg))
                    {
                        return;
                    }

                    var ids = e.GetArg("ids").Split('|');
                    if (ids.Length != 2)
                    {
                        return;
                    }
                    var sid    = ulong.Parse(ids[0]);
                    var server = WizBot.Client.Servers.Where(s => s.Id == sid).FirstOrDefault();

                    if (server == null)
                    {
                        return;
                    }

                    if (ids[1].ToUpperInvariant().StartsWith("C:"))
                    {
                        var cid     = ulong.Parse(ids[1].Substring(2));
                        var channel = server.TextChannels.Where(c => c.Id == cid).FirstOrDefault();
                        if (channel == null)
                        {
                            return;
                        }
                        await channel.SendMessage(msg);
                    }
                    else if (ids[1].ToUpperInvariant().StartsWith("U:"))
                    {
                        var uid  = ulong.Parse(ids[1].Substring(2));
                        var user = server.Users.Where(u => u.Id == uid).FirstOrDefault();
                        if (user == null)
                        {
                            return;
                        }
                        await user.SendMessage(msg);
                    }
                    else
                    {
                        await e.Channel.SendMessage("`Invalid format.`");
                    }
                });

                cgb.CreateCommand(Prefix + "mentionrole")
                .Alias(Prefix + "menro")
                .Description($"Mentions every person from the provided role or roles (separated by a ',') on this server. Requires you to have mention everyone permission. | `{Prefix}menro RoleName`")
                .Parameter("roles", ParameterType.Unparsed)
                .Do(async e =>
                {
                    await Task.Run(async() =>
                    {
                        if (!e.User.ServerPermissions.MentionEveryone)
                        {
                            return;
                        }
                        var arg     = e.GetArg("roles").Split(',').Select(r => r.Trim());
                        string send = $"--{e.User.Mention} has invoked a mention on the following roles--";
                        foreach (var roleStr in arg.Where(str => !string.IsNullOrWhiteSpace(str)))
                        {
                            var role = e.Server.FindRoles(roleStr).FirstOrDefault();
                            if (role == null)
                            {
                                continue;
                            }
                            send += $"\n`{role.Name}`\n";
                            send += string.Join(", ", role.Members.Select(r => r.Mention));
                        }

                        while (send.Length > 2000)
                        {
                            var curstr = send.Substring(0, 2000);
                            await
                            e.Channel.Send(curstr.Substring(0,
                                                            curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1)).ConfigureAwait(false);
                            send = curstr.Substring(curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1) +
                                   send.Substring(2000);
                        }
                        await e.Channel.Send(send).ConfigureAwait(false);
                    }).ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "unstuck")
                .Description($"Clears the message queue. **Bot Owner Only!** | `{Prefix}unstuck`")
                .AddCheck(SimpleCheckers.OwnerOnly())
                .Do(e =>
                {
                    WizBot.Client.MessageQueue.Clear();
                });

                cgb.CreateCommand(Prefix + "donators")
                .Description($"List of lovely people who donated to keep this project alive. | `{Prefix}donators`")
                .Do(async e =>
                {
                    await Task.Run(async() =>
                    {
                        var rows            = DbHandler.Instance.GetAllRows <Donator>();
                        var donatorsOrdered = rows.OrderByDescending(d => d.Amount);
                        string str          = $"**Thanks to the people listed below for making this project happen!**\n";

                        await e.Channel.SendMessage(str + string.Join("⭐", donatorsOrdered.Select(d => d.UserName))).ConfigureAwait(false);
                    }).ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "donadd")
                .Description($"Add a donator to the database. **Wizkiller96 Only** | `{Prefix}donadd Donate Amount`")
                .Parameter("donator")
                .Parameter("amount")
                .AddCheck(SimpleCheckers.OwnerOnly())
                .Do(async e =>
                {
                    await Task.Run(() =>
                    {
                        var donator = e.Server.FindUsers(e.GetArg("donator")).FirstOrDefault();
                        var amount  = int.Parse(e.GetArg("amount"));
                        if (donator == null)
                        {
                            return;
                        }
                        try
                        {
                            DbHandler.Instance.Connection.Insert(new Donator
                            {
                                Amount   = amount,
                                UserName = donator.Name,
                                UserId   = (long)donator.Id
                            });
                            e.Channel.SendMessage("Successfuly added a new donator. 👑").ConfigureAwait(false);
                        }
                        catch { }
                    }).ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "announce")
                .Description($"Sends a message to all servers' general channel bot is connected to.**Bot Owner Only!** | `{Prefix}announce Useless spam`")
                .Parameter("msg", ParameterType.Unparsed)
                .AddCheck(SimpleCheckers.OwnerOnly())
                .Do(async e =>
                {
                    foreach (var ch in WizBot.Client.Servers.Select(s => s.DefaultChannel))
                    {
                        await ch.SendMessage(e.GetArg("msg")).ConfigureAwait(false);
                    }

                    await e.Channel.SendMessage(":ok:").ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "updates")
                .Alias(Prefix + "unotes")
                .Description("Shows updates that have been done to WizBot.")
                .Do(async e =>
                {
                    await e.Channel.SendMessage(" **WizBot Update Notes**\n\n<http://wizkiller96network.com/wizbot/updates.html>").ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "savechat")
                .Description($"Saves a number of messages to a text file and sends it to you. **Bot Owner Only** | `{Prefix}savechat 150`")
                .Parameter("cnt", ParameterType.Required)
                .AddCheck(SimpleCheckers.OwnerOnly())
                .Do(async e =>
                {
                    var cntstr = e.GetArg("cnt")?.Trim();
                    int cnt;
                    if (!int.TryParse(cntstr, out cnt))
                    {
                        return;
                    }
                    ulong?lastmsgId = null;
                    var sb          = new StringBuilder();
                    var msgs        = new List <Message>(cnt);
                    while (cnt > 0)
                    {
                        var dlcnt = cnt < 100 ? cnt : 100;

                        var dledMsgs = await e.Channel.DownloadMessages(dlcnt, lastmsgId);
                        if (!dledMsgs.Any())
                        {
                            break;
                        }
                        msgs.AddRange(dledMsgs);
                        lastmsgId = msgs[msgs.Count - 1].Id;
                        cnt      -= 100;
                    }
                    await e.User.SendFile($"Chatlog-{e.Server.Name}/#{e.Channel.Name}-{DateTime.Now}.txt", JsonConvert.SerializeObject(new { Messages = msgs.Select(s => s.ToString()) }, Formatting.Indented).ToStream()).ConfigureAwait(false);
                });
            });
        }
Beispiel #7
0
        public override void Install(ModuleManager manager)
        {
            var rng = new Random();

            manager.CreateCommands("", cgb =>
            {
                cgb.AddCheck(PermissionChecker.Instance);

                cgb.CreateCommand("..")
                .Description("Adds a new quote with the specified name (single word) and message (no limit). | `.. abc My message`")
                .Parameter("keyword", ParameterType.Required)
                .Parameter("text", ParameterType.Unparsed)
                .Do(async e =>
                {
                    var text = e.GetArg("text");
                    if (string.IsNullOrWhiteSpace(text))
                    {
                        return;
                    }
                    await Task.Run(() =>
                                   Classes.DbHandler.Instance.Connection.Insert(new DataModels.UserQuote()
                    {
                        DateAdded = DateTime.Now,
                        Keyword   = e.GetArg("keyword").ToLowerInvariant(),
                        Text      = text,
                        UserName  = e.User.Name,
                    })).ConfigureAwait(false);

                    await e.Channel.SendMessage("`New quote added.`").ConfigureAwait(false);
                });

                cgb.CreateCommand("...")
                .Description("Shows a random quote with a specified name. | `... abc`")
                .Parameter("keyword", ParameterType.Required)
                .Do(async e =>
                {
                    var keyword = e.GetArg("keyword")?.ToLowerInvariant();
                    if (string.IsNullOrWhiteSpace(keyword))
                    {
                        return;
                    }

                    var quote =
                        Classes.DbHandler.Instance.GetRandom <DataModels.UserQuote>(
                            uqm => uqm.Keyword == keyword);

                    if (quote != null)
                    {
                        await e.Channel.SendMessage($"📣 {quote.Text}").ConfigureAwait(false);
                    }
                    else
                    {
                        await e.Channel.SendMessage("💢`No quote found.`").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand("..qdel")
                .Alias("..quotedelete")
                .Description("Deletes all quotes with the specified keyword. You have to either be bot owner or the creator of the quote to delete it. | `..qdel abc`")
                .Parameter("quote", ParameterType.Required)
                .Do(async e =>
                {
                    var text = e.GetArg("quote")?.Trim();
                    if (string.IsNullOrWhiteSpace(text))
                    {
                        return;
                    }
                    await Task.Run(() =>
                    {
                        if (WizBot.IsOwner(e.User.Id))
                        {
                            Classes.DbHandler.Instance.DeleteWhere <UserQuote>(uq => uq.Keyword == text);
                        }
                        else
                        {
                            Classes.DbHandler.Instance.DeleteWhere <UserQuote>(uq => uq.Keyword == text && uq.UserName == e.User.Name);
                        }
                    }).ConfigureAwait(false);

                    await e.Channel.SendMessage("`Done.`").ConfigureAwait(false);
                });
            });

            manager.CreateCommands(WizBot.BotMention, cgb =>
            {
                var client = manager.Client;

                cgb.AddCheck(PermissionChecker.Instance);

                commands.ForEach(cmd => cmd.Init(cgb));

                cgb.CreateCommand("die")
                .Description("Works only for the owner. Shuts the bot down. | `@WizBot die`")
                .Do(async e =>
                {
                    if (WizBot.IsOwner(e.User.Id))
                    {
                        await e.Channel.SendMessage(e.User.Mention + ", Yes, my love.").ConfigureAwait(false);
                        await Task.Delay(5000).ConfigureAwait(false);
                        Environment.Exit(0);
                    }
                    else
                    {
                        await e.Channel.SendMessage(e.User.Mention + ", No.").ConfigureAwait(false);
                    }
                });

                var randServerSw = new Stopwatch();
                randServerSw.Start();

                cgb.CreateCommand("do you love me")
                .Description("Replies with positive answer only to the bot owner. | `@WizBot do you love me`")
                .Do(async e =>
                {
                    if (WizBot.IsOwner(e.User.Id))
                    {
                        await e.Channel.SendMessage(e.User.Mention + ", Of course I do, my Master.").ConfigureAwait(false);
                    }
                    else
                    {
                        await e.Channel.SendMessage(e.User.Mention + ", Don't be silly.").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand("how are you")
                .Alias("how are you?")
                .Description("Replies positive only if bot owner is online. | `@WizBot how are you`")
                .Do(async e =>
                {
                    if (WizBot.IsOwner(e.User.Id))
                    {
                        await e.Channel.SendMessage(e.User.Mention + " I am great as long as you are here.").ConfigureAwait(false);
                        return;
                    }
                    var kw = e.Server.GetUser(WizBot.Creds.OwnerIds[0]);
                    if (kw != null && kw.Status == UserStatus.Online)
                    {
                        await e.Channel.SendMessage(e.User.Mention + " I am great as long as " + kw.Mention + " is with me.").ConfigureAwait(false);
                    }
                    else
                    {
                        await e.Channel.SendMessage(e.User.Mention + " I am sad. My Master is not with me.").ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand("fire")
                .Description("Shows a unicode fire message. Optional parameter [x] tells her how many times to repeat the fire. | `@WizBot fire [x]`")
                .Parameter("times", ParameterType.Optional)
                .Do(async e =>
                {
                    int count;
                    if (string.IsNullOrWhiteSpace(e.Args[0]))
                    {
                        count = 1;
                    }
                    else
                    {
                        int.TryParse(e.Args[0], out count);
                    }
                    if (count < 1 || count > 12)
                    {
                        await e.Channel.SendMessage("Number must be between 1 and 12").ConfigureAwait(false);
                        return;
                    }

                    var str = new StringBuilder();
                    for (var i = 0; i < count; i++)
                    {
                        str.Append(firestr);
                    }
                    await e.Channel.SendMessage(str.ToString()).ConfigureAwait(false);
                });

                cgb.CreateCommand("dump")
                .Description("Dumps all of the invites it can to dump.txt.** Owner Only.** | `@WizBot dump`")
                .Do(async e =>
                {
                    if (!WizBot.IsOwner(e.User.Id))
                    {
                        return;
                    }
                    var i       = 0;
                    var j       = 0;
                    var invites = "";
                    foreach (var s in client.Servers)
                    {
                        try
                        {
                            var invite = await s.CreateInvite(0).ConfigureAwait(false);
                            invites   += invite.Url + "\n";
                            i++;
                        }
                        catch
                        {
                            j++;
                            continue;
                        }
                    }
                    File.WriteAllText("dump.txt", invites);
                    await e.Channel.SendMessage($"Got invites for {i} servers and failed to get invites for {j} servers")
                    .ConfigureAwait(false);
                });

                cgb.CreateCommand("ab")
                .Description("Try to get 'abalabahaha'| `@WizBot ab`")
                .Do(async e =>
                {
                    string[] strings = { "ba", "la", "ha" };
                    var construct    = "@a";
                    var cnt          = rng.Next(4, 7);
                    while (cnt-- > 0)
                    {
                        construct += strings[rng.Next(0, strings.Length)];
                    }
                    await e.Channel.SendMessage(construct).ConfigureAwait(false);
                });
            });
        }