Пример #1
0
        public EmbedBuilder CreatePlayerEmbed(Player player)
        {
            var stats   = player.Statistics;
            var flag    = _emojiService.GetEmojiString(player.Nationality);
            var builder = new EmbedBuilder()
                          .WithTitle($"{player.Name} {flag}")
                          .WithColor(Color.Purple)
                          .WithDescription(
                $"Position: {player.Position.ToString()}, Age: {player.Age}, Height: {player.Height}, Weight: {player.Weight}"
                )
                          .WithFooter($"Stats last updated at {player.UpdatedAt:dd/MM/yyyy HH:mm} UTC")
                          .AddField("Games played", stats.Games.Appearances)
                          .AddField("Goals", stats.Goals.Total)
                          .AddField("Assists", stats.Goals.Assists)
                          .AddField("Rating", stats.Rating is null ? "0" : $"{stats.Rating:0.##}");

            var converter = new ToPer90Converter(stats.Games.MinutesPlayed);

            switch (player.Position)
            {
            case Position.Attacker:
                AddShots();
                AddPasses();
                AddDribbles();
                break;

            case Position.Midfielder:
                AddPasses();
                AddDribbles();
                AddTackles();
                break;

            case Position.Defender:
                AddGoalsConceded();
                AddTackles();
                AddPasses();
                break;

            case Position.Goalkeeper:
                AddGoalsConceded();
                AddPasses();
                break;

            case Position.None:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            return(builder);

            void AddShots()
            {
                var shotsTotal              = converter.ToPer90(stats.Shots.Total);
                var shotsOnTarget           = converter.ToPer90(stats.Shots.OnTarget);
                var percentageShotsOnTarget = shotsOnTarget / shotsTotal;

                builder.AddField("Shots per 90 minutes",
                                 $"Total: {shotsTotal:0.##}, On Target: {shotsOnTarget:0.##} ({percentageShotsOnTarget:0.##%})");
            }

            void AddPasses()
            {
                builder.AddField("Passes per 90 minutes",
                                 $"Total: {converter.ToPer90(stats.Passes.Total):0.##}, Key passes: {converter.ToPer90(stats.Passes.Key):0.##}, Accuracy: {stats.Passes.Accuracy:0.##}%"
                                 );
            }

            void AddDribbles()
            {
                var dribblesAttempted            = converter.ToPer90(stats.Dribbles.Attempts);
                var dribblesSuccessful           = converter.ToPer90(stats.Dribbles.Success);
                var percentageDribblesSuccessful = dribblesSuccessful / dribblesAttempted;

                builder.AddField("Dribbles per 90 minutes",
                                 $"Attempted: {dribblesAttempted:0.##}, Successful: {converter.ToPer90(stats.Dribbles.Success):0.##} ({percentageDribblesSuccessful:0.##%})"
                                 );
            }

            void AddTackles()
            {
                builder.AddField("Tackles per 90 minutes",
                                 $"Tackles: {converter.ToPer90(stats.Tackles.Total):0.##}, Interceptions: {converter.ToPer90(stats.Tackles.Interceptions):0.##}, Blocks: {converter.ToPer90(stats.Tackles.Blocks):0.##}"
                                 );
            }

            void AddGoalsConceded()
            {
                builder.AddField("Goals conceded:", stats.Goals.Conceded);
            }
        }
Пример #2
0
        public async Task WasagotchiUser([Remainder] string arg = "")
        {
            SocketUser user          = null;
            var        mentionedUser = Context.Message.MentionedUsers.FirstOrDefault();

            user = mentionedUser ?? Context.User;
            var      config         = GlobalWasagotchiUserAccounts.GetWasagotchiAccount(user);
            var      configg        = GlobalUserAccounts.GetUserAccount(user);
            DateTime now            = DateTime.UtcNow;
            var      timeSpanString = string.Format("{0:%s} seconds", config.LastStats.AddSeconds(8) - now);

            if (now < config.LastStats.AddSeconds(8))
            {
                await Context.Channel.SendMessageAsync($"**{Context.User.Username}, please cooldown! You may use this command in {timeSpanString}.**");

                return;
            }
            config.LastStats = now;
            if (config.Have == false) //if they own a Wasagotchi or not
            {
                await Context.Channel.SendMessageAsync($":no:  |  **{Context.User.Username}**, you don't own a <:wasagotchi:454535808079364106> Wasagotchi! \n\nPurchase one with w!wasagotchi buy!");

                return;
            }
            else //show their Wasagotchi status
            {
                var thumbnailurl = Context.User.GetAvatarUrl();
                var auth         = new EmbedAuthorBuilder()
                {
                    Name    = $"{user.Username}'s Wasagotchi",
                    IconUrl = thumbnailurl,
                };
                var embed = new EmbedBuilder()
                {
                    Author = auth
                };
                if (config.pfp == null)
                {
                    embed.WithThumbnailUrl("https://i.imgur.com/6AaY08I.png");
                }
                else
                {
                    embed.WithThumbnailUrl(config.pfp);
                }
                embed.WithColor(37, 152, 255);
                embed.AddField("Owner", user, true);
                if (config.Name == null)
                {
                    embed.AddField("Name", "*(Name your wasagotchi!)*", true);
                }
                else
                {
                    embed.AddField("Name", config.Name, true);
                }
                if (config.Breed == null)
                {
                    embed.AddField("Breed", "Breedless (You can get a wasagotchi with a breed from a wasagotchi capsule)", true);
                }
                else
                {
                    embed.AddField("Breed", config.Breed, true);
                }
                embed.AddField("Exp", config.XP, true);
                embed.AddField("Level", config.LevelNumber, true);
                embed.AddField("Room", GetRooms(config.rLvl), true);
                embed.AddField("Waste", config.Waste, true);
                embed.AddField("Attention", config.Attention, true);
                embed.AddField("Hunger", config.Hunger, true);
                embed.AddField("Sick", config.Sick, true);
                embed.AddField("Ran Away", config.RanAway, true);
                if (config.pfp == null)
                {
                    embed.AddField("Picture", "*Default*", true);
                }
                else
                {
                    embed.AddField("Picture", "*Custom*", true);
                }

                await Context.Channel.SendMessageAsync("", embed : embed.Build());
            }
        }
Пример #3
0
        public async Task LeaderBoard(string arg = null)
        {
            var embed  = new EmbedBuilder();
            var server = Servers.ServerList.First(x => x.ServerId == Context.Guild.Id);
            var desc   = "";

            try
            {
                if (arg != null && arg.Contains("win"))
                {
                    var orderlist = server.UserList.OrderBy(x => x.Wins).Reverse().ToList();

                    var i = 0;
                    foreach (var user in orderlist)
                    {
                        i++;
                        if (i <= 20)
                        {
                            desc += $"{i}. {user.Username} - {user.Wins}\n";
                        }
                    }
                    embed.WithFooter(x =>
                    {
                        x.Text    = $"Usercount = {i}";
                        x.IconUrl = Context.Client.CurrentUser.GetAvatarUrl();
                    });
                    embed.AddField("LeaderBoard Wins", desc);
                    embed.Color = Color.Blue;
                    await ReplyAsync("", false, embed.Build());
                }
                else if (arg != null && arg.Contains("los"))
                {
                    var orderlist = server.UserList.OrderBy(x => x.Losses).Reverse().ToList();

                    var i = 0;
                    foreach (var user in orderlist)
                    {
                        i++;
                        if (i <= 20)
                        {
                            desc += $"{i}. {user.Username} - {user.Losses}\n";
                        }
                    }
                    embed.WithFooter(x =>
                    {
                        x.Text    = $"Usercount = {i}";
                        x.IconUrl = Context.Client.CurrentUser.GetAvatarUrl();
                    });
                    embed.AddField("LeaderBoard Losses", desc);
                    embed.Color = Color.Blue;
                    await ReplyAsync("", false, embed.Build());
                }
                else
                {
                    var orderlist = server.UserList.OrderBy(x => x.Points).Reverse().ToList();

                    var i = 0;
                    foreach (var user in orderlist)
                    {
                        i++;
                        if (i <= 20)
                        {
                            desc += $"{i}. {user.Username} - {user.Points}\n";
                        }
                    }
                    embed.WithFooter(x =>
                    {
                        x.Text    = $"Usercount = {i}";
                        x.IconUrl = Context.Client.CurrentUser.GetAvatarUrl();
                    });
                    embed.AddField("LeaderBoard Points", desc);
                    embed.Color = Color.Blue;
                    await ReplyAsync("", false, embed.Build());
                }
            }
            catch
            {
                var orderlist = server.UserList.OrderBy(x => x.Points).Reverse().ToList();

                var i = 0;
                foreach (var user in orderlist)
                {
                    i++;
                    if (i <= 20)
                    {
                        desc += $"{i}. {user.Username} - {user.Points}\n";
                    }
                }
                embed.WithFooter(x =>
                {
                    x.Text    = $"Usercount = {i}";
                    x.IconUrl = Context.Client.CurrentUser.GetAvatarUrl();
                });
                embed.AddField("LeaderBoard Points", desc);
                embed.Color = Color.Blue;
                await ReplyAsync("", false, embed.Build());
            }
        }
Пример #4
0
        public async Task PollCreate([Remainder] string parameters)
        {
            string[] parameterArray = parameters.Split('|');
            if (parameterArray.Length >= 4 && parameterArray.Length <= 7)
            {
                string question = parameterArray[0];
                parameterArray[0] = "";
                string timecode = parameterArray[1];
                parameterArray[1] = "";

                ulong timeSpan = 0;
                timecode = timecode.ToLower();
                if (Regex.Match(timecode, @"\d+[dhm]").Success || timecode == "test")
                {
                    if (timecode == "test")
                    {
                        timeSpan = 10;
                    }
                    else
                    {
                        int   i          = timecode.Contains('d') ? timecode.IndexOf('d') : (timecode.Contains('h') ? timecode.IndexOf('h') : timecode.IndexOf('m'));
                        ulong multiplier = 1;
                        switch (timecode.Substring(i, 1))
                        {
                        case "d":
                            multiplier = 24 * 60 * 60; break;

                        case "m":
                            multiplier = 60; break;

                        default:
                            multiplier = 60 * 60; break;
                        }
                        timeSpan = ulong.Parse(timecode.Substring(0, i)) * multiplier;
                    }
                    if (timeSpan > (7 * 24 * 60 * 60))
                    {
                        await Context.Channel.SendMessageAsync($"Timespan too large, max amount of time: 7 days *({7 * 24} hours)*"); return;
                    }
                }

                List <string> pollOptions = new List <string>();
                foreach (string s in parameterArray)
                {
                    if (s != "")
                    {
                        pollOptions.Add(s);
                    }
                }

                var m = await Context.Channel.SendMessageAsync("Poll creating...");

                Poll p = new Poll(m, question, Context.User, pollOptions.ToArray());

                EmbedBuilder eb = new EmbedBuilder();
                eb.WithAuthor($"Poll by {Context.User.Username}#{Context.User.DiscriminatorValue}", Context.User.GetAvatarUrl());
                eb.WithDescription($"**{question}**");
                eb.WithFooter($"PollID: {p.PollId}");
                eb.WithColor(0, 255, 0);
                foreach (PollOption s in p.PollOptions)
                {
                    float amt = p.PollReactions.Count(x => x.PollVote == s.Option);
                    eb.AddField($"{s.React} {s.Option}", $"{Poll.GetPercentageBar(p, s.Option)} - 0/{p.PollReactions.Count} (0,00%)");
                }

                await m.ModifyAsync(x => {
                    x.Content = "";
                    x.Embed   = eb.Build();
                });

                await p.AddAllReactions();

                GlobalVars.AddPoll(p, timeSpan);
            }
            else
            {
                var m = await Context.Channel.SendMessageAsync("Too many parameters");

                GlobalVars.AddRandomTracker(m);
            }
        }
Пример #5
0
        public async Task Apply()
        {
            if (Config.ModAppsActive == false)
            {
                await ReplyAsync(":x: Thank you, but we closed moderator applications for now.");

                return;
            }

            if (Context.User.IsBot)
            {
                return;
            }
            if (!(Context.Channel is IDMChannel))
            {
                await ReplyAsync(":x: To apply for the moderator position, please use this command in a DM channel with the bot.");

                return;
            }
            if (Context.Message.Timestamp.AddHours(2).Day == 17)
            {
                return;
            }

            SocketGuild       guild             = Context.Client.Guilds.First();
            SocketTextChannel moderationchannel = (SocketTextChannel)guild.Channels.First(x => x.Id == Methods.Data.GetChnlId("moderation-log"));

            EmbedBuilder moderationembed = new EmbedBuilder();

            moderationembed.WithAuthor(Context.User);
            moderationembed.WithColor(114, 137, 218);
            moderationembed.WithTitle("Moderation Application");
            moderationembed.WithFooter($"Started at {DateTime.Now.ToString("h:mm")}");

            RestUserMessage moderationmsg = await moderationchannel.SendMessageAsync("", false, moderationembed.Build());

            await ReplyAsync("Thank you for applying to moderate the r/Jordan Discord! We are going to ask you a few questions to make sure you are fit for the job. You can reply with `cancel` at any time to cancel the application. Waiting for more than 5 minutes to answer a question will cancel the application. Troll applications are not tolerated.");

            IUserMessage response;

            // Questions
            {
                await ReplyAsync("First of all, how old are you?");

                response = (IUserMessage) await NextMessageAsync(true, true, TimeSpan.FromMinutes(5));

                if (response == null || response.Content.ToLower() == "cancel")
                {
                    goto cancel;
                }
                moderationembed.AddField("First of all, how old are you?", response.Content);
                await moderationmsg.ModifyAsync(x => x.Embed = moderationembed.Build());

                await ReplyAsync("What is the timezone of your current place of residence?");

                response = (IUserMessage) await NextMessageAsync(true, true, TimeSpan.FromMinutes(5));

                if (response == null || response.Content.ToLower() == "cancel")
                {
                    goto cancel;
                }
                moderationembed.AddField("What is the timezone of your current place of residence?", response.Content);
                await moderationmsg.ModifyAsync(x => x.Embed = moderationembed.Build());

                await ReplyAsync("Tell us a little about yourself.");

                response = (IUserMessage) await NextMessageAsync(true, true, TimeSpan.FromMinutes(5));

                if (response == null || response.Content.ToLower() == "cancel")
                {
                    goto cancel;
                }
                moderationembed.AddField("Tell us a little about yourself.", response.Content);
                await moderationmsg.ModifyAsync(x => x.Embed = moderationembed.Build());

                await ReplyAsync("How many hours a day do you average on Discord?");

                response = (IUserMessage) await NextMessageAsync(true, true, TimeSpan.FromMinutes(5));

                if (response == null || response.Content.ToLower() == "cancel")
                {
                    goto cancel;
                }
                moderationembed.AddField("How many hours a day do you average on Discord?", response.Content);
                await moderationmsg.ModifyAsync(x => x.Embed = moderationembed.Build());

                await ReplyAsync("What do you think you could bring to the server as a moderator?");

                response = (IUserMessage) await NextMessageAsync(true, true, TimeSpan.FromMinutes(5));

                if (response == null || response.Content.ToLower() == "cancel")
                {
                    goto cancel;
                }
                moderationembed.AddField("What do you think you could bring to the server as a moderator?", response.Content);
                await moderationmsg.ModifyAsync(x => x.Embed = moderationembed.Build());

                await ReplyAsync("Do you have any previous moderation experiences on or off Discord?");

                response = (IUserMessage) await NextMessageAsync(true, true, TimeSpan.FromMinutes(5));

                if (response == null || response.Content.ToLower() == "cancel")
                {
                    goto cancel;
                }
                moderationembed.AddField("Do you have any previous moderation experiences on or off Discord?", response.Content);
                await moderationmsg.ModifyAsync(x => x.Embed = moderationembed.Build());
            }

            await ReplyAsync("Your application has been recorded. Thank you for your time.");

            moderationembed.WithFooter(moderationembed.Footer.Text + $" | Finished at {DateTime.Now.ToString("h:mm")}");
            await moderationmsg.ModifyAsync(x => x.Embed = moderationembed.Build());

            return;

cancel:
            IEmote x = new Emoji("❌");

            if (response != null)
            {
                await response.AddReactionAsync(x);
            }
            else
            {
                await ReplyAndDeleteAsync("Moderation application canceled.", false, null, TimeSpan.FromSeconds(30));
            }

            moderationembed.WithFooter(moderationembed.Footer.Text + $" | Canceled at {DateTime.Now.ToString("h:mm")}");
            await moderationmsg.ModifyAsync(x => x.Embed = moderationembed.Build());

            return;
        }
Пример #6
0
        public async Task CovidStats(string date = null)
        {
            DateTime dateTime = DateTime.Today;

            if (DateTime.TryParseExact(date, "d-M-yyyy", null, System.Globalization.DateTimeStyles.None, out DateTime outDateTime))
            {
                dateTime = outDateTime;
            }
            else if (DateTime.TryParseExact(date, "d/M/yyyy", null, System.Globalization.DateTimeStyles.None, out DateTime outDateTime2))
            {
                dateTime = outDateTime2;
            }
            if (dateTime < new DateTime(2020, 10, 1))
            {
                await ReplyAsync(":x: The API only contains COVID data from 1/10/2020 and after.");

                return;
            }
            COVID stats = await Data.APIHttpRequest <COVID>($"https://api.anastarawneh.tech/v1/covid-19/{dateTime.Year}/{dateTime.Month}/{dateTime.Day}", "GET");

            dateTime = stats.date;
            DateTime yesterday      = dateTime.AddDays(-1);
            COVID    yesterdayStats = await Data.APIHttpRequest <COVID>($"https://api.anastarawneh.tech/v1/covid-19/{yesterday.Year}/{yesterday.Month}/{yesterday.Day}", "GET");

            EmbedBuilder embed = new EmbedBuilder();

            embed.WithTitle($"COVID-19 stats for {dateTime:dd/MM/yyyy}");
            embed.WithColor(Constants.IColors.Blurple);
            embed.WithDescription($"{stats.localCases} new local cases, {stats.deaths} casualties and {stats.recoveries} recoveries.");
            if (stats.cities.Total() != 0)
            {
                embed.AddField("Amman", stats.cities.amman, true);
                embed.AddField("Irbid", stats.cities.irbid, true);
                embed.AddField("Zarqa", stats.cities.zarqa, true);
                embed.AddField("Mafraq", stats.cities.mafraq, true);
                embed.AddField("Ajloun", stats.cities.ajloun, true);
                embed.AddField("Jerash", stats.cities.jerash, true);
                embed.AddField("Madaba", stats.cities.madaba, true);
                embed.AddField("Balqa", stats.cities.balqa, true);
                embed.AddField("Karak", stats.cities.karak, true);
                embed.AddField("Tafileh", stats.cities.tafileh, true);
                embed.AddField("Ma'an", stats.cities.maan, true);
                embed.AddField("Aqaba", stats.cities.aqaba, true);
            }
            decimal percentage = (decimal)stats.cases / (decimal)stats.tests * 100m;
            string  moreStats  =
                $"Total cases: {stats.totalCases}\n" +
                $"Total casualties: {stats.totalDeaths}\n" +
                $"Total recoveries: {stats.totalRecoveries}\n" +
                $"Foreign cases: {stats.cases - stats.localCases}\n" +
                $"Hospitalized cases today: {stats.hospitalized}, total: {stats.totalHospitalized}\n" +
                $"Recovery distribution: {stats.homeRecoveries} at home, {stats.hospitalRecoveries} from hospitals\n" +
                $"Tests today: {stats.tests}, total: {stats.totalTests}\n" +
                $"Positive test percentage: {Math.Round(percentage, 2)}%\n" +
                $"Active cases: {stats.active}";

            if (yesterdayStats.critical != 0)
            {
                moreStats += $"\nYesterday's critical cases: {yesterdayStats.critical}";
            }
            if (stats.vaxRegistered != 0)
            {
                moreStats +=
                    $"\nvaccine.jo registrants: {stats.vaxRegistered}\n" +
                    $"Vaccinated - First dose: {stats.vaxFirstDose}\n" +
                    $"Vaccinated - Second dose: {stats.vaxSecondDose}";
            }
            embed.AddField("More stats", moreStats);

            IUserMessage statmsg;

            if (Context.Channel.Name == "covid-19-stats")
            {
                bool statsReady = stats.date == DateTime.Today;
                if (!statsReady)
                {
                    await ReplyAsync(":x: Today's stats aren't ready yet.");

                    return;
                }
                statmsg = await ReplyAsync(MentionUtils.MentionRole(773576613605933087), false, embed.Build());

                await Context.Message.DeleteAsync();

                await statmsg.CrosspostAsync();
            }
            else
            {
                statmsg = await ReplyAsync("", false, embed.Build());
            }
        }
Пример #7
0
        public async Task Call(string target, string requestedCard)
        {
            target        = target.Replace("@", "").Replace("<", "").Replace(">", "").Replace("!", "");
            requestedCard = requestedCard.ToUpperInvariant();

            if (variables[Context.Guild].RedScore + variables[Context.Guild].BlueScore == 9)
            {
                await ReplyAsync(
                    ":checkered_flag: The game has ended! Use the `.reset` command to play again! :checkered_flag:");

                return;
            }

            if (!variables[Context.Guild].GameInProgress)
            {
                await ReplyAsync($":x: Game is not in progress yet! :x:");

                await Context.Message.DeleteAsync();

                return;
            } // make sure the game is in progress

            if (variables[Context.Guild].AuthorUsers[variables[Context.Guild].PlayerTurn] != Context.Message.Author)
            {
                await Context.Message.DeleteAsync();

                return;
            } // make sure only the person's whose turn it is can call

            if (variables[Context.Guild].TeamDict[target] ==
                variables[Context.Guild].TeamDict[variables[Context.Guild].PlayerTurn])
            {
                await ReplyAsync($":x: Cannot call cards from someone on your team! :x:");

                await Context.Message.DeleteAsync();

                return;
            } // make sure they call someone on the opposite team

            if (variables[Context.Guild].PlayerCards[target].Count == 0)
            {
                await ReplyAsync($":x: Cannot call a player with no cards! :x:");

                await Context.Message.DeleteAsync();

                return;
            }

            // delete previous call info
            var rawMessages = Context.Channel.GetMessagesAsync().FlattenAsync();

            foreach (var msg in rawMessages.Result)
            {
                if (msg.Author.Id == Context.Client.CurrentUser.Id && msg.Content.Contains("*TEMPORARY*")) // everything marked with *TEMPORARY*
                {
                    await msg.DeleteAsync();
                }
            }

            var req = CardDealer.GetCardByName(requestedCard.ToUpperInvariant());

            if (!variables[Context.Guild].Players.Contains(target)) // make sure the target is a valid player
            {
                await ReplyAsync($":x: `{target}` is not a player! :x:");

                await Context.Message.DeleteAsync();

                return;
            }

            if (!CardDealer.CardNames.Contains(requestedCard)) // make sure requestedCard is a valid card
            {
                await ReplyAsync($":x: `{requestedCard}` is not a valid card! :x:");

                await Context.Message.DeleteAsync();

                return;
            }

            var builder = new EmbedBuilder
            {
                Title    = "Call Result",
                ImageUrl = "https://raw.githubusercontent.com/jonathanh8686/DiscordFishBot/master/cards/" +
                           req.CardName + ".png"
            };

            int cardIndex = CardDealer.CardNames.IndexOf(requestedCard);
            int hsIndex   = cardIndex / 6; // get index of halfsuit

            var hasHalfSuit = false;

            for (var i = 0; i < 6; i++) // loop through halfsuit and see if they have something in the same hs
            {
                if (variables[Context.Guild].PlayerCards[variables[Context.Guild].PlayerTurn]
                    .Contains(CardDealer.GetCardByName(CardDealer.CardNames[6 * hsIndex + i])))
                {
                    hasHalfSuit = true;
                }
            }

            // handing illegal moves
            if (variables[Context.Guild].PlayerCards[variables[Context.Guild].PlayerTurn].Contains(req) || !hasHalfSuit) // player already has the card or they don't have something in the halfsuit
            {
                await Context.Message.DeleteAsync();

                return;
                //variables[Context.Guild].AlgebraicNotation += $"call {target} {requestedCard} illegal;";

                //builder.Color = Color.Magenta;
                //builder.Description = ":oncoming_police_car: ILLEGAL CALL! :oncoming_police_car:";

                //builder.AddField("Info",
                //    $"<@{variables[Context.Guild].PlayerTurn}> called the `{requestedCard}` from <@{target}> but it was **illegal**!\n It is now <@{target}>'s turn.");
                //variables[Context.Guild].PlayerTurn = target;
                //await ReplyAsync("*TEMPORARY*", false, builder.Build());

                //await Context.Message.DeleteAsync();
                //return;
            }

            if (variables[Context.Guild].PlayerCards[target].Contains(req))
            {
                // hit
                variables[Context.Guild].AlgebraicNotation += $"call {target} {requestedCard} hit;";

                builder.Color        = Color.Green;
                builder.Description  = ":boom: Call was a hit! :boom:";
                builder.ThumbnailUrl =
                    "https://raw.githubusercontent.com/jonathanh8686/DiscordFishBot/master/cards/hit.png";

                builder.AddField("Info",
                                 $"<@{variables[Context.Guild].PlayerTurn}> called the `{requestedCard}` from <@{target}> and it was a **hit**!\n It is now <@{variables[Context.Guild].PlayerTurn}>'s turn.");

                variables[Context.Guild].PlayerCards[target].Remove(req);
                variables[Context.Guild].PlayerCards[variables[Context.Guild].PlayerTurn].Add(req);
            }
            else
            {
                // miss
                variables[Context.Guild].AlgebraicNotation += $"call {target} {requestedCard} miss;";

                builder.Color        = Color.DarkRed;
                builder.Description  = ":thinking: Call was a miss! :thinking:";
                builder.ThumbnailUrl =
                    "https://raw.githubusercontent.com/jonathanh8686/DiscordFishBot/master/cards/miss.png";

                builder.AddField("Info",
                                 $"<@{variables[Context.Guild].PlayerTurn}> called the `{requestedCard}` from <@{target}> and it was a **miss**!\n It is now <@{target}>'s turn.");
                variables[Context.Guild].PlayerTurn = target;
            }

            await Context.Message.DeleteAsync();

            await ReplyAsync("*TEMPORARY*", false, builder.Build());

            await CardDealer.SendCards(Context.Guild);

            if (CheckPlayerTurnHandEmpty())
            {
                await ReplyAsync(
                    "not sure how this can ever get called but ill leave this here for a few games and see if this text ever shows up and if it doesn't i guess ill delete it xd");

                await ReplyAsync(
                    $"<@{variables[Context.Guild].PlayerTurn}> is out of cards! Use the `.designate` command to select the next player!");

                variables[Context.Guild].NeedsDesignatedPlayer = true;
            }
        }
Пример #8
0
        public async Task CheckUser(IGuildUser user)
        {
            try
            {
                var comander = UserAccounts.GetAccount(Context.User, Context.Guild.Id);
                if (comander.OctoPass >= 4 || ((IGuildUser)Context.User).GuildPermissions.ManageMessages)
                {
                    var account = UserAccounts.GetAccount((SocketUser)user, Context.Guild.Id);

                    //   var avatar = ("https://cdn.discordapp.com/avatars/" + user.Id + "/" + user.AvatarId + ".png");

                    var usedNicks  = "";
                    var usedNicks2 = "";
                    var usedNicks3 = "";
                    var usedNicks4 = "";
                    if (account.ExtraUserName != null)
                    {
                        var extra = account.ExtraUserName.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                        for (var i = 0; i < extra.Length; i++)
                        {
                            if (i == extra.Length - 1)
                            {
                                usedNicks += extra[i];
                            }
                            else if (usedNicks.Length <= 970)
                            {
                                usedNicks += extra[i] + ", ";
                            }
                            else if (usedNicks2.Length <= 970)
                            {
                                usedNicks2 += extra[i] + ", ";
                            }
                            else if (usedNicks3.Length <= 970)
                            {
                                usedNicks3 += extra[i] + ", ";
                            }
                            else if (usedNicks4.Length <= 970)
                            {
                                usedNicks4 += extra[i] + ", ";
                            }
                        }
                    }
                    else
                    {
                        usedNicks = "None";
                    }


                    var octopuses = "";
                    if (account.Octopuses != null)
                    {
                        var octo = account.Octopuses.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);


                        for (var i = 0; i < octo.Length; i++)
                        {
                            if (i == octo.Length - 1)
                            {
                                octopuses += octo[i];
                            }
                            else
                            {
                                octopuses += octo[i] + ", ";
                            }
                        }
                    }
                    else
                    {
                        octopuses = "None";
                    }

                    var warnings = "None";
                    if (account.Warnings != null)
                    {
                        var warns = account.Warnings.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                        warnings = "";
                        foreach (var t in warns)
                        {
                            warnings += t + "\n";
                        }
                    }

                    var   statList          = account.UserStatistics.ToList();
                    ulong allMessages       = 0;
                    ulong editMesages       = 0;
                    ulong deletedMessages   = 0;
                    var   mostActiveChannel = "N/A";

                    foreach (var t in statList)
                    {
                        if (t.Key == "all")
                        {
                            allMessages = t.Value;
                        }
                        if (t.Key == "updated")
                        {
                            editMesages = t.Value;
                        }
                        if (t.Key == "deleted")
                        {
                            deletedMessages = t.Value;
                        }
                    }

                    var ordered = statList.OrderByDescending(x => x.Value).ToList();

                    mostActiveChannel = $"<#{Convert.ToUInt64(ordered[1].Key)}> - {ordered[1].Value} messages";

                    var embed = new EmbedBuilder();

                    embed.WithColor(Color.Purple);
                    embed.WithAuthor(user);
                    embed.WithFooter("lil octo notebook");
                    embed.AddField("ID", "" + user.Id, true);
                    embed.AddField("UserName", "" + user, true);
                    embed.AddField("Registered", "" + user.CreatedAt, true);
                    embed.AddField("Joined", "" + user.JoinedAt, true);
                    embed.AddField("NickName", "" + user.Mention, true);
                    embed.AddField("Octo Points", "" + account.Points, true);
                    embed.AddField("Octo Reputation", "" + account.Rep, true);
                    embed.AddField("Access LVL", "" + account.OctoPass, true);
                    embed.AddField("User LVL", "" + Math.Round(account.Lvl, 2), true);
                    embed.AddField("Pull Points", "" + account.DailyPullPoints, true);
                    embed.AddField("Best 2048 Game Score", $"{account.Best2048Score}", true);
                    embed.AddField("All Messages", $"{allMessages}", true);
                    embed.AddField("All Edited Messages", $"{editMesages}", true);
                    embed.AddField("All Deleted Messages", $"{deletedMessages}", true);
                    embed.AddField("Channel Most Active In", $"{mostActiveChannel}", true);



                    embed.AddField("Warnings", "" + warnings);

                    embed.AddField("OctoCollection ", "" + octopuses);
                    embed.AddField("Used Nicknames", "" + usedNicks);
                    embed.WithThumbnailUrl(user.GetAvatarUrl());


                    await CommandHandeling.ReplyAsync(Context, embed);

                    if (usedNicks2.Length >= 2)
                    {
                        var usedEmbed = new EmbedBuilder();

                        usedEmbed.AddField("Used Nicknames Co-nt:", $"{usedNicks2}");
                        if (usedNicks3.Length >= 2)
                        {
                            usedEmbed.AddField("boole?!", $"{usedNicks3}");
                        }
                        if (usedNicks4.Length >= 2)
                        {
                            usedEmbed.AddField("It's time to stop.", $"{usedNicks4}");
                        }
                        usedEmbed.WithColor(Color.Blue);
                        usedEmbed.WithAuthor(user);
                        usedEmbed.WithFooter("lil octo notebook");
                        await CommandHandeling.ReplyAsync(Context, usedEmbed);
                    }
                }
                else
                {
                    await CommandHandeling.ReplyAsync(Context,
                                                      "Boole! You do not have a tolerance of this level!");
                }
            }
            catch
            {
                //    await ReplyAsync("boo... An error just appear >_< \nTry to use this command properly: **Stats [user_ping(or user ID)]**");
            }
        }
Пример #9
0
Файл: osu.cs Проект: Kyuwu/Bott
        public async Task BM(string url)
        {
            try
            {
                //int t = 0;
                //string code = "";
                //foreach (char x in url)
                //{
                //    if (x == '/')
                //    {
                //        t = t + 1;
                //    }
                //    else if (t == 4)
                //    {
                //        code += x.ToString();
                //    }
                //}
                //string img = "";
                //foreach (char x in url)
                //{
                //    if (x == '/')
                //    {
                //        t = t + 1;
                //    }
                //    else if (t == 4)
                //    {
                //        code += x.ToString();
                //    }
                //}
                var request3 =
                    WebRequest.Create(
                        $"https://osu.ppy.sh/api/get_beatmaps?k=00b5c6aaae0d1a09091f08fc294836c893c591de&s={url}")
                    as
                    HttpWebRequest;
                if (request3 == null)
                {
                    return;
                }
                EmbedBuilder xdd = new EmbedBuilder
                {
                    Description = "---"
                };
                request3.Method      = "GET";
                request3.ContentType = "application/json";
                var myWebResponse3 = (HttpWebResponse)request3.GetResponse();
                var encoding3      = Encoding.ASCII;
                using (var reader3 =
                           new StreamReader(
                               myWebResponse3.GetResponseStream() ?? throw new InvalidOperationException(),
                               encoding3))
                {
                    var result3  = reader3.ReadToEnd();
                    var haitai   = (JArray)JsonConvert.DeserializeObject(result3);
                    var kekistan = haitai.Count;

                    for (int i = 0; i < haitai.Count; i++)
                    {
                        var    title            = haitai[i]["title"].ToString();
                        var    bpm              = haitai[i]["bpm"].ToString();
                        var    version          = haitai[i]["version"].ToString();
                        var    creator          = haitai[i]["creator"].ToString();
                        var    max_combo        = haitai[i]["max_combo"].ToString();
                        double difficultyrating = Convert.ToDouble(haitai[i]["difficultyrating"]);
                        var    approved_date    = haitai[i]["approved_date"].ToString();
                        var    diff_approach    = haitai[i]["diff_approach"].ToString();
                        var    approved         = haitai[i]["approved"].ToString();
                        var    mlg              = haitai[i]["beatmapset_id"].ToString();
                        var    mlg2             = haitai[i]["beatmap_id"].ToString();
                        var    shee             = Math.Round(difficultyrating, 2);
                        if (approved.Contains("0"))
                        {
                            xdd.AddField(x =>
                            {
                                x.Name  = $"[{title}({version})](https://osu.ppy.sh/api/get_beatmaps?k=00b5c6aaae0d1a09091f08fc294836c893c591de&s={url})";
                                x.Value =
                                    $"**Type:** Pending **Creator:** {creator} **BPM** {bpm} **Max combo:** {max_combo}\n**Difficulty:** {shee} **AR:** {diff_approach} **Approve date:** {approved_date}";
                            });
                        }
                        else if (approved.Contains("-1"))
                        {
                            xdd.AddField(x =>
                            {
                                x.Name  = $"[{title}({version})](https://osu.ppy.sh/api/get_beatmaps?k=00b5c6aaae0d1a09091f08fc294836c893c591de&s={url})";
                                x.Value =
                                    $"**Type:** WIP **Creator:** {creator}**BPM** {bpm}**Max combo:** {max_combo}\n**Difficulty:** {shee} **AR:** {diff_approach}";
                            });
                        }
                        else if (approved.Contains("-2"))
                        {
                            xdd.AddField(x =>
                            {
                                x.Name  = $"[{title}({version})](https://osu.ppy.sh/api/get_beatmaps?k=00b5c6aaae0d1a09091f08fc294836c893c591de&s={url})";
                                x.Value =
                                    $"**Type:** In the graveyard ;( **Creator:** {creator} **BPM** {bpm} **Max combo:** {max_combo}\n**Difficulty:** {shee} **AR:** {diff_approach}";
                            });
                        }
                        else if (approved.Contains("1"))
                        {
                            xdd.AddField(x =>
                            {
                                x.Name  = $"[{title}({version})]";
                                x.Value =
                                    $"**Type:** Ranked **Creator:** {creator} **BPM** {bpm} **Max combo:** {max_combo}\n**Difficulty:** {shee} **AR:** {diff_approach} **Approve date:** {approved_date}[:arrow_down:](https://osu.ppy.sh/d/{url}) [:information_source:](https://osu.ppy.sh/s/{url})";
                            });
                        }
                        else if (approved.Contains("2"))
                        {
                            xdd.AddField(x =>
                            {
                                x.Name  = $"[{title}({version})]";
                                x.Value =
                                    $"**Type:** Approved **Creator:** {creator} **BPM** {bpm} **Max combo:** {max_combo}\n**Difficulty:** {shee} **AR:** {diff_approach} **Approve date:** {approved_date}";
                            });
                        }
                        else if (approved.Contains("3"))
                        {
                            xdd.AddField(x =>
                            {
                                x.Name  = $"[{title}({version})](https://osu.ppy.sh/api/get_beatmaps?k=00b5c6aaae0d1a09091f08fc294836c893c591de&s={url})";
                                x.Value =
                                    $"**Type:** qualified **Creator:** {creator} **BPM** {bpm} **Max combo:** {max_combo}\n**Difficulty:** {shee} **AR:** {diff_approach} **Approve date:** {approved_date}";
                            });
                        }
                        else if (approved.Contains("4"))
                        {
                            xdd.AddField(x =>
                            {
                                x.Name  = $"[{title}({version})](https://osu.ppy.sh/api/get_beatmaps?k=00b5c6aaae0d1a09091f08fc294836c893c591de&s={url})";
                                x.Value =
                                    $"**Type:** LOVED ❤ **Creator:** {creator} **BPM** {bpm} **Max combo:** {max_combo}\n**Difficulty:** {shee} **AR:** {diff_approach} **Approve date:** {approved_date}";
                            });
                        }

                        else
                        {
                            var auth = new EmbedAuthorBuilder()
                            {
                                Name = $"Error",
                            };
                            var rnd     = new Random();
                            int g1      = rnd.Next(1, 255);
                            int g2      = rnd.Next(1, 255);
                            int g3      = rnd.Next(1, 255);
                            var builder = new EmbedBuilder()
                            {
                                Color  = new Discord.Color(g1, g2, g3),
                                Author = auth,
                            };
                            builder.Description  = $"No data yet....\nosu ples";
                            builder.ThumbnailUrl =
                                $"https://raw.githubusercontent.com/ThijmenHogenkamp/Bot/master/Luxary/bin/Debug/pic/oh.png";
                            await ReplyAsync("", false, builder.Build());
                        }
                        xdd.Title = title;
                    }
                    await ReplyAsync("", false, xdd.Build());
                }
            }
            catch (Exception e)
            {
                var auth = new EmbedAuthorBuilder()
                {
                    Name = $"Error",
                };
                var rnd     = new Random();
                int g1      = rnd.Next(1, 255);
                int g2      = rnd.Next(1, 255);
                int g3      = rnd.Next(1, 255);
                var builder = new EmbedBuilder()
                {
                    Color  = new Discord.Color(g1, g2, g3),
                    Author = auth,
                };
                builder.Description  = $"No data yet....\nosu ples";
                builder.ThumbnailUrl =
                    $"https://raw.githubusercontent.com/ThijmenHogenkamp/Bot/master/Luxary/bin/Debug/pic/oh.png";
                await ReplyAsync("", false, builder.Build());

                Console.WriteLine(e);
                throw;
            }
        }
Пример #10
0
        public async Task UpdateAccount()
        {
            try{
                //getting id of sender and selecting lol id
                string UserID      = Context.User.Id.ToString();
                ulong  resultid    = Context.User.Id;
                ulong  xxx         = Convert.ToUInt64(resultid);
                var    GottenName  = Context.Guild.GetUser(xxx);
                var    guildUser   = GottenName as SocketGuildUser;
                string DiscordName = null;

                if (guildUser.ToString().Contains("'"))
                {
                    DiscordName = guildUser.ToString().Replace("'", "''");
                }

                string getID             = "SELECT League_id FROM users_testing WHERE Discord_Id like  '%" + UserID + "%'; ";
                string getIcon           = "SELECT Icon_id FROM users_testing WHERE Discord_Id like '%" + UserID + "%';";
                string getstatus         = "SELECT verified FROM users_testing WHERE Discord_ID like '%" + UserID + "%';";
                string InsertDiscordName = "UPDATE users_testing SET `Discord_Name` = '" + DiscordName + "' WHERE Discord_Id like  '%" + UserID + "%';";
                string getToken          = "SELECT TOKEN FROM users_testing WHERE Discord_Id like '%" + UserID + "%';";
                string id     = null;
                string token  = null;
                string status = null;
                string data;

                //getting the lol id from the sender of the update command
                MySqlConnection myconn            = new MySqlConnection(Global.connect);
                MySqlCommand    command           = new MySqlCommand(getID, myconn);
                MySqlCommand    geticon           = new MySqlCommand(getIcon, myconn);
                MySqlCommand    GetToken          = new MySqlCommand(getToken, myconn);
                MySqlCommand    GetStatus         = new MySqlCommand(getstatus, myconn);
                MySqlCommand    InsertDiscordname = new MySqlCommand(InsertDiscordName, myconn);
                MySqlDataReader myreader;
                MySqlDataReader iconreader;

                //getting the League ID from the DB
                myconn.Open();
                myreader = command.ExecuteReader();
                while (myreader.Read())
                {
                    data = myreader.GetString(0);
                    id   = data;
                }
                myconn.Close();

                //get verification status
                myconn.Open();
                myreader = GetStatus.ExecuteReader();
                while (myreader.Read())
                {
                    data   = myreader.GetString(0);
                    status = data;
                }
                myconn.Close();

                if (id == "")
                {
                    var embed2 = new EmbedBuilder();
                    embed2.AddField("updating your account...",
                                    "No account was found!")
                    .WithAuthor(author => { author
                                            .WithName("Birdie Bot")
                                            .WithIconUrl(Global.Birdieicon); })
                    .WithThumbnailUrl(Global.Birdiethumbnail)
                    .WithColor(new Color(255, 83, 13))
                    .WithTitle("Birdie Bot notification")
                    .WithFooter(footer => { footer
                                            .WithText(Global.Botcreatorname)
                                            .WithIconUrl(Global.Birdieicon); })
                    .WithCurrentTimestamp()
                    .Build();
                    await Context.Channel.SendMessageAsync("", false, embed2);

                    await Task.Delay(5000);

                    var messages2 = await Context.Channel.GetMessagesAsync(2).Flatten();

                    await Context.Channel.DeleteMessagesAsync(messages2);

                    return;
                }

                if (status == "false")
                {
                    var embed2 = new EmbedBuilder();
                    embed2.AddField("updating your account...",
                                    "Your account is not verified!")
                    .WithAuthor(author => { author
                                            .WithName("Birdie Bot")
                                            .WithIconUrl(Global.Birdieicon); })
                    .WithThumbnailUrl(Global.Birdiethumbnail)
                    .WithColor(new Color(255, 83, 13))
                    .WithTitle("Birdie Bot notification")
                    .WithFooter(footer => { footer
                                            .WithText(Global.Botcreatorname)
                                            .WithIconUrl(Global.Birdieicon); })
                    .WithCurrentTimestamp()
                    .Build();
                    await Context.Channel.SendMessageAsync("", false, embed2);

                    await Task.Delay(5000);

                    var messages2 = await Context.Channel.GetMessagesAsync(2).Flatten();

                    await Context.Channel.DeleteMessagesAsync(messages2);

                    return;
                }

                myconn.Open();
                myreader = GetToken.ExecuteReader();
                while (myreader.Read())
                {
                    data  = myreader.GetString(0);
                    token = data;
                }
                myconn.Close();

                if (token == "")
                {
                    var embed2 = new EmbedBuilder();
                    embed2.AddField("updating your account...",
                                    "Your account is not verified!")
                    .WithAuthor(author => { author
                                            .WithName("Birdie Bot")
                                            .WithIconUrl(Global.Birdieicon); })
                    .WithThumbnailUrl(Global.Birdiethumbnail)
                    .WithColor(new Color(255, 83, 13))
                    .WithTitle("Birdie Bot notification")
                    .WithFooter(footer => { footer
                                            .WithText(Global.Botcreatorname)
                                            .WithIconUrl(Global.Birdieicon); })
                    .WithCurrentTimestamp()
                    .Build();
                    await Context.Channel.SendMessageAsync("", false, embed2);

                    await Task.Delay(5000);

                    var messages3 = await Context.Channel.GetMessagesAsync(2).Flatten();

                    await Context.Channel.DeleteMessagesAsync(messages3);

                    return;
                }

                //getting the icon ID from the DB
                myconn.Open();
                string iconid = null;
                iconreader = geticon.ExecuteReader();
                while (iconreader.Read())
                {
                    data   = iconreader.GetString(0);
                    iconid = data;
                }
                myconn.Close();

                //using c for webclient connections
                WebClient c = new WebClient();

                //getting league rank from ID
                //using "r" for rank
                string responserank = c.DownloadString("https://euw1.api.riotgames.com/lol/league/v4/entries/by-summoner/" + id + "?api_key=" + Global.apikey + "");
                JArray r            = JArray.Parse(responserank);
                string rank         = null;
                string usedtiersolo = null;
                string rankflex5    = null;

                //getting icon for thumbnail
                string findlatestlolversion = c.DownloadString("https://ddragon.leagueoflegends.com/api/versions.json");
                JArray latestlolversion     = JArray.Parse(findlatestlolversion);
                var    version      = latestlolversion[0];
                string thumbnailURL = "http://ddragon.leagueoflegends.com/cdn/" + version + "/img/profileicon/" + iconid + ".png";

                var embed = new EmbedBuilder();
                embed.AddField("updating your account...",
                               "Hang on while i update your rank!")
                .WithAuthor(author => { author
                                        .WithName("Birdie Bot")
                                        .WithIconUrl(Global.Birdieicon); })
                .WithThumbnailUrl(thumbnailURL)
                .WithColor(new Color(255, 0, 0))
                .WithTitle("Birdie Bot notification")
                .WithFooter(footer => { footer
                                        .WithText(Global.Botcreatorname)
                                        .WithIconUrl(Global.Birdieicon); })
                .WithCurrentTimestamp()
                .Build();
                var message = await Context.Channel.SendMessageAsync("", false, embed);

                if (responserank == "[]")
                {
                    Console.WriteLine("Unranked given");
                    rank      = "Unranked";
                    rankflex5 = "Unranked";
                }

                //using a for loop to check all the bodies of the json
                //since each queue type is in another body
                for (int x = 0; x < r.Count; x++)
                {
                    if ((string)r[x]["queueType"] == "RANKED_SOLO_5x5")
                    {
                        var    tiersolo = (string)r[x]["tier"];
                        var    division = (string)r[x]["rank"];
                        string soloq    = tiersolo + " " + division;
                        rank         = soloq;
                        usedtiersolo = tiersolo.ToLower();
                    }

                    if (((string)r[x]["queueType"] == "RANKED_FLEX_SR"))
                    {
                        var    tierflex5v5     = (string)r[x]["tier"];
                        var    divisionflex5v5 = (string)r[x]["rank"];
                        string flex5v5         = tierflex5v5 + " " + divisionflex5v5;
                        rankflex5 = flex5v5;
                    }
                    else
                    {
                        rankflex5 = "Unranked";
                    }
                }
                if (usedtiersolo == "" || usedtiersolo == null)
                {
                    usedtiersolo = "Unranked";
                }

                myconn.Open();
                myreader = InsertDiscordname.ExecuteReader();
                myconn.Close();

                //updating the rank of the user
                string       updaterank    = "UPDATE users_testing SET `SOLO_QUEUE` = '" + rank + "', `Discord_Name` = '" + DiscordName + "', `FLEX_5V5` = '" + rankflex5 + "' WHERE Discord_Id like  '%" + UserID + "%';";
                MySqlCommand updatecommand = new MySqlCommand(updaterank, myconn);
                myconn.Open();
                myreader = updatecommand.ExecuteReader();
                myconn.Close();

                var allRanks = new[] { "challenger", "grandMaster", "master", "diamond", "platinum", "gold", "silver", "bronze", "iron", "unranked", "new ones :)" };
                var username = Context.User as SocketGuildUser;

                //running through all the different roles
                for (int x = 0; x < allRanks.GetLength(0); x++)
                {
                    var roles = Context.Guild.Roles.FirstOrDefault(y => y.Name.ToLower() == allRanks[x]);
                    if (username.Roles.Contains(roles))
                    {
                        await(username as IGuildUser).RemoveRoleAsync(roles);
                    }
                }
                var role = Context.Guild.Roles.FirstOrDefault(x => x.Name.ToLower() == usedtiersolo.ToLower());
                await(username as IGuildUser).AddRoleAsync(role);
                Console.WriteLine(Context.User.Username + " Was assigned the role " + usedtiersolo + " on the server " + Context.Guild.Name);


                await Task.Delay(2000);

                await message.ModifyAsync(x => {
                    x.Embed = new EmbedBuilder()
                              .AddField("Your rank has now been updated!",
                                        "if it didnt update, try waiting up to an hour before trying again!")
                              .WithAuthor(author => { author
                                                      .WithName("Birdie Bot")
                                                      .WithIconUrl(Global.Birdieicon); })
                              .WithThumbnailUrl(thumbnailURL)
                              .WithColor(new Color(0, 255, 0))
                              .WithTitle("Birdie Bot notification")
                              .WithFooter(footer => { footer
                                                      .WithText(Global.Botcreatorname)
                                                      .WithIconUrl(Global.Birdieicon); })
                              .WithCurrentTimestamp()
                              .Build();
                });

                await Task.Delay(4000);

                var messages = await Context.Channel.GetMessagesAsync(2).Flatten();

                await Context.Channel.DeleteMessagesAsync(messages);
            }
            catch (Exception ex) {
                Console.WriteLine(ex);
            }
        }
Пример #11
0
Файл: osu.cs Проект: Kyuwu/Bott
        public async Task Osssu([Remainder] string name)
        {
            //https://osu.ppy.sh/api/get_beatmaps?k=00b5c6aaae0d1a09091f08fc294836c893c591de&b=275265"
            try
            {
                var request =
                    WebRequest.Create(
                        $"https://osu.ppy.sh/api/get_user?k=00b5c6aaae0d1a09091f08fc294836c893c591de&u={name}") as
                    HttpWebRequest;
                if (request == null)
                {
                    return;
                }
                request.Method      = "GET";
                request.ContentType = "application/json";

                var myWebResponse = (HttpWebResponse)request.GetResponse();
                var encoding      = Encoding.ASCII;
                using (var reader =
                           new StreamReader(myWebResponse.GetResponseStream() ?? throw new InvalidOperationException(),
                                            encoding))
                {
                    var          result    = reader.ReadToEnd();
                    var          container = (JContainer)JsonConvert.DeserializeObject(result);
                    var          userid    = container[0]["user_id"].ToString();
                    var          username  = container[0]["username"].ToString();
                    EmbedBuilder xd        = new EmbedBuilder
                    {
                        Title        = username,
                        Description  = "Top 10 plays.\n----",
                        ThumbnailUrl = $"https://s.ppy.sh/a/{userid}"
                    };
                    for (int xdd = 0; xdd < 10; xdd++)
                    {
                        var request2 =
                            WebRequest.Create(
                                $"https://osu.ppy.sh/api/get_user_best?k=00b5c6aaae0d1a09091f08fc294836c893c591de&u={userid}")
                            as
                            HttpWebRequest;
                        if (request2 == null)
                        {
                            return;
                        }
                        request2.Method      = "GET";
                        request2.ContentType = "application/json";

                        var myWebResponse2 = (HttpWebResponse)request2.GetResponse();
                        var encoding2      = Encoding.ASCII;
                        using (var reader2 =
                                   new StreamReader(
                                       myWebResponse2.GetResponseStream() ?? throw new InvalidOperationException(),
                                       encoding2))
                        {
                            var result2 = reader2.ReadToEnd();

                            var    container2 = (JContainer)JsonConvert.DeserializeObject(result2);
                            double ppr2       = Convert.ToDouble(container2[xdd]["pp"]);
                            var    date       = container2[xdd]["maxcombo"].ToString();
                            var    bmap       = container2[xdd]["beatmap_id"].ToString();
                            var    rank       = container2[xdd]["rank"].ToString();
                            var    mod        = container2[xdd]["enabled_mods"].ToString();
                            var    c50        = Convert.ToDouble(container2[xdd]["count50"]);
                            var    c100       = Convert.ToDouble(container2[xdd]["count100"]);
                            var    c300       = Convert.ToDouble(container2[xdd]["count300"]);

                            var cmiss      = Convert.ToDouble(container2[xdd]["countmiss"]);
                            var acc2       = 100.0 * (6 * c300 + 2 * c100 + c50) / (6 * (c50 + c100 + c300 + cmiss));
                            var acc        = Math.Round(acc2, 2);
                            var quickmaffs = Math.Round(ppr2, 0);
                            //------------------------------------------------
                            var request3 =
                                WebRequest.Create(
                                    $"https://osu.ppy.sh/api/get_beatmaps?k=00b5c6aaae0d1a09091f08fc294836c893c591de&b={bmap}")
                                as
                                HttpWebRequest;
                            if (request3 == null)
                            {
                                return;
                            }
                            if (rank.Contains("A"))
                            {
                                rank = "<:rankingAsmall:400920344593956867>";
                            }
                            if (rank.Contains("B"))
                            {
                                rank = "<:rankingBsmall:400920320925761538>";
                            }
                            if (rank.Contains("C"))
                            {
                                rank = "<:rankingCsmall:400920375053254656>";
                            }
                            if (rank.Contains("D"))
                            {
                                rank = "<:rankingDsmall:400920408884510721>";
                            }
                            if (rank.Contains("S"))
                            {
                                rank = "<:rankingSsmall:400920431344746517>";
                            }
                            if (rank.Contains("F"))
                            {
                                rank = "<:sectionfail:400920942408368128>";
                            }
                            if (rank.Contains("X"))
                            {
                                rank = "<:rankingXsmall:400920039479574532>";
                            }
                            if (mod.Contains("64"))
                            {
                                mods.AppendLine("DT");
                            }
                            if (mod.Contains("1024"))
                            {
                                mods.AppendLine("FL");
                            }
                            if (mod.Contains("576"))
                            {
                                mods.AppendLine("NC");
                            }
                            if (mod.Contains("16"))
                            {
                                mods.AppendLine("HR");
                            }
                            if (mod.Contains("8"))
                            {
                                mods.AppendLine("RL Pleb");
                            }
                            if (mod.Contains("8"))
                            {
                                mods.AppendLine("HD");
                            }
                            if (mod.Contains("72"))
                            {
                                mods.AppendLine("HDDT");
                            }

                            request3.Method      = "GET";
                            request3.ContentType = "application/json";
                            var myWebResponse3 = (HttpWebResponse)request3.GetResponse();
                            var encoding3      = Encoding.ASCII;
                            using (var reader3 =
                                       new StreamReader(
                                           myWebResponse3.GetResponseStream() ?? throw new InvalidOperationException(),
                                           encoding3))
                            {
                                var result3    = reader3.ReadToEnd();
                                var container3 = (JContainer)JsonConvert.DeserializeObject(result3);

                                var title = container3[0]["title"].ToString();
                                var diff  = container3[0]["version"].ToString();
                                var url   = container3[0]["beatmapset_id"].ToString();
                                var mc    = container3[0]["max_combo"].ToString();
                                var ar    = container3[0]["artist"].ToString();

                                if (mod == "0")
                                {
                                    xd.AddField(x =>
                                    {
                                        x.Name  = $"{ar} - {title} ({diff})";
                                        x.Value =
                                            $"**PP**: {quickmaffs} **Rank:** {rank} **Combo**: {date}({mc})**Accuracy:** {acc}[:arrow_down:](https://osu.ppy.sh/d/{url}) [:information_source:](https://osu.ppy.sh/s/{url})";
                                    });
                                }
                                else if (mod == "592")
                                {
                                    xd.AddField(x =>
                                    {
                                        x.Name  = $"{ar} - {title} ({diff})";
                                        x.Value =
                                            $"**PP**: {quickmaffs} **Rank:** {rank} **Combo**: {date}({mc})**Accuracy:** {acc}[:arrow_down:](https://osu.ppy.sh/d/{url}) [:information_source:](https://osu.ppy.sh/s/{url})";
                                    });
                                }
                                else
                                {
                                    xd.AddField(x =>
                                    {
                                        x.Name  = $"{ar} - {title} ({diff}) +{mods}";
                                        x.Value =
                                            $"**PP**: {quickmaffs} **Rank:** {rank} **Combo**: {date}({mc})**Accuracy:** {acc}[:arrow_down:](https://osu.ppy.sh/d/{url}) [:information_source:](https://osu.ppy.sh/s/{url})";
                                    });
                                    mods.Clear();
                                }
                            }
                        }
                    }
                    await ReplyAsync("", false, xd.Build());
                }
            }



            catch (Exception e)
            {
                await Erroruser();
            }
        }
Пример #12
0
        public async Task Help([Remainder] string postcommand = null)
        {
            List <CommandInfo> commands = _commandService.Commands.ToList();

            if (postcommand == null)
            {
                string url = Context.User.GetAvatarUrl();
                if (url == null)
                {
                    url = Context.User.GetDefaultAvatarUrl();
                }

                //начинаем создание embed
                _embed.WithTitle("Доступные команды:");
                foreach (CommandInfo command in commands)
                {
                    string embedField = command.Summary ?? "Описание недоступно. \n";

                    _embed.AddField($"`{command.Name}`", embedField);
                }
                _embed.WithFooter(footer =>
                {
                    footer
                    .WithIconUrl(url)
                    .WithText($"Вызвано {Context.User.Username}");
                });
                _embed.WithCurrentTimestamp();

                Embed embed = _embed.Build();
                //отправка ответа
                await ReplyAsync(embed : embed);
            }
            else
            {
                var    result = _commandService.Search(Context, postcommand);
                string url    = Context.User.GetAvatarUrl();
                if (url == null)
                {
                    url = Context.User.GetDefaultAvatarUrl();
                }

                _embed.WithFooter(footer =>
                {
                    footer
                    .WithIconUrl(url)
                    .WithText($"Вызвано {Context.User.Username}");
                });
                _embed.WithCurrentTimestamp();

                if (!result.IsSuccess)
                {
                    _embed.WithTitle($"Команда `{postcommand}`");
                    _embed.WithDescription($"*Такой команды не существует.*");
                    _embed.WithColor(255, 000, 000);
                    Embed embed = _embed.Build();
                    //отправка ответа
                    await ReplyAsync(embed : embed);

                    return;
                }

                _embed.WithColor(000, 255, 000);
                _embed.WithTitle($"Команды, похожие на `{postcommand}` ");

                foreach (var match in result.Commands)
                {
                    var cmd = match.Command;

                    List <string> listCommands = new List <string>();
                    listCommands = cmd.Aliases.ToList();

                    for (int i = 0; i < listCommands.Count(); i++)
                    {
                        listCommands[i] = $"`{listCommands[i]}`";
                    }

                    _embed.AddField(field =>
                    {
                        field.Name  = string.Join(", ", listCommands);
                        field.Value = $"**Описание**: {cmd.Summary} \n" +
                                      $"**Параметры**: {string.Join(", ", cmd.Parameters.Select(p => p.Name))}\n" +
                                      $"**Ремарки**: dev {cmd.Remarks}";
                        field.IsInline = false;
                    });
                }
                Embed embedSuccess = _embed.Build();
                await ReplyAsync(embed : embedSuccess);
            }
        }
Пример #13
0
        public static async Task UserJoined(SocketGuildUser user)
        {
            #region Database

            var  guildDb       = new DBGuild(user.Guild.Id);
            bool alreadyJoined = false;
            if (guildDb.Users.Any(u => u.ID.Equals(user.Id))) // if already exists
            {
                guildDb.Users.Find(u => u.ID.Equals(user.Id)).AddUsername(user.Username);
                alreadyJoined = true;
            }
            else
            {
                guildDb.Users.Add(new DBUser(user));
            }
            lock ("db")
            {
                guildDb.Save();
            }

            #endregion Databasae

            #region Logging

            var guildConfig = GenericBot.GuildConfigs[user.Guild.Id];

            if (!(guildConfig.VerifiedRole == 0 || (string.IsNullOrEmpty(guildConfig.VerifiedMessage) || guildConfig.VerifiedMessage.Split().Length < 32 || !user.Guild.Roles.Any(r => r.Id == guildConfig.VerifiedRole))))
            {
                string vMessage = $"Hey {user.Username}! To get verified on **{user.Guild.Name}** reply to this message with the hidden code in the message below\n\n"
                                  + GenericBot.GuildConfigs[user.Guild.Id].VerifiedMessage;

                string verificationMessage =
                    VerificationEngine.InsertCodeInMessage(vMessage, VerificationEngine.GetVerificationCode(user.Id, user.Guild.Id));

                try
                {
                    await user.GetOrCreateDMChannelAsync().Result.SendMessageAsync(verificationMessage);
                }
                catch (Exception ex)
                {
                }
            }
            if (guildConfig.ProbablyMutedUsers.Contains(user.Id))
            {
                try { user.AddRoleAsync(user.Guild.GetRole(guildConfig.MutedRoleId)); }
                catch { }
            }
            if (guildConfig.AutoRoleIds != null && guildConfig.AutoRoleIds.Any())
            {
                foreach (var role in guildConfig.AutoRoleIds)
                {
                    try
                    {
                        await user.AddRoleAsync(user.Guild.GetRole(role));
                    }
                    catch
                    {
                        // Supress
                    }
                }
            }

            if (guildConfig.UserLogChannelId == 0)
            {
                return;
            }

            EmbedBuilder log = new EmbedBuilder()
                               .WithAuthor(new EmbedAuthorBuilder().WithName("User Joined")
                                           .WithIconUrl(user.GetAvatarUrl()).WithUrl(user.GetAvatarUrl()))
                               .WithColor(114, 137, 218)
                               .AddField(new EmbedFieldBuilder().WithName("Username").WithValue(user.ToString().Escape()).WithIsInline(true))
                               .AddField(new EmbedFieldBuilder().WithName("UserId").WithValue(user.Id).WithIsInline(true))
                               .AddField(new EmbedFieldBuilder().WithName("Mention").WithValue(user.Mention).WithIsInline(true))
                               .AddField(new EmbedFieldBuilder().WithName("User Number").WithValue(user.Guild.MemberCount + (!alreadyJoined ? " (New Member)" : "")).WithIsInline(true))
                               .AddField(new EmbedFieldBuilder().WithName("Database Number").WithValue(guildDb.Users.Count + (alreadyJoined ? " (Previous Member)" : "")).WithIsInline(true))
                               .WithFooter($"{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT");

            if ((DateTimeOffset.Now - user.CreatedAt).TotalDays < 7)
            {
                log.AddField(new EmbedFieldBuilder().WithName("New User")
                             .WithValue($"Account made {(DateTimeOffset.Now - user.CreatedAt).Nice()} ago").WithIsInline(true));
            }

            try
            {
                DBUser usr = guildDb.Users.First(u => u.ID.Equals(user.Id));

                if (!usr.Warnings.Empty())
                {
                    string warns = "";
                    for (int i = 0; i < usr.Warnings.Count; i++)
                    {
                        warns += $"{i + 1}: {usr.Warnings.ElementAt(i)}\n";
                    }
                    log.AddField(new EmbedFieldBuilder().WithName($"{usr.Warnings.Count} Warnings")
                                 .WithValue(warns));
                }
            }
            catch
            {
            }

            await user.Guild.GetTextChannel(guildConfig.UserLogChannelId).SendMessageAsync("", embed: log.Build());

            #endregion Logging
        }
Пример #14
0
        public static async Task Resolution_Scaling_P1_PSP_Output_Resolution(SocketGuildUser user, RestUserMessage message)
        {
            // Get the account information of the command's user.
            var account = UserInfoClasses.GetAccount(user);

            // Find the menu session associated with the current user.
            var menuSession = Global.MenuIdList.SingleOrDefault(x => x.User.Id == user.Id);

            var embed  = new EmbedBuilder();
            var author = new EmbedAuthorBuilder
            {
                Name    = "Output Resolution",
                IconUrl = user.GetAvatarUrl()
            };

            embed.WithAuthor(author);

            var footer = new EmbedFooterBuilder
            {
                Text = "↩️ Persona (Remake) Resolution & Scaling Menu"
            };

            embed.WithFooter(footer);

            // Assign a color and thumbnail to the embeded message based on the title being edited.
            embed.WithColor(EmbedSettings.Get_Game_Color("P1-PSP", null));
            embed.WithThumbnailUrl(EmbedSettings.Get_Game_Logo("P1-PSP"));

            embed.WithDescription("" +
                                  "**Choose a resolution to output your scenes in.**\n" +
                                  "\n" +
                                  $"⚙️ **Current setting:** **`{account.P1_PSP_Resolution}`**\n" +
                                  "\n" +
                                  "** **");

            embed.AddField(":one: 480 × 272", "" +
                           "Original PlayStation® Portable output resolution.");

            embed.AddField(":two: 1920 × 1088", "" +
                           "Scaled HD resolution.");

            // Attempt editing the message if it hasn't been deleted by the user yet.
            // If it has, catch the exception, remove the menu entry from the global list, and return.
            try
            {
                // Remove all reactions from the current message.
                await message.RemoveAllReactionsAsync();

                // Edit the current active message by replacing it with the recently created embed.
                await message.ModifyAsync(x => {
                    x.Embed = embed.Build();
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);

                // Remove the menu entry from the global list.
                Global.MenuIdList.Remove(menuSession);

                return;
            }

            // Edit the menu session according to the current message.
            menuSession.CurrentMenu = "Resolution_Scaling_P1_PSP_Output_Resolution";
            menuSession.MenuTimer   = new Timer()
            {
                // Create a timer that expires as a "time out" duration for the user.
                Interval  = MenuConfig.menu.timerDuration,
                AutoReset = false,
                Enabled   = true
            };

            // If the menu timer runs out, activate a function.
            menuSession.MenuTimer.Elapsed += (sender, e) => MenuTimer_Elapsed(sender, e, menuSession);

            // Create an empty list for reactions.
            List <IEmote> reaction_list = new List <IEmote> {
            };

            // Add needed emote reactions for the menu.
            reaction_list.Add(new Emoji("↩️"));
            reaction_list.Add(new Emoji("\u0031\ufe0f\u20e3"));
            reaction_list.Add(new Emoji("\u0032\ufe0f\u20e3"));

            // Add the reactions to the message.
            _ = ReactionHandling.AddReactionsToMenu(message, reaction_list);
        }
Пример #15
0
        public async Task CallHalfSuit(string halfsuit, string callstring)
        {
            callstring = callstring.Trim();

            halfsuit = halfsuit.ToUpperInvariant();

            if (variables[Context.Guild].RedScore + variables[Context.Guild].BlueScore == 9)
            {
                await ReplyAsync(
                    ":checkered_flag: The game has ended! Use the `.reset` command to play again! :checkered_flag:");

                return;
            }

            if (!variables[Context.Guild].GameInProgress)
            {
                await ReplyAsync($":x: Game is not in progress yet! :x:");

                return;
            } // make sure game is in progress

            if (!CardDealer.HalfSuitNames.Contains(halfsuit))
            {
                await ReplyAsync($":x: `{halfsuit}` is not a valid halfsuit! :x:");

                return;
            } // make sure that the halfsuit called is valid

            if (variables[Context.Guild].CalledHalfSuits.Contains(halfsuit))
            {
                await ReplyAsync($":x: `{halfsuit}` was already called! :x:");

                return;
            } // make sure that the halfsuit has not already been called

            var seperatedCallString = callstring.Split(" ");
            var claimedCards        = new List <string>();
            var allClaimed          = new List <string>();
            var cuser      = "";
            var authorName = "";

            foreach (var authorUserPair in variables[Context.Guild].AuthorUsers)
            {
                if (authorUserPair.Value == Context.Message.Author)
                {
                    authorName = authorUserPair.Key;
                }
            }

            var works = true;

            foreach (string strSeg in seperatedCallString)
            {
                string editedSeg = strSeg.Replace("@", "").Replace("<", "").Replace(">", "").Replace("!", "");

                if (editedSeg == "")
                {
                    continue;
                }
                if (!CardDealer.CardNames.Contains(editedSeg) && !variables[Context.Guild].Players.Contains(editedSeg))
                {
                    await ReplyAsync(
                        $":x: `{editedSeg}` not recognized as a card or a player! :x:"); // if a strSeg in the callString is not a player nor a card then it's invalid

                    return;
                }

                if (variables[Context.Guild].Players.Contains(editedSeg)) // if this part of the segStr is a player
                {
                    foreach (string card in claimedCards)
                    {
                        if (!variables[Context.Guild].PlayerCards[cuser].Contains(CardDealer.GetCardByName(card.ToUpperInvariant())))
                        {
                            works = false;
                        }
                    }
                    cuser = editedSeg;

                    if (variables[Context.Guild].TeamDict[cuser] !=
                        variables[Context.Guild].TeamDict[authorName])
                    {
                        await ReplyAsync($":x: callString included players not on your team! :x:");

                        return;
                    }

                    claimedCards = new List <string>();
                }
                else
                {
                    if (CardDealer.CardNames.Contains(editedSeg))
                    {
                        claimedCards.Add(editedSeg);
                        allClaimed.Add(editedSeg);
                    }
                }
            }

            foreach (string card in claimedCards)
            {
                if (!variables[Context.Guild].PlayerCards[cuser].Contains(CardDealer.GetCardByName(card)))
                {
                    works = false;
                }
            }

            int hsindex = CardDealer.HalfSuitNames.IndexOf(halfsuit);

            foreach (string _ in allClaimed)
            {
                for (var i = 0; i < 6; i++)
                {
                    if (!allClaimed.Contains(CardDealer.CardNames[hsindex * 6 + i]))
                    {
                        await ReplyAsync(":x: Cards do not match up with the halfsuit :x:");

                        return;
                    }
                }
            }

            for (var i = 0; i < 6; i++) // cards
            {
                foreach (string t in variables[Context.Guild].Players)
                {
                    variables[Context.Guild].PlayerCards[t]
                    .Remove(CardDealer.GetCardByName(CardDealer.CardNames[hsindex * 6 + i]));
                }
            }


            var username = "";

            foreach (var player in variables[Context.Guild].AuthorUsers)
            {
                if (player.Value == Context.User)
                {
                    username = player.Key;
                }
            }

            await CardDealer.SendCards(Context.Guild);

            string team = variables[Context.Guild].TeamDict[username];

            var builder = new EmbedBuilder {
                Title = ":telephone_receiver: HalfSuit Call :telephone_receiver:"
            };

            if (works)
            {
                variables[Context.Guild].AlgebraicNotation += $"callhs {username} {halfsuit} {callstring} hit;";

                builder.Color       = Color.Green;
                builder.Description = $":boom: <@{username}> **hit** the `{halfsuit}`! :boom:";
                if (team == "red")
                {
                    variables[Context.Guild].RedScore++;
                }
                else
                {
                    variables[Context.Guild].BlueScore++;
                }
            }
            else
            {
                variables[Context.Guild].AlgebraicNotation += $"callhs {username} {halfsuit} {callstring} miss;";

                builder.Color       = Color.DarkRed;
                builder.Description = $":thinking: <@{username}> **missed** the `{halfsuit}`! :thinking:";
                if (team == "red")
                {
                    variables[Context.Guild].BlueScore++;
                }
                else
                {
                    variables[Context.Guild].RedScore++;
                }
            }

            variables[Context.Guild].CalledHalfSuits.Add(halfsuit);
            builder.AddField("Score Update",
                             $"Blue Team: {variables[Context.Guild].BlueScore}\n Red Team: {variables[Context.Guild].RedScore}");

            await ReplyAsync("", false, builder.Build());

            if (variables[Context.Guild].RedScore + variables[Context.Guild].BlueScore >= 9)
            {
                // maybe refactor this and combine with the one in gamemodule
                var builder2 = new EmbedBuilder {
                    Title = "Game Result!"
                };

                if (variables[Context.Guild].RedScore > variables[Context.Guild].BlueScore)
                {
                    builder2.Color       = Color.Red;
                    builder2.Description = ":red_circle: Red team wins! :red_circle:";
                }
                else
                {
                    builder2.Color       = Color.Blue;
                    builder2.Description = ":large_blue_circle: Blue team wins! :large_blue_circle:";
                }

                builder2.AddField("Final Scores",
                                  $"Blue Team: {variables[Context.Guild].BlueScore}\n Red Team: {variables[Context.Guild].RedScore}");
                await ReplyAsync("", false, builder2.Build());

                await ReplyAsync(":checkered_flag: The game has ended! Use the `.reset` command to play again! :checkered_flag:");

                File.WriteAllText("afn.txt", variables[Context.Guild].AlgebraicNotation);
                // end of that upper comment thing
            }
            else
            {
                if (variables[Context.Guild].RedScore >= 5)
                {
                    await ReplyAsync("Red Team has clinched the game!! Use `.reset` to stop the game now, or continue playing!");

                    variables[Context.Guild].GameClinch = true;
                }
                else if (variables[Context.Guild].BlueScore >= 5)
                {
                    await ReplyAsync("Blue Team has clinched the game!! Use `.reset` to stop the game now, or continue playing!");

                    variables[Context.Guild].GameClinch = true;
                }
            }

            if (CheckPlayerTurnHandEmpty() && variables[Context.Guild].GameInProgress)
            {
                string newPlayerID = variables[Context.Guild].PlayerTurn;

                if (variables[Context.Guild].TeamDict[variables[Context.Guild].PlayerTurn] == "red")
                {
                    // red team
                    int loopCount   = 0;
                    int playerIndex = variables[Context.Guild].RedTeam.FindIndex(a => a == newPlayerID);
                    do
                    {
                        if (loopCount++ > variables[Context.Guild].BlueTeam.Count)
                        {
                            break;
                        }
                        playerIndex = variables[Context.Guild].RedTeam.FindIndex(a => a == newPlayerID);
                        newPlayerID = variables[Context.Guild].RedTeam[(playerIndex + 1) % variables[Context.Guild].RedTeam.Count];
                    } while (variables[Context.Guild].PlayerCards[newPlayerID].Count == 0);
                }
                else if (variables[Context.Guild].TeamDict[variables[Context.Guild].PlayerTurn] == "blue")
                {
                    // blue team
                    int loopCount   = 0;
                    int playerIndex = variables[Context.Guild].BlueTeam.FindIndex(a => a == newPlayerID);
                    do
                    {
                        if (loopCount++ > variables[Context.Guild].BlueTeam.Count)
                        {
                            break;
                        }
                        playerIndex = variables[Context.Guild].BlueTeam.FindIndex(a => a == newPlayerID);
                        newPlayerID = variables[Context.Guild].BlueTeam[(playerIndex + 1) % variables[Context.Guild].BlueTeam.Count];
                    } while (variables[Context.Guild].PlayerCards[newPlayerID].Count == 0);
                }

                await ReplyAsync($":open_mouth: <@{variables[Context.Guild].PlayerTurn}> is out of cards! Turn will move to <@{newPlayerID}> :open_mouth:");

                variables[Context.Guild].PlayerTurn = newPlayerID;
                //await ReplyAsync($":open_mouth: {variables[Context.Guild].PlayerTurn} is out of cards! Use the `.designate` command to select the next player! :open_mouth:");
                //variables[Context.Guild].NeedsDesignatedPlayer = true;
                //variables[Context.Guild].Designator = variables[Context.Guild].PlayerTurn.Replace("@", "").Replace("<", "").Replace(">", "").Replace("!", "");
            }
        }
        public async Task SendEmbedFromCli(CommandArguments cmdArgs, IUser pmInstead = null)
        {
            if (string.IsNullOrEmpty(cmdArgs.TrimmedMessage) || cmdArgs.TrimmedMessage == "-h" || cmdArgs.TrimmedMessage == "--help")
            {
                await cmdArgs.SendReplySafe("```md\nCreate an embed using the following parameters:\n" +
                                            "[ --channel     ] Channel where to send the embed.\n" +
                                            "[ --edit <msgId>] Replace a MessageId with a new embed (use after --channel)\n" +
                                            "[ --text        ] Regular content text\n" +
                                            "[ --title       ] Title\n" +
                                            "[ --description ] Description\n" +
                                            "[ --footer      ] Footer\n" +
                                            "[ --color       ] #rrggbb hex color used for the embed stripe.\n" +
                                            "[ --image       ] URL of a Hjuge image in the bottom.\n" +
                                            "[ --thumbnail   ] URL of a smol image on the side.\n" +
                                            "[ --fieldName   ] Create a new field with specified name.\n" +
                                            "[ --fieldValue  ] Text value of a field - has to follow a name.\n" +
                                            "[ --fieldInline ] Use to set the field as inline.\n" +
                                            "Where you can repeat the field* options multiple times.\n```"
                                            );

                return;
            }

            SocketTextChannel channel = null;

            bool              debug        = false;
            string            text         = null;
            IMessage          msg          = null;
            EmbedFieldBuilder currentField = null;
            EmbedBuilder      embedBuilder = new EmbedBuilder();

            foreach (Match match in this.RegexCliParam.Matches(cmdArgs.TrimmedMessage))
            {
                string optionString = this.RegexCliOption.Match(match.Value).Value;

                if (optionString == "--debug")
                {
                    if (IsGlobalAdmin(cmdArgs.Message.Author.Id) || IsSupportTeam(cmdArgs.Message.Author.Id))
                    {
                        debug = true;
                    }
                    continue;
                }

                if (optionString == "--fieldInline")
                {
                    if (currentField == null)
                    {
                        await cmdArgs.SendReplySafe($"`fieldInline` can not precede `fieldName`.");

                        return;
                    }

                    currentField.WithIsInline(true);
                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Setting inline for field `{currentField.Name}`");
                    }
                    continue;
                }

                string value;
                if (match.Value.Length <= optionString.Length || string.IsNullOrWhiteSpace(value = match.Value.Substring(optionString.Length + 1).Trim()))
                {
                    await cmdArgs.SendReplySafe($"Invalid value for `{optionString}`");

                    return;
                }

                if (value.Length >= UserProfileOption.ValueCharacterLimit)
                {
                    await cmdArgs.SendReplySafe($"`{optionString}` is too long! (It's {value.Length} characters while the limit is {UserProfileOption.ValueCharacterLimit})");

                    return;
                }

                switch (optionString)
                {
                case "--channel":
                    if (!guid.TryParse(value.Trim('<', '>', '#'), out guid id) || (channel = cmdArgs.Server.Guild.GetTextChannel(id)) == null)
                    {
                        await cmdArgs.SendReplySafe($"Channel {value} not found.");

                        return;
                    }

                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Channel set: `{channel.Name}`");
                    }

                    break;

                case "--text":
                    if (value.Length > GlobalConfig.MessageCharacterLimit)
                    {
                        await cmdArgs.SendReplySafe($"`--text` is too long (`{value.Length} > {GlobalConfig.MessageCharacterLimit}`)");

                        return;
                    }

                    text = value;
                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Text set: `{value}`");
                    }

                    break;

                case "--title":
                    if (value.Length > 256)
                    {
                        await cmdArgs.SendReplySafe($"`--title` is too long (`{value.Length} > 256`)");

                        return;
                    }

                    embedBuilder.WithTitle(value);
                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Title set: `{value}`");
                    }

                    break;

                case "--description":
                    if (value.Length > 2048)
                    {
                        await cmdArgs.SendReplySafe($"`--description` is too long (`{value.Length} > 2048`)");

                        return;
                    }

                    embedBuilder.WithDescription(value);
                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Description set: `{value}`");
                    }

                    break;

                case "--footer":
                    if (value.Length > 2048)
                    {
                        await cmdArgs.SendReplySafe($"`--footer` is too long (`{value.Length} > 2048`)");

                        return;
                    }

                    embedBuilder.WithFooter(value);
                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Description set: `{value}`");
                    }

                    break;

                case "--image":
                    try
                    {
                        embedBuilder.WithImageUrl(value.Trim('<', '>'));
                    }
                    catch (Exception)
                    {
                        await cmdArgs.SendReplySafe($"`--image` is invalid url");

                        return;
                    }

                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Image URL set: `{value}`");
                    }

                    break;

                case "--thumbnail":
                    try
                    {
                        embedBuilder.WithThumbnailUrl(value.Trim('<', '>'));
                    }
                    catch (Exception)
                    {
                        await cmdArgs.SendReplySafe($"`--thumbnail` is invalid url");

                        return;
                    }

                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Thumbnail URL set: `{value}`");
                    }

                    break;

                case "--color":
                    try
                    {
                        uint color = uint.Parse(value.TrimStart('#'), System.Globalization.NumberStyles.AllowHexSpecifier);
                        if (color > uint.Parse("FFFFFF", System.Globalization.NumberStyles.AllowHexSpecifier))
                        {
                            await cmdArgs.SendReplySafe("Color out of range.");

                            return;
                        }

                        embedBuilder.WithColor(color);
                        if (debug)
                        {
                            await cmdArgs.Channel.SendMessageSafe($"Color `{value}` set.");
                        }
                    }
                    catch (Exception)
                    {
                        await cmdArgs.SendReplySafe("Invalid color format.");

                        return;
                    }
                    break;

                case "--fieldName":
                    if (value.Length > 256)
                    {
                        await cmdArgs.SendReplySafe($"`--fieldName` is too long (`{value.Length} > 256`)\n```\n{value}\n```");

                        return;
                    }

                    if (currentField != null && currentField.Value == null)
                    {
                        await cmdArgs.SendReplySafe($"Field `{currentField.Name}` is missing a value!");

                        return;
                    }

                    if (embedBuilder.Fields.Count >= 25)
                    {
                        await cmdArgs.SendReplySafe("Too many fields! (Limit is 25)");

                        return;
                    }

                    embedBuilder.AddField(currentField = new EmbedFieldBuilder().WithName(value));
                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Creating new field `{currentField.Name}`");
                    }

                    break;

                case "--fieldValue":
                    if (value.Length > 1024)
                    {
                        await cmdArgs.SendReplySafe($"`--fieldValue` is too long (`{value.Length} > 1024`)\n```\n{value}\n```");

                        return;
                    }

                    if (currentField == null)
                    {
                        await cmdArgs.SendReplySafe($"`fieldValue` can not precede `fieldName`.");

                        return;
                    }

                    currentField.WithValue(value);
                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Setting value:\n```\n{value}\n```\n...for field:`{currentField.Name}`");
                    }

                    break;

                case "--edit":
                    if (!guid.TryParse(value, out guid msgId) || (msg = await channel?.GetMessageAsync(msgId)) == null)
                    {
                        await cmdArgs.SendReplySafe($"`--edit` did not find a message with ID `{value}` in the <#{(channel?.Id ?? 0)}> channel.");

                        return;
                    }

                    break;

                default:
                    await cmdArgs.SendReplySafe($"Unknown option: `{optionString}`");

                    return;
                }
            }

            if (currentField != null && currentField.Value == null)
            {
                await cmdArgs.SendReplySafe($"Field `{currentField.Name}` is missing a value!");

                return;
            }

            switch (msg)
            {
            case null:
                if (pmInstead != null)
                {
                    await pmInstead.SendMessageAsync(text : text, embed : embedBuilder.Build());
                }
                else if (channel == null)
                {
                    await cmdArgs.SendReplySafe(text : text, embed : embedBuilder.Build());
                }
                else
                {
                    await channel.SendMessageAsync(text : text, embed : embedBuilder.Build());
                }
                break;

            case RestUserMessage message:
                await message?.ModifyAsync(m => {
                    m.Content = text;
                    m.Embed   = embedBuilder.Build();
                });

                break;

            case SocketUserMessage message:
                await message?.ModifyAsync(m => {
                    m.Content = text;
                    m.Embed   = embedBuilder.Build();
                });

                break;

            default:
                await cmdArgs.SendReplySafe("GetMessage went bork.");

                break;
            }
        }
Пример #17
0
        /// <summary>
        /// Execute command
        /// </summary>
        /// <param name="commandArguments">Command arguments</param>
        /// <returns>Command result</returns>
        public ECommandResult Execute(ICommandArguments commandArguments)
        {
            ECommandResult ret = ECommandResult.Failed;

            ICommands[]       commands_services  = commandArguments.Bot.GetServices <ICommands>();
            IChat[]           chat_services      = commandArguments.Bot.GetServices <IChat>();
            HelpConfiguration help_configuration = commandArguments.Bot.GetService <HelpConfiguration>();

            if ((commands_services != null) && (chat_services != null) && (help_configuration != null))
            {
                List <Embed> embeds = new List <Embed>();
                if (commandArguments.Arguments.Count > 0)
                {
                    string command_string = commandArguments.Arguments[0];
                    List <KeyValuePair <ICommands, ICommand> > command_list = new List <KeyValuePair <ICommands, ICommand> >();
                    foreach (ICommands commands in commands_services)
                    {
                        ICommand command = commands.FindCommand(command_string);
                        if (command != null)
                        {
                            command_list.Add(new KeyValuePair <ICommands, ICommand>(commands, command));
                        }
                    }
                    if (command_list.Count > 0)
                    {
                        foreach (KeyValuePair <ICommands, ICommand> command in command_list)
                        {
                            EmbedBuilder embed_builder = PrepareEmbedBuilder("Help topic for command \"" + command.Value.Name + "\"");
                            embed_builder.AddField("Command", command.Value.Name, true);
                            embed_builder.AddField("Description", command.Value.Description, true);
                            embed_builder.AddField("Full description", command.Value.FullDescription);
                            StringBuilder required_privileges = new StringBuilder();
                            foreach (KeyValuePair <string, uint> privilege in command.Value.ForceRequiredPrivileges)
                            {
                                required_privileges.Append("\"");
                                required_privileges.Append(privilege.Key);
                                required_privileges.Append("\" : ");
                                required_privileges.Append(privilege.Value.ToString());
                            }
                            if (required_privileges.Length > 0)
                            {
                                embed_builder.AddField("Required privileges", required_privileges);
                            }
                            ICommandGroup command_group = command.Key.GetCommandGroup(command.Value.CommandGroup);
                            if (command_group != null)
                            {
                                StringBuilder more_commands = new StringBuilder();
                                bool          first         = true;
                                foreach (ICommand command_group_command in command.Key.FromCommandGroup(command_group))
                                {
                                    if (first)
                                    {
                                        first = false;
                                    }
                                    else
                                    {
                                        more_commands.Append(", ");
                                    }
                                    more_commands.Append(command_group_command.Name);
                                }
                                if (first)
                                {
                                    more_commands.Append("No commands?");
                                }
                                embed_builder.AddField("More commands " + command_group.Icon, more_commands.ToString());
                            }
                            embeds.Add(embed_builder.Build());
                        }
                    }
                    else
                    {
                        List <KeyValuePair <ICommands, ICommandGroup> > command_group_list = new List <KeyValuePair <ICommands, ICommandGroup> >();
                        string command_group_name_key = commandArguments.Arguments[0].Trim().ToLower();
                        foreach (ICommands commands in commands_services)
                        {
                            ICommandGroup command_group = commands.GetCommandGroup(command_string);
                            if (command_group != null)
                            {
                                if (command_group.Name.Trim().ToLower() == command_group_name_key)
                                {
                                    command_group_list.Add(new KeyValuePair <ICommands, ICommandGroup>(commands, command_group));
                                }
                            }
                        }
                        if (command_group_list.Count > 0)
                        {
                            foreach (KeyValuePair <ICommands, ICommandGroup> command_group in command_group_list)
                            {
                                EmbedBuilder  embed_builder          = PrepareEmbedBuilder("Help topic for command group \"" + command_group.Value.Icon + " " + command_group.Value.Name + "\"");
                                StringBuilder command_group_commands = new StringBuilder();
                                bool          first = true;
                                foreach (ICommand command_group_command in command_group.Key.FromCommandGroup(command_group.Value))
                                {
                                    if (first)
                                    {
                                        first = false;
                                    }
                                    else
                                    {
                                        command_group_commands.Append(", ");
                                    }
                                    command_group_commands.Append(command_group_command.Name);
                                }
                                if (first)
                                {
                                    command_group_commands.Append("No commands?");
                                }
                                embed_builder.AddField("Commands", command_group_commands.ToString());
                                command_group_commands.Clear();
                                embeds.Add(embed_builder.Build());
                            }
                        }
                        else
                        {
                            foreach (ICommands commands in commands_services)
                            {
                                EmbedBuilder embed_builder = PrepareEmbedBuilder();
                                embed_builder.WithTitle("Help topics similar to \"" + command_string + "\"");
                                StringBuilder all_commands_groups = new StringBuilder();
                                bool          first = true;
                                foreach (ICommand command in commands.AvailableCommands)
                                {
                                    if (Levenshtein.GetDistance(command_string, command.Name) <= help_configuration.Data.MaximumLevenshteinDistance)
                                    {
                                        if (first)
                                        {
                                            first = false;
                                        }
                                        else
                                        {
                                            all_commands_groups.Append(", ");
                                        }
                                        all_commands_groups.Append(command.Name);
                                    }
                                }
                                if (first)
                                {
                                    all_commands_groups.Append("No similar commands found");
                                }
                                embed_builder.AddField("Commands", all_commands_groups.ToString());
                                all_commands_groups.Clear();
                                first = true;
                                foreach (ICommandGroup command_group in commands.AvailableCommandGroups)
                                {
                                    if (Levenshtein.GetDistance(command_string, command_group.Name) <= help_configuration.Data.MaximumLevenshteinDistance)
                                    {
                                        if (first)
                                        {
                                            first = false;
                                        }
                                        else
                                        {
                                            all_commands_groups.Append(", ");
                                        }
                                        all_commands_groups.Append(command_group.Icon);
                                        all_commands_groups.Append(" ");
                                        all_commands_groups.Append(command_group.Name);
                                    }
                                }
                                if (first)
                                {
                                    all_commands_groups.Append("No similar command groups found");
                                }
                                embed_builder.AddField("Command groups", all_commands_groups.ToString());
                                embeds.Add(embed_builder.Build());
                            }
                        }
                        command_group_list.Clear();
                    }
                    command_list.Clear();
                }
                else
                {
                    foreach (ICommands commands in commands_services)
                    {
                        EmbedBuilder  embed_builder          = PrepareEmbedBuilder("Help topics");
                        StringBuilder command_group_commands = new StringBuilder();
                        foreach (ICommandGroup command_group in commands.AvailableCommandGroups)
                        {
                            bool first = true;
                            command_group_commands.Clear();
                            foreach (ICommand command_group_command in commands.FromCommandGroup(command_group))
                            {
                                if (first)
                                {
                                    first = false;
                                }
                                else
                                {
                                    command_group_commands.Append(", ");
                                }
                                command_group_commands.Append(command_group_command.Name);
                            }
                            if (first)
                            {
                                command_group_commands.Append("No commands specified yet.");
                            }
                            embed_builder.AddField(command_group.Icon + " " + command_group.Name, command_group_commands.ToString());
                        }
                        embeds.Add(embed_builder.Build());
                    }
                }
                foreach (IChat chat in chat_services)
                {
                    foreach (Embed embed in embeds)
                    {
                        chat.SendEmbedAsync(embed, commandArguments.MessageChannel);
                    }
                }
                embeds.Clear();
                ret = ECommandResult.Successful;
            }
            return(ret);
        }
Пример #18
0
            public async Task Raffle()
            {
                if (MidRaffle)
                {
                    return;
                }
                if (!HasPerms())
                {
                    var build = new EmbedBuilder()
                    {
                        Color = Color.Red,
                    };
                    string desc = null;
                    desc += $"Command reserved for Kingpins!";
                    build.Description = desc;
                    await ReplyAsync("", false, build.Build());

                    return;
                }


                if (Program.LottoList.TicketCount.Count <= 1)
                {
                    var builder = new EmbedBuilder()
                    {
                        Color = Color.Red,
                    };
                    string description = null;
                    description        += $"Not enough participants to start the raffle! <:omg:438433957173002242>";
                    builder.Description = description;
                    await ReplyAsync("", false, builder.Build());

                    return;
                }

                MidRaffle = true;
                Random rng          = new Random();
                Random list         = new Random();
                Random RandomMember = new Random();

                Shuffle(lottotickets);
                var builders = new EmbedBuilder()
                {
                    Color       = new Color(114, 137, 218),
                    Description = $"Total pot: {lottotickets.Count} <:perin:462691285308932098>, Good Luck!"
                };
                string descriptions = $"Starting Lottery in 3...";

                builders.AddField(x =>
                {
                    x.Name     = "Start up";
                    x.Value    = descriptions;
                    x.IsInline = false;
                });
                var Message = await ReplyAsync("", false, builders.Build());

                Thread.Sleep(1000);
                for (int i = 2; i >= 1; i--)
                {
                    descriptions = $"Starting Lottery in {i}...";

                    if (!string.IsNullOrWhiteSpace(descriptions))
                    {
                        builders.Fields.FirstOrDefault(x => x.Name == "Start up").Value =
                            $"Starting Lottery in {i}...";
                        await Message.ModifyAsync(msg => msg.Embed = builders.Build());
                    }
                    Thread.Sleep(1000);
                }

                builders.Fields.FirstOrDefault(x => x.Name == "Start up").Value = "In Progress...";
                await Message.ModifyAsync(msg => msg.Embed = builders.Build());

                int loops            = list.Next(16, 30);
                var next             = RandomMember.Next(0, Program.LottoList.TicketCount.Count);
                var messageToDisplay = Program.LottoList.TicketCount[next].Name;
                var mention          = Context.Guild.GetUserAsync(messageToDisplay).Result;

                builders.AddField(x =>
                {
                    x.Name     = "Raffle";
                    x.Value    = mention.Nickname ?? mention.Username;
                    x.IsInline = false;
                });
                await Message.ModifyAsync(msg => msg.Embed = builders.Build());

                for (int i = 0; i <= loops; i++)
                {
                    Thread.Sleep(rng.Next(50, 150));
                    var m = messageToDisplay;
                    while (messageToDisplay == m)
                    {
                        next             = RandomMember.Next(0, Program.LottoList.TicketCount.Count);
                        messageToDisplay = Program.LottoList.TicketCount[next].Name;
                    }
                    var ment = Context.Guild.GetUserAsync(messageToDisplay).Result;
                    builders.Fields.FirstOrDefault(x => x.Name == "Raffle").Value =
                        ment.Nickname ?? ment.Username;
                    await Message.ModifyAsync(msg => msg.Embed = builders.Build());
                }
                next    = RandomMember.Next(0, lottotickets.Count);
                mention = Context.Guild.GetUserAsync(lottotickets[next]).Result;
                builders.Fields.FirstOrDefault(x => x.Name == "Raffle").Value =
                    mention.Nickname ?? mention.Username;

                await Message.ModifyAsync(msg => msg.Embed = builders.Build());

                Thread.Sleep(800);
                builders.Fields.FirstOrDefault(x => x.Name == "Start up").Value = "Finished";
                builders.AddField(x =>
                {
                    x.Name     = ":trophy:";
                    x.Value    = $"{mention.Mention} won the lottery! Congratulations! <:rich:438433957755748353>";
                    x.IsInline = false;
                });
                await Message.ModifyAsync(msg => msg.Embed = builders.Build());

                lottotickets.Clear();
                Program.LottoList.TicketCount.Clear();
                WriteToJson(Program.LottoList.TicketCount);
                MidRaffle = false;
            }
Пример #19
0
        public async Task HelpCommand([Remainder] string para = null)
        {
            if (para == null)
            {
                await HelpCommand();

                return;
            }
            para = para.ToLower();
            var embed = new EmbedBuilder().WithColor(Color.Orange);

            var module = commands.Modules
                         .FirstOrDefault(x => x.Name.StartsWithIgnoreCase(para))
                         ?? (int.TryParse(para, out int result) ? commands.Modules
                             .OrderBy(x => x.Remarks ?? "Module Z")
                             .ElementAtOrDefault(result - 1)
                : null);

            if (module != null)
            {
                var commandList = GetCommnadListFormatted(module);
                embed.WithAuthor("📦 Module Information")
                .WithTitle(module.Name)
                .WithDescription(module.Summary ?? "In Development".MarkdownCodeBlock())
                .AddField("Commands", commandList);
                goto helpReplyProcedure;
            }

            para = para.StartsWith(prefix) ? para.Substring(prefix.Length) : para;
            var command = commands.Commands
                          .Where(x => x.Name.EqualsIgnoreCase(para) || x.Aliases.Any(y => y.EqualsIgnoreCase(para)))
                          .ToList();

            if (command.Count > 0)
            {
                command.Sort((a, b) => a.Name == para ? -1 : 1);
                var    baseCommand        = command.First();
                string commandDescription = "";
                command.ForEach(x =>
                {
                    commandDescription =
                        !commandDescription.Contains(x.Summary ?? "") ?
                        commandDescription + (x.Summary == null ? "" : x.Summary.AddSpace()) : commandDescription;
                });
                commandDescription = commandDescription == "" ? "In Development".MarkdownCodeBlock() : commandDescription;
                embed.WithAuthor("📃 Command Information")
                .WithTitle(baseCommand.Name)
                .WithDescription(commandDescription);
                if (baseCommand.Aliases.Count > 0)
                {
                    var alias = baseCommand.Aliases.Select(x => $"{(prefix + x).MarkdownCodeLine()}\t");
                    embed.AddField("Alias", string.Join(" ", alias));
                }
                string restrictions = null;
                baseCommand.Module.Preconditions
                .ToList()
                .ForEach(x => restrictions += x.GetDescription().MarkdownCodeLine().AddLine());
                baseCommand.Preconditions
                .ToList()
                .ForEach(x => restrictions += x.GetDescription().MarkdownCodeLine().AddLine());
                if (restrictions != null)
                {
                    embed.AddField("Restrictions", restrictions);
                }

                var usages = command.Select(x => $"{prefix}{x.Name.AddSpace() + x.GetCommandParametersInfo()}");
                embed.AddField("Usage", string.Join("\n", usages).MarkdownCodeBlock("css"));

                string example = "";
                command.ForEach(x => example += x.Remarks != null ? x.Remarks.AddLine() : "");
                if (example != "")
                {
                    embed.AddField("Example", example.MarkdownCodeBlock("ts"));
                }

                embed.WithFooter($"📦 {baseCommand.Module.Name} module");

                goto helpReplyProcedure;
            }

            embed.WithDescription("🔎 module / command not found.");

helpReplyProcedure:
            await ReplyAsync(embed : embed.Build());
        }
Пример #20
0
        public async Task Report()
        {
            if (Config.ReportBanned.Contains(Context.User.Id))
            {
                await ReplyAsync(":x: You have been banned from using the report system.");

                return;
            }
            if (!(Context.Channel is IDMChannel))
            {
                await ReplyAsync(":x: Please only use the report system in DMs.");

                return;
            }

            await ReplyAsync(":exclamation: Welcome to the report system. We're sorry for the problem you are dealing with. You can reply with `cancel` at any time to cancel your report.");
            await ReplyAsync(":exclamation: NOTE: Misusing or spamming the report system will get you banned from using it.");

            //Ask if anonymous
anonymous:
            await ReplyAsync("Do you wish to remain anonymous? Your User ID will be recorded regardless for security reasons. (`Y`/`N`)");

            SocketMessage msg = await NextMessageAsync(true, true, TimeSpan.FromSeconds(120));

            if (msg.Content == "cancel")
            {
                goto cancel;
            }
            bool anon = false;

            switch (msg.Content.ToLower())
            {
            case "y":
                anon = true;
                break;

            case "n":
                anon = false;
                break;

            default:
                await ReplyAsync(":x: I don't understand. Please answer with `Y` or `N`.");

                goto anonymous;
            }

            //Get user(s) reported
            await ReplyAsync("Please specify the user(s) reported, each in one message. You can enter usernames, but IDs are preferred.");
            await ReplyAsync("Please reply with `done` after all usernames have been entered.");

            List <string> userlist = new List <string>();

            while (true)
            {
user2:
                msg = await NextMessageAsync(true, true, TimeSpan.FromSeconds(120));

                if (msg == null)
                {
                    goto user2;
                }
                if (msg.Content == "cancel")
                {
                    goto cancel;
                }
                if (msg.Content != "done")
                {
                    userlist.Add(msg.Content);
                }
                else if (userlist.Count() != 0)
                {
                    break;
                }
                else
                {
                    await ReplyAsync(":x: Please specify at least one user.");

                    goto user2;
                }
                IEmote emote = new Emoji("✅");
                await(msg as IUserMessage).AddReactionAsync(emote);
            }

            //Get messages
            await ReplyAsync("Please specify any offending messages, each in one message. Please use message links, or IDs.");
            await ReplyAsync("Please reply with `done` after all messages have been entered.");

            List <string> msglist = new List <string>();

            while (true)
            {
messages2:
                msg = await NextMessageAsync(true, true, TimeSpan.FromSeconds(120));

                if (msg == null)
                {
                    goto messages2;
                }
                if (msg.Content == "cancel")
                {
                    goto cancel;
                }
                if (msg.Content != "done")
                {
                    msglist.Add(msg.Content);
                }
                else if (msglist.Count() != 0)
                {
                    break;
                }
                else
                {
                    await ReplyAsync(":x: Please specify at least one message.");

                    goto messages2;
                }
                IEmote emote = new Emoji("✅");
                await(msg as IUserMessage).AddReactionAsync(emote);
            }

            //Get notes
            await ReplyAsync("Any notes you want to add? Type `none` if not.");

            string notes = "N/A";

notes2:
            msg = await NextMessageAsync(true, true, TimeSpan.FromSeconds(120));

            if (msg == null)
            {
                goto notes2;
            }
            if (msg.Content == "cancel")
            {
                goto cancel;
            }
            if (msg.Content.ToLower() != "none")
            {
                notes = msg.Content;
                IEmote emote = new Emoji("✅");
                await(msg as IUserMessage).AddReactionAsync(emote);
            }

            //Finish up
            await ReplyAsync(":white_check_mark: Thank you for your report. We'll look into your case as soon as possible.");

            //Prep embed
            EmbedBuilder embed = new EmbedBuilder();

            embed.WithTitle("User Report");
            switch (anon)
            {
            case true:
                embed.WithDescription("User: `anonymous`.");
                break;

            case false:
                embed.WithDescription($"User: `{Context.User.Username}`");
                break;
            }
            foreach (string user in userlist)
            {
                embed.AddField("Offending user", user);
            }
            foreach (string message in msglist)
            {
                embed.AddField("Message", message);
            }
            embed.AddField("Notes", notes);
            embed.WithFooter($"{DateTime.Now} | User ID: {Context.User.Id}");

            SocketGuild        guild   = Context.Client.Guilds.FirstOrDefault();
            SocketGuildChannel channel = guild.Channels.FirstOrDefault(x => x.Id == Methods.Data.GetChnlId("moderation-log"));

            await(channel as SocketTextChannel).SendMessageAsync($"{guild.Roles.Where(x => x.Name == "Moderator").FirstOrDefault().Mention}", false, embed.Build());
            return;

cancel:
            IEmote emote_ = new Emoji("❌");

            await(msg as IUserMessage).AddReactionAsync(emote_);
            return;
        }
Пример #21
0
        public async Task UpdateEntry(SocketCommandContext context, string shareUrl, string title, string tags)
        {
            using (var soraContext = new SoraContext())
            {
                var userDb = Utility.OnlyGetUser(context.User.Id, soraContext);
                if (userDb == null || userDb.ShareCentrals.Count == 0)
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "You have no playlists"));

                    return;
                }
                var shareResult = userDb.ShareCentrals.FirstOrDefault(x => x.ShareLink == shareUrl);
                if (shareResult == null)
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "No playlist found with that URL!"));

                    return;
                }

                string[] seperatedTags;
                if (tags.IndexOf(";", StringComparison.Ordinal) < 1)
                {
                    seperatedTags = new[] { tags };
                }
                else
                {
                    seperatedTags = tags.Split(";");
                }
                List <string> betterTags = new List <string>();
                foreach (var tag in seperatedTags)
                {
                    string finalTag = tag;
                    if (finalTag.Contains(";"))
                    {
                        finalTag = finalTag.Replace(";", "");
                    }
                    if (!string.IsNullOrWhiteSpace(finalTag))
                    {
                        betterTags.Add(finalTag.Trim());
                    }
                }
                if (betterTags.Count < 1)
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                                                  "Add at least one Tag!").WithDescription("Tags must be added like this: `trap;edm;chill music;other`"));

                    return;
                }
                if (betterTags.Count > 10)
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                                                  "Please dont exceed 10 tags!"));

                    return;
                }

                string joinedTags = String.Join(";", betterTags);

                var eb = new EmbedBuilder()
                {
                    Color       = Utility.BlueInfoEmbed,
                    Title       = $"{Utility.SuccessLevelEmoji[3]} Are you sure you want Update this? y/n",
                    Description = $"{shareUrl}",
                    Author      = new EmbedAuthorBuilder()
                    {
                        IconUrl = context.User.GetAvatarUrl() ?? Utility.StandardDiscordAvatar,
                        Name    = Utility.GiveUsernameDiscrimComb(context.User)
                    }
                };
                eb.AddField(x =>
                {
                    x.IsInline = false;
                    x.Name     = "Title";
                    x.Value    = title;
                });
                eb.AddField(x =>
                {
                    x.IsInline = true;
                    x.Name     = "Tags";
                    x.Value    = joinedTags.Replace(";", " - ");
                });
                var msg = await context.Channel.SendMessageAsync("", embed : eb);

                var response = await _interactive.NextMessageAsync(context, true, true, TimeSpan.FromSeconds(45));

                await msg.DeleteAsync();

                if (response == null)
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "Didn't answer in time ;_;"));

                    return;
                }

                if (response.Content.Equals("y", StringComparison.OrdinalIgnoreCase) ||
                    response.Content.Equals("yes", StringComparison.OrdinalIgnoreCase))
                {
                    shareResult.Tags  = joinedTags;
                    shareResult.Titel = title;
                    await soraContext.SaveChangesAsync();

                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.GreenSuccessEmbed, Utility.SuccessLevelEmoji[0], $"Successfully updated playlist (ノ◕ヮ◕)ノ*:・゚✧"));
                }
                else
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "Didn't answer with y or yes! Discarded changes"));
                }
            }
        }
Пример #22
0
        public async Task gamble(string amount)
        {
            string path = "C:\\Users\\Aidan Johnsotn\\Desktop\\coins\\";

            if (!File.Exists($"{path}{Context.User.Username}.txt"))
            {
                await ReplyAsync($"Hey, you have not started a coin bank yet.  You can start one with !coinstart");
            }
            else
            {   //Read current user balance
                int balance = int.Parse((await File.ReadAllTextAsync($"{path}{Context.User.Username}.txt")).Trim());

                //Convert user bet amount to int, will fail if string contains anything other than a number
                int  amount_int;
                bool isNumerical = int.TryParse(amount, out amount_int);

                //Check if amount_int is vaild number ( number != 0, number  < 0)
                if (amount_int == 0)
                {
                    await ReplyAsync("You can't bet that many coin dummie");
                }
                if (amount_int > balance)
                {
                    await ReplyAsync("You don't even have that many coins.");
                }
                if (amount_int > 0 && amount_int <= balance)
                {
                    int ran = rand.Next(0, 100);


                    //51% to win
                    if (ran > 45)
                    {
                        //New balance amount after winning the bet picks random number between 100% and 150% of bet amount

                        int amountwon = amount_int / 2 + rand.Next((amount_int / 2) + 1, amount_int + 2);

                        balance = amountwon + balance;

                        //Convert to string
                        string balance_string = balance.ToString();

                        //Input value in text file
                        await File.WriteAllTextAsync($"{path}{Context.User.Username}.txt", balance_string);

                        //Print out info on bet
                        EmbedBuilder builder = new EmbedBuilder();
                        builder.AddField($"Aw shucks, you won {amountwon}", $"New balance is {balance}")
                        .WithColor(Color.Orange);
                        await ReplyAsync("", false, builder.Build());
                    }

                    else
                    {
                        //Amount lost, chose the loss amount to be between 75% of and 100$ of bet
                        int amountlost = 3 * (amount_int / 4) + rand.Next(1, (amount_int / 4) + 1);


                        balance = balance - amountlost;

                        //Bank acount cant go below 0
                        if (balance < 0)
                        {
                            balance = 0;
                        }

                        //Converting balance to string
                        string balance_string = balance.ToString();

                        //Inputing new string in file
                        await File.WriteAllTextAsync($"{path}{Context.User.Username}.txt", balance.ToString());

                        //Printing info
                        EmbedBuilder builder = new EmbedBuilder();
                        builder.AddField($"Heck yeah, you lost {amountlost} coins", $"New balance is {balance}")
                        .WithColor(Color.Orange);
                        await ReplyAsync("", false, builder.Build());
                    }
                }
            }
        }
Пример #23
0
        public async Task SharePlaylist(SocketCommandContext context, string shareUrl, string title, string tags, bool isPrivate)
        {
            using (var soraContext = new SoraContext())
            {
                var userDb = Utility.OnlyGetUser(context.User.Id, soraContext);
                if (userDb == null || ExpService.CalculateLevel(userDb.Exp) < MIN_LEVEL)
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], $"You need to be at least lvl {MIN_LEVEL} to share playlists!"));

                    return;
                }

                if (await CanAddNewPlaylist(context, userDb) == false)
                {
                    return;
                }

                if (!shareUrl.StartsWith("https://hastebin.com/"))
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "The link must be a valid hastebin link!"));

                    return;
                }

                if (!shareUrl.EndsWith(".sora") && !shareUrl.EndsWith(".fredboat"))
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                                                  "Must be an originaly exported sora or fredboat playlist!")
                                                           .WithDescription(
                                                               $"Use `{Utility.GetGuildPrefix(context.Guild, soraContext)}export` when you have a Queue! This is to minimize errors."));

                    return;
                }
                if (shareUrl.EndsWith(".fredboat"))
                {
                    shareUrl = shareUrl.Replace(".fredboat", ".sora");
                }

                if (soraContext.ShareCentrals.Any(x => x.ShareLink == shareUrl))
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "Playlist already exists!"));

                    return;
                }
                string[] seperatedTags;
                if (tags.IndexOf(";", StringComparison.Ordinal) < 1)
                {
                    seperatedTags = new[] { tags };
                }
                else
                {
                    seperatedTags = tags.Split(";");
                }
                List <string> betterTags = new List <string>();
                foreach (var tag in seperatedTags)
                {
                    string finalTag = tag;
                    if (finalTag.Contains(";"))
                    {
                        finalTag = finalTag.Replace(";", "");
                    }
                    if (!string.IsNullOrWhiteSpace(finalTag))
                    {
                        betterTags.Add(finalTag.Trim());
                    }
                }
                if (betterTags.Count < 1)
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                                                  "Add at least one Tag!").WithDescription("Tags must be added like this: `trap;edm;chill music;other`"));

                    return;
                }
                if (betterTags.Count > 10)
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                                                  "Please dont exceed 10 tags!"));

                    return;
                }
                string joinedTags = String.Join(";", betterTags);

                var eb = new EmbedBuilder()
                {
                    Color       = Utility.BlueInfoEmbed,
                    Title       = $"{Utility.SuccessLevelEmoji[3]} Are you sure you want share this? y/n",
                    Description = $"{shareUrl}\n" +
                                  $"You can change the Title and Tags afterwards but never the playlist link!",
                    Author = new EmbedAuthorBuilder()
                    {
                        IconUrl = context.User.GetAvatarUrl() ?? Utility.StandardDiscordAvatar,
                        Name    = Utility.GiveUsernameDiscrimComb(context.User)
                    }
                };
                eb.AddField(x =>
                {
                    x.IsInline = false;
                    x.Name     = "Title";
                    x.Value    = title;
                });
                eb.AddField(x =>
                {
                    x.IsInline = true;
                    x.Name     = "Tags";
                    x.Value    = joinedTags.Replace(";", " - ");
                });
                eb.AddField(x =>
                {
                    x.IsInline = true;
                    x.Name     = "Is Private?";
                    x.Value    = $"{(isPrivate ? "Yes" : "No")}";
                });

                var msg = await context.Channel.SendMessageAsync("", embed : eb);

                var response = await _interactive.NextMessageAsync(context, true, true, TimeSpan.FromSeconds(45));

                await msg.DeleteAsync();

                if (response == null)
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "Didn't answer in time ;_;"));

                    return;
                }

                if (response.Content.Equals("y", StringComparison.OrdinalIgnoreCase) ||
                    response.Content.Equals("yes", StringComparison.OrdinalIgnoreCase))
                {
                    userDb.ShareCentrals.Add(new ShareCentral()
                    {
                        CreatorId = context.User.Id,
                        Downvotes = 0,
                        Upvotes   = 0,
                        ShareLink = shareUrl,
                        Titel     = title,
                        IsPrivate = isPrivate,
                        Tags      = joinedTags
                    });
                    await soraContext.SaveChangesAsync();

                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.GreenSuccessEmbed, Utility.SuccessLevelEmoji[0], $"Successfully {(isPrivate ? "saved" : "shared")} playlist (ノ◕ヮ◕)ノ*:・゚✧"));
                }
                else
                {
                    await context.Channel.SendMessageAsync("", embed :
                                                           Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "Didn't answer with y or yes! Discarded changes"));
                }
            }
        }
Пример #24
0
        public async Task Register([Remainder] string username = null)
        {
            var embed = new EmbedBuilder();

            if (username == null)
            {
                embed.AddField("ERROR", "Please specify a name to be registered with");
                embed.WithColor(Color.Red);
                await ReplyAsync("", false, embed.Build());

                return;
            }

            if (username.Length > 20)
            {
                embed.AddField("ERROR", "Username Must be 20 characters or less");
                embed.WithColor(Color.Red);
                await ReplyAsync("", false, embed.Build());

                return;
            }

            var server = Servers.ServerList.First(x => x.ServerId == Context.Guild.Id);

            if (server.UserList.Count >= 20 && !server.IsPremium)
            {
                embed.AddField("ERROR",
                               "Free User limit has been hit. To upgrade the limit from 20 users to unlimited users, Purchase premium here: https://rocketr.net/buy/0e79a25902f5");
                await ReplyAsync("", false, embed.Build());

                return;
            }

            try
            {
                if (server.UserList.Any(member => member.UserId == Context.User.Id))
                {
                    var userprofile = server.UserList.FirstOrDefault(x => x.UserId == Context.User.Id);

                    if (userprofile == null)
                    {
                        await ReplyAsync("ERROR: User not registered!");

                        return;
                    }

                    if (!((IGuildUser)Context.User).RoleIds.Contains(server.RegisterRole) && server.RegisterRole != 0)
                    {
                        try
                        {
                            var serverrole = Context.Guild.GetRole(server.RegisterRole);
                            try
                            {
                                await((IGuildUser)Context.User).AddRoleAsync(serverrole);
                            }
                            catch
                            {
                                embed.AddField("ERROR", "User Role Unable to be modified");
                            }
                        }
                        catch
                        {
                            embed.AddField("ERROR", "Register Role is Unavailable");
                        }
                    }

                    try
                    {
                        await UserRename(server.UsernameSelection, Context.User, username, userprofile.Points);


                        userprofile.Username = username;
                    }
                    catch
                    {
                        embed.AddField("ERROR", "Username Unable to be modified (Permissions are above the bot)");
                    }


                    embed.AddField("ERROR", "User is already registered, role and name have been updated accordingly");

                    embed.WithColor(Color.Red);

                    await ReplyAsync("", false, embed.Build());

                    return;
                }
            }
            catch
            {
                //
            }


            var user = new Servers.Server.User
            {
                UserId   = Context.User.Id,
                Username = username,
                Points   = 0
            };

            server.UserList.Add(user);
            embed.AddField($"{Context.User.Username} registered as {username}", $"{server.Registermessage}");
            embed.WithColor(Color.Blue);
            try
            {
                await UserRename(server.UsernameSelection, Context.User, user.Username, 0);
            }
            catch
            {
                embed.AddField("ERROR", "Username Unable to be modified (Permissions are above the bot)");
            }
            if (server.RegisterRole != 0)
            {
                try
                {
                    var serverrole = Context.Guild.GetRole(server.RegisterRole);
                    try
                    {
                        await((IGuildUser)Context.User).AddRoleAsync(serverrole);
                    }
                    catch
                    {
                        embed.AddField("ERROR", "User Role Unable to be modified");
                    }
                }
                catch
                {
                    embed.AddField("ERROR", "Register Role is Unavailable");
                }
            }
            await ReplyAsync("", false, embed.Build());
        }
Пример #25
0
        public async Task fmfullhelpAsync()
        {
            string prefix = ConfigData.Data.CommandPrefix;

            ISelfUser SelfUser = Context.Client.CurrentUser;

            string description = null;
            int    length      = 0;

            EmbedBuilder builder = new EmbedBuilder();

            foreach (ModuleInfo module in _service.Modules.OrderByDescending(o => o.Commands.Count()).Where(w => !w.Name.Contains("SecretCommands") && !w.Name.Contains("OwnerCommands") && !w.Name.Contains("AdminCommands") && !w.Name.Contains("GuildCommands")))
            {
                foreach (CommandInfo cmd in module.Commands)
                {
                    PreconditionResult result = await cmd.CheckPreconditionsAsync(Context);

                    if (result.IsSuccess)
                    {
                        if (!string.IsNullOrWhiteSpace(cmd.Summary))
                        {
                            description += $"{prefix}{cmd.Aliases.First()} - {cmd.Summary}\n";
                        }
                        else
                        {
                            description += $"{prefix}{cmd.Aliases.First()}\n";
                        }
                    }
                }


                if (description.Length < 1024)
                {
                    builder.AddField
                        (module.Name + (module.Summary != null ? " - " + module.Summary : ""),
                        description != null ? description : "");
                }


                length     += description.Length;
                description = null;

                if (length < 1990)
                {
                    await Context.User.SendMessageAsync("", false, builder.Build()).ConfigureAwait(false);

                    builder = new EmbedBuilder();
                    length  = 0;
                }
            }


            builder = new EmbedBuilder
            {
                Title = "Additional information",
            };

            builder.AddField("Quick tips",
                             "- Be sure to use 'help' after a command name to see the parameters. \n" +
                             "- Chart sizes range from 3x3 to 10x10 \n" +
                             "- Most commands have no required parameters");


            builder.AddField("Setting your username",
                             "Use `" + prefix + "fmset 'username' 'embedfull/embedmini/textfull/textmini'` to set your global LastFM username. " +
                             "The last parameter means the mode that your embed will be");


            builder.AddField("Making album charts",
                             "`" + prefix + "fmchart '3x3-10x10' 'weekly/monthly/yearly/overall' 'notitles/titles' 'user'`");


            builder.AddField("Making artist charts",
                             "`" + prefix + "fmartistchart '3x3-10x10' 'weekly/monthly/yearly/overall' 'notitles/titles' 'user'`");


            builder.AddField("Setting the default server settings",
                             "Please note that server defaults are a planned feature. \n" +
                             "Only users with the 'Ban Members' permission or admins can use this command. \n" +
                             "`" + prefix + "fmserverset 'embedfull/embedmini/textfull/textmini' 'Weekly/Monthly/Yearly/AllTime'`");

            builder.WithFooter("Still need help? Join the FMBot Discord Server: https://discord.gg/srmpCaa");

            await Context.User.SendMessageAsync("", false, builder.Build()).ConfigureAwait(false);

            if (!guildService.CheckIfDM(Context))
            {
                await Context.Channel.SendMessageAsync("Check your DMs!").ConfigureAwait(false);
            }
        }
Пример #26
0
        internal static Embed SignupDetails(string profileName, string id, string profileLink, string status, string platformLinks, ulong requestor)
        {
            EmbedBuilder builder = new EmbedBuilder()
            {
                Color = Constants.SuccessColor,
            };

            switch (status)
            {
            case "Notify of Approval":
                status = "Awaiting Acceptance";
                break;

            case "Pending":
                status = "Awaiting Calculation";
                break;

            case "Requirements not reached":
                status = "Denied";
                break;

            case "Notify of Denied Signup":
                status = "Awaiting Denial";
                break;

            case "Approved and Notified":
                status = "Accepted";
                break;

            case "Investigate App":
            case "Issue":
            case "Missing Data":
                status = "Missing Data/Information/Signup Incomplete";
                break;

            case "Left Discord before Denial":
            case "Active Player left the IEL discord":
                status = "Player Left Discord";
                break;

            default:
                status = "Pending Review";
                break;
            }


            builder.AddField(new EmbedFieldBuilder()
            {
                Name = "Profile Name", Value = profileName
            });
            builder.AddField(new EmbedFieldBuilder()
            {
                Name = "Discord Id", Value = id
            });
            builder.AddField(new EmbedFieldBuilder()
            {
                Name = "Profile Link", Value = profileLink
            });
            builder.AddField(new EmbedFieldBuilder()
            {
                Name = "Application Status", Value = status
            });
            builder.AddField(new EmbedFieldBuilder()
            {
                Name = "Accounts Linked", Value = platformLinks
            });

            builder.Description = "Here are the details of your application. If you have any questions please ask a member of the Support or Applications teams.";
            if (status == "Missing Data/Information/Signup Incomplete" && id == requestor.ToString())
            {
                builder.Description += "\r\nIf you were denied due to your games played, please type !rechecksignup to have your games recounted.";
            }

            return(builder.Build());
        }
Пример #27
0
        public async Task statusAsync()
        {
            ISelfUser SelfUser = Context.Client.CurrentUser;

            EmbedAuthorBuilder eab = new EmbedAuthorBuilder
            {
                IconUrl = SelfUser.GetAvatarUrl(),
                Name    = SelfUser.Username
            };

            EmbedBuilder builder = new EmbedBuilder();

            builder.WithAuthor(eab);
            builder.WithDescription(SelfUser.Username + " Statistics");

            TimeSpan startTime = (DateTime.Now - Process.GetCurrentProcess().StartTime);

            DiscordShardedClient client = Context.Client as DiscordShardedClient;

            SocketSelfUser SocketSelf = Context.Client.CurrentUser as SocketSelfUser;

            string status = "Online";

            switch (SocketSelf.Status)
            {
            case UserStatus.Offline: status = "Offline"; break;

            case UserStatus.Online: status = "Online"; break;

            case UserStatus.Idle: status = "Idle"; break;

            case UserStatus.AFK: status = "AFK"; break;

            case UserStatus.DoNotDisturb: status = "Do Not Disturb"; break;

            case UserStatus.Invisible: status = "Invisible/Offline"; break;
            }

            string assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            int fixedCmdGlobalCount         = GlobalVars.CommandExecutions + 1;
            int fixedCmdGlobalCount_Servers = GlobalVars.CommandExecutions_Servers + 1;
            int fixedCmdGlobalCount_DMs     = GlobalVars.CommandExecutions_DMs + 1;

            builder.AddField("Bot Uptime: ", startTime.ToReadableString(), true);
            builder.AddField("Server Uptime: ", GlobalVars.SystemUpTime().ToReadableString(), true);
            builder.AddField("Usercount: ", (await userService.GetUserCountAsync()).ToString(), true);
            builder.AddField("Servercount: ", client.Guilds.Count, true);
            builder.AddField("Commands used since bot start: ", fixedCmdGlobalCount);
            builder.AddField("Commands in servers: ", fixedCmdGlobalCount_Servers);
            builder.AddField("Commands in DMs ", fixedCmdGlobalCount_DMs);
            builder.AddField("Bot status: ", status, true);
            builder.AddField("Latency: ", client.Latency + "ms", true);
            builder.AddField("Shards: ", client.Shards.Count, true);
            builder.AddField("Bot version: ", assemblyVersion, true);

            await Context.Channel.SendMessageAsync("", false, builder.Build()).ConfigureAwait(false);
        }
Пример #28
0
        public List <Command> Load()
        {
            List <Command> commands = new List <Command>();

            Command addwarning = new Command("addwarning");

            addwarning.Description       += "Add a warning to the database";
            addwarning.Usage              = "addwarning <user> <warning>";
            addwarning.RequiredPermission = Command.PermissionLevels.Moderator;
            addwarning.ToExecute         += async(context) =>
            {
                if (context.Parameters.IsEmpty())
                {
                    await context.Message.ReplyAsync("You must specify a user");

                    return;
                }
                ulong uid;
                if (ulong.TryParse(context.Parameters[0].TrimStart('<', '@', '!').TrimEnd('>'), out uid))
                {
                    context.Parameters.RemoveAt(0);
                    string warning = context.Parameters.Rejoin();
                    warning += $" (Added By `{context.Author}` At `{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT`)";
                    var finalUser = Core.GetUserFromGuild(uid, context.Guild.Id).AddWarning(warning);
                    Core.SaveUserToGuild(finalUser, context.Guild.Id);
                    var builder = new EmbedBuilder()
                                  .WithTitle("Warning Added")
                                  .WithDescription(warning)
                                  .WithColor(new Color(0xFFFF00))
                                  .WithFooter(footer =>
                    {
                        footer
                        .WithText($"By {context.Author} at {DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT");
                    });


                    EmbedFieldBuilder warningCountField = new EmbedFieldBuilder().WithName("Warning Count").WithValue(finalUser.Warnings.Count).WithIsInline(true);
                    builder.AddField(warningCountField);

                    try
                    {
                        var user = Core.DiscordClient.GetUser(uid);
                        builder.Author = new EmbedAuthorBuilder().WithName(user.ToString()).WithIconUrl(user.GetAvatarUrl());
                    }
                    catch (Exception ex)
                    {
                        await Core.Logger.LogErrorMessage(ex, context);

                        builder.Author = new EmbedAuthorBuilder().WithName(uid.ToString());
                    }


                    await context.Message.Channel.SendMessageAsync("", embed : builder.Build());

                    if (Core.GetGuildConfig(context.Guild.Id).LoggingChannelId != 0)
                    {
                        await((SocketTextChannel)Core.DiscordClient.GetChannel(Core.GetGuildConfig(context.Guild.Id).LoggingChannelId))
                        .SendMessageAsync("", embed: builder.Build());
                    }
                }
                else
                {
                    await context.Message.ReplyAsync("Could not find that user");
                }
            };
            commands.Add(addwarning);

            Command issuewarning = new Command("issuewarning");

            issuewarning.Description       += "Add a warning to the database and send it to the user";
            issuewarning.Usage              = "issuewarning <user> <warning>";
            issuewarning.RequiredPermission = Command.PermissionLevels.Moderator;
            issuewarning.ToExecute         += async(context) =>
            {
                if (context.Parameters.IsEmpty())
                {
                    await context.Message.ReplyAsync("You must specify a user");

                    return;
                }
                if (context.Message.GetMentionedUsers().Any())
                {
                    var user = context.Message.GetMentionedUsers().First();
                    if (!context.Guild.Users.Any(u => u.Id.Equals(user.Id)))
                    {
                        await context.Message.ReplyAsync("Could not find that user");

                        return;
                    }
                    context.Parameters.RemoveAt(0);
                    string warning = context.Parameters.Rejoin();
                    warning += $" (Issued By `{context.Author}` At `{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT`)";

                    var finalUser = Core.GetUserFromGuild(user.Id, context.Guild.Id).AddWarning(warning);
                    Core.SaveUserToGuild(finalUser, context.Guild.Id);

                    try
                    {
                        await user.GetOrCreateDMChannelAsync().Result.SendMessageAsync(
                            $"The Moderator team of **{context.Guild.Name}** has issued you the following warning:\n{context.Parameters.Rejoin()}");
                    }
                    catch (Exception ex)
                    {
                        await Core.Logger.LogErrorMessage(ex, context);

                        warning += $"\nCould not message {user}";
                    }

                    var builder = new EmbedBuilder()
                                  .WithTitle("Warning Issued")
                                  .WithDescription(warning)
                                  .WithColor(new Color(0xFFFF00))
                                  .WithFooter(footer =>
                    {
                        footer
                        .WithText($"By {context.Author} at {DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT");
                    });

                    EmbedFieldBuilder warningCountField = new EmbedFieldBuilder().WithName("Warning Count").WithValue(finalUser.Warnings.Count).WithIsInline(true);
                    builder.AddField(warningCountField);

                    builder.Author = new EmbedAuthorBuilder().WithName(user.ToString()).WithIconUrl(user.GetAvatarUrl());

                    await context.Message.Channel.SendMessageAsync("", embed : builder.Build());

                    if (Core.GetGuildConfig(context.Guild.Id).LoggingChannelId != 0)
                    {
                        await((SocketTextChannel)Core.DiscordClient.GetChannel(Core.GetGuildConfig(context.Guild.Id).LoggingChannelId))
                        .SendMessageAsync("", embed: builder.Build());
                    }
                }
                else
                {
                    await context.Message.ReplyAsync("Could not find that user");
                }
            };
            commands.Add(issuewarning);

            Command removeWarning = new Command("removeWarning");

            removeWarning.RequiredPermission = Command.PermissionLevels.Moderator;
            removeWarning.Usage       = "removewarning <user>";
            removeWarning.Description = "Remove the last warning from a user";
            removeWarning.ToExecute  += async(context) =>
            {
                if (context.Parameters.IsEmpty())
                {
                    await context.Message.ReplyAsync($"You need to add some arguments. A user, perhaps?");

                    return;
                }

                ulong uid;
                if (ulong.TryParse(context.Parameters[0].TrimStart('<', '@', '!').TrimEnd('>'), out uid))
                {
                    var user = Core.GetUserFromGuild(uid, context.Guild.Id);
                    try
                    {
                        Core.SaveUserToGuild(user.RemoveWarning(), context.Guild.Id);
                        await context.Message.ReplyAsync($"Done!");
                    }
                    catch (DivideByZeroException ex)
                    {
                        await Core.Logger.LogErrorMessage(ex, context);

                        await context.Message.ReplyAsync("User had no warnings");
                    }
                }
                else
                {
                    await context.Message.ReplyAsync($"No user found");
                }
            };
            commands.Add(removeWarning);

            return(commands);
        }
Пример #29
0
        public static async Task InspectCharacter(string _characterName, string _realmName, ICommandContext _context)
        {
            var requestResultCharacter = await warcraftClient.GetCharacterAsync(_realmName, _characterName, CharacterFields.All);

            if (requestResultCharacter.Value == null)
            {
                await _context.Channel.SendMessageAsync("Character not found."); return;
            }
            Character character = requestResultCharacter.Value;

            EmbedBuilder embed = new EmbedBuilder()
            {
                Title        = character.Name + "-" + character.Realm,
                Description  = "Level " + character.Level + " " + character.Race + " " + character.Class,
                ThumbnailUrl = "https://render-eu.worldofwarcraft.com/character/" + character.Thumbnail,
                Color        = character.Faction == Faction.Alliance ? Color.Blue : Color.Red,
                Footer       = new EmbedFooterBuilder()
                {
                    Text = "Last updated on: " + character.LastModified
                }
            };

            if (character.Guild != null)
            {
                embed.AddField(new EmbedFieldBuilder()
                {
                    Name = "<" + character.Guild.Name + ">", Value = "\u200B"
                });
            }
            embed.AddField(new EmbedFieldBuilder()
            {
                Name = "__**Achievement Points:**__ " + character.AchievementPoints.ToString() + "    " + "__**Honorable Kills:**__ " + character.TotalHonorableKills.ToString(), Value = "\u200B"
            });

            List <Proffessions> bfaProffessionIds = new List <Proffessions> {
                Proffessions.Alchemy, Proffessions.Blacksmithing, Proffessions.Enchanting, Proffessions.Engineering, Proffessions.Herbalism, Proffessions.Inscription, Proffessions.Jewelcrafting, Proffessions.Leatherworking, Proffessions.Mining, Proffessions.Skinning, Proffessions.Tailoring
            };
            Profession firstPrimaryProf = (character.Professions.Primary as List <Profession>).Find(x => bfaProffessionIds.Contains((Proffessions)x.Id));

            if (firstPrimaryProf != null)
            {
                bfaProffessionIds.Remove((Proffessions)firstPrimaryProf.Id);
            }
            Profession SecondPrimaryProf = (character.Professions.Primary as List <Profession>).Find(x => bfaProffessionIds.Contains((Proffessions)x.Id));

            if (SecondPrimaryProf != null)
            {
                bfaProffessionIds.Remove((Proffessions)SecondPrimaryProf.Id);
            }
            string firstPrimaryProfString  = firstPrimaryProf == null ? "N/A" : firstPrimaryProf.Name + "[" + firstPrimaryProf.Rank + "/" + firstPrimaryProf.Max + "]";
            string secondPrimaryProfString = SecondPrimaryProf == null ? "N/A" : SecondPrimaryProf.Name + "[" + SecondPrimaryProf.Rank + "/" + SecondPrimaryProf.Max + "]";

            embed.AddField(new EmbedFieldBuilder()
            {
                Name = "__**Proffesions:**__\n" + "- " + firstPrimaryProfString + "\n" + "- " + secondPrimaryProfString, Value = "\u200B"
            });

            string offhandString = character.Items.OffHand != null ? "__Offhand:__ " + character.Items.OffHand.Name + " [Ilvl: " + character.Items.OffHand.ItemLevel + " " + GetItemQualityString(character.Items.OffHand) + "]\n" : "__Offhand:__ N/A";

            embed.AddField(new EmbedFieldBuilder()
            {
                Name  = "__**AvgIlvl:**__ " + character.Items.AverageItemLevelEquipped + "\n__**Gear:**__",
                Value = "__Head:__ " + character.Items.Head.Name + " [Ilvl " + character.Items.Head.ItemLevel + " " + GetItemQualityString(character.Items.Head) + "]\n" +
                        "__Neck:__ " + character.Items.Neck.Name + " [Ilvl " + character.Items.Neck.ItemLevel + " " + GetItemQualityString(character.Items.Neck) + "]\n" +
                        "__Shoulders:__ " + character.Items.Shoulder.Name + " [Ilvl " + character.Items.Shoulder.ItemLevel + " " + GetItemQualityString(character.Items.Shoulder) + "]\n" +
                        "__Back:__ " + character.Items.Back.Name + " [Ilvl " + character.Items.Back.ItemLevel + " " + GetItemQualityString(character.Items.Back) + "]\n" +
                        "__Chest:__ " + character.Items.Chest.Name + " [Ilvl " + character.Items.Chest.ItemLevel + " " + GetItemQualityString(character.Items.Chest) + "]\n" +
                        "__Wrists:__ " + character.Items.Wrist.Name + " [Ilvl " + character.Items.Wrist.ItemLevel + " " + GetItemQualityString(character.Items.Wrist) + "]\n" +
                        "__Hands:__ " + character.Items.Hands.Name + " [Ilvl " + character.Items.Hands.ItemLevel + " " + GetItemQualityString(character.Items.Hands) + "]\n" +
                        "__Waist:__ " + character.Items.Waist.Name + " [Ilvl " + character.Items.Waist.ItemLevel + " " + GetItemQualityString(character.Items.Waist) + "]\n" +
                        "__Leggs:__ " + character.Items.Legs.Name + " [Ilvl " + character.Items.Legs.ItemLevel + " " + GetItemQualityString(character.Items.Legs) + "]\n" +
                        "__Feet:__ " + character.Items.Feet.Name + " [Ilvl " + character.Items.Feet.ItemLevel + " " + GetItemQualityString(character.Items.Feet) + "]\n" +
                        "__Ring 1:__ " + character.Items.Finger1.Name + " [Ilvl " + character.Items.Finger1.ItemLevel + " " + GetItemQualityString(character.Items.Finger1) + "]\n" +
                        "__Ring 2:__ " + character.Items.Finger2.Name + " [Ilvl " + character.Items.Finger2.ItemLevel + " " + GetItemQualityString(character.Items.Finger2) + "]\n" +
                        "__Trinket 1:__ " + character.Items.Trinket1.Name + " [Ilvl " + character.Items.Trinket1.ItemLevel + " " + GetItemQualityString(character.Items.Trinket1) + "]\n" +
                        "__Trinket 2:__ " + character.Items.Trinket2.Name + " [Ilvl " + character.Items.Trinket2.ItemLevel + " " + GetItemQualityString(character.Items.Trinket2) + "]\n" +
                        "__Mainhand:__ " + character.Items.MainHand.Name + " [Ilvl " + character.Items.MainHand.ItemLevel + " " + GetItemQualityString(character.Items.MainHand) + "]\n" +
                        offhandString
            });

            embed.AddField(new EmbedFieldBuilder()
            {
                Name  = "__**Talents:**__",
                Value = ListTalents(character)
            });

            await _context.Channel.SendMessageAsync("", false, embed.Build());
        }
Пример #30
0
        public async Task Rps(RpsPick pick, ShmartNumber amount = default)
        {
            long oldAmount = amount;

            if (!await CheckBetOptional(amount).ConfigureAwait(false) || (amount == 1))
            {
                return;
            }

            string getRpsPick(RpsPick p)
            {
                switch (p)
                {
                case RpsPick.R:
                    return("🚀");

                case RpsPick.P:
                    return("📎");

                default:
                    return("✂️");
                }
            }

            var embed = new EmbedBuilder();

            var nadekoPick = (RpsPick) new NadekoRandom().Next(0, 3);

            if (amount > 0)
            {
                if (!await _cs.RemoveAsync(Context.User.Id,
                                           "Rps-bet", amount, gamble: true).ConfigureAwait(false))
                {
                    await ReplyErrorLocalized("not_enough", Bc.BotConfig.CurrencySign).ConfigureAwait(false);

                    return;
                }
            }

            string msg;

            if (pick == nadekoPick)
            {
                await _cs.AddAsync(Context.User.Id,
                                   "Rps-draw", amount, gamble : true).ConfigureAwait(false);

                embed.WithOkColor();
                msg = GetText("rps_draw", getRpsPick(pick));
            }
            else if ((pick == RpsPick.Paper && nadekoPick == RpsPick.Rock) ||
                     (pick == RpsPick.Rock && nadekoPick == RpsPick.Scissors) ||
                     (pick == RpsPick.Scissors && nadekoPick == RpsPick.Paper))
            {
                amount = (long)(amount * Bc.BotConfig.BetflipMultiplier);
                await _cs.AddAsync(Context.User.Id,
                                   "Rps-win", amount, gamble : true).ConfigureAwait(false);

                embed.WithOkColor();
                embed.AddField(GetText("won"), amount);
                msg = GetText("rps_win", Context.User.Mention,
                              getRpsPick(pick), getRpsPick(nadekoPick));
            }
            else
            {
                embed.WithErrorColor();
                amount = 0;
                msg    = GetText("rps_win", Context.Client.CurrentUser.Mention, getRpsPick(nadekoPick),
                                 getRpsPick(pick));
            }

            embed
            .WithDescription(msg);

            await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
        }
Пример #31
0
        public static async Task MakeAnimeObjectAsync(IMessage message, IGuildUser author, object obj)
        {
            var anime = obj as Models.AnimeModel;
            if(anime == null)
            {
                await message.Channel.SendMessageAsync($"{author.Mention}: Something went wrong! I'm so sorry :(");
                return;
            }

            EmbedBuilder eb = new EmbedBuilder();
            eb.WithColor(new Color(0, 255, 0))
            .WithTitle(anime.Title)
            .WithDescription(anime.Genre)
            .WithUrl(anime.Url)
            .WithThumbnailUrl(anime.ImageUrl)
            .WithAuthor(x=>
            {
                x.Name = author.Nickname == null ? author.Username : author.Nickname;
                x.IconUrl = author.AvatarUrl;
            });

            //Add Episodes field
            eb.AddField(x =>
            {
                x.IsInline = true;
                x.Name = "Episodes";
                x.Value = anime.Episodes;
            });

            if (!String.IsNullOrEmpty(anime.Duration))
            {
                eb.AddField(x =>
                {
                    x.IsInline = true;
                    x.Name = "Duration";
                    x.Value = anime.Duration;
                });
            }

            eb.AddField(x =>
            {
                x.IsInline = true;
                x.Name = "Score";
                x.Value = anime.Score;
            });

            eb.AddField(x =>
            {
                x.IsInline = true;
                x.Name = "Type";
                x.Value = anime.Type;
            });

            eb.AddField(x =>
            {
                x.IsInline = false;
                x.Name = "Description";
                x.Value = anime.Description;
            });

            await message.Channel.SendMessageAsync("", embed: eb);
        }