Exemple #1
0
        public async Task TrainAttributes(CommandContext c)
        {
            using (var session = Db.DocStore.OpenAsyncSession())
            {
                var player = await session.LoadAsync <Player>(c.User.Id.ToString());

                if (player == null)
                {
                    await c.RespondAsync(Realm.GetMessage("not_registered"));

                    await c.RejectMessage();

                    return;
                }

                if (player.AttributePoints < 1)
                {
                    await c.RespondAsync(Realm.GetMessage("not_enough_attrib_pts"));

                    await c.RejectMessage();

                    return;
                }

                var interact = c.Client.GetInteractivity();

                var desc = new System.Text.StringBuilder();

                desc.AppendLine($"{c.User.Mention}, what attribute do you want to train. Current level in parentheses");
                desc.AppendLine($"STR: :muscle: ({player.Attributes.Strength})");
                desc.AppendLine($"AGI: :hand_splayed: ({player.Attributes.Agility})");
                desc.AppendLine($"STA: :heart: ({player.Attributes.Stamina})");
                desc.AppendLine($"INT: :eye_in_speech_bubble: ({player.Attributes.Intelligence})");
                desc.AppendLine($"WIS: :six_pointed_star: ({player.Attributes.Wisdom})");

                var embed = new DiscordEmbedBuilder().WithDescription(desc.ToString());

                var msg = await c.RespondAsync(embed : embed);

                await msg.CreateReactionAsync(DiscordEmoji.FromName(c.Client, Constants.ATTRIB_STR));                 // Strength

                await msg.CreateReactionAsync(DiscordEmoji.FromName(c.Client, Constants.ATTRIB_AGI));                 // Agility

                await msg.CreateReactionAsync(DiscordEmoji.FromName(c.Client, Constants.ATTRIB_STA));                 // Stamina

                await msg.CreateReactionAsync(DiscordEmoji.FromName(c.Client, Constants.ATTRIB_INT));                 // Intelligence

                await msg.CreateReactionAsync(DiscordEmoji.FromName(c.Client, Constants.ATTRIB_WIS));                 // Wisdom

                var response = await interact.WaitForMessageReactionAsync(msg, c.User, System.TimeSpan.FromSeconds(10));

                if (response == null)
                {
                    await c.RejectMessage();

                    await msg.DeleteAsync();

                    return;
                }

                await msg.DeleteAllReactionsAsync();

                var responsename = response.Emoji.GetDiscordName().ToLower();

                switch (responsename)
                {
                case Constants.ATTRIB_STR:
                    player.Attributes.Strength++;
                    player.AttributePoints--;
                    await c.RespondAsync(string.Format(Realm.GetMessage("train_str"), c.User.Mention));

                    break;

                case Constants.ATTRIB_AGI:
                    player.Attributes.Agility++;
                    player.AttributePoints--;
                    await c.RespondAsync(string.Format(Realm.GetMessage("train_agi"), c.User.Mention));

                    break;

                case Constants.ATTRIB_STA:
                    player.Attributes.Stamina++;
                    player.AttributePoints--;
                    await c.RespondAsync(string.Format(Realm.GetMessage("train_sta"), c.User.Mention));

                    break;

                case Constants.ATTRIB_INT:
                    player.Attributes.Intelligence++;
                    player.AttributePoints--;
                    await c.RespondAsync(string.Format(Realm.GetMessage("train_int"), c.User.Mention));

                    break;

                case Constants.ATTRIB_WIS:
                    player.Attributes.Wisdom++;
                    player.AttributePoints--;
                    await c.RespondAsync(string.Format(Realm.GetMessage("train_wis"), c.User.Mention));

                    break;
                }

                await msg.DeleteAsync();

                if (session.Advanced.HasChanged(player))
                {
                    await session.SaveChangesAsync();
                }
            }

            await c.ConfirmMessage();
        }
Exemple #2
0
        public async Task Reversi(CommandContext ctx, [Description("Person to play with")] DiscordMember player2,
                                  [Description("Amount of coinst to bet")]
                                  decimal bet,
                                  [Description("Doesn't delete messages. Speeds up game greatly but increases spam")]
                                  bool keepMsgs = false)
        {
            if (ctx.Channel.Get(ConfigManager.Enabled)
                .And(ctx.Channel.GetMethodEnabled()))
            {
                await ctx.TriggerTypingAsync();

                if (bet > ctx.Guild.GetMoney(ctx.Member) || bet < 0)
                {
                    await ctx.RespondAsync("You don't have that much");

                    return;
                }
                if (bet > ctx.Guild.GetMoney(player2) || bet < 0)
                {
                    await ctx.RespondAsync($"{player2.DisplayName} doesn't have that much");

                    return;
                }
                DiscordMessage invite = await ctx.RespondAsync("Waiting 1 minute for Player 2 to react with :ok:...");

                await invite.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":ok:"));

                InteractivityResult <MessageReactionAddEventArgs> res =
                    await invite.WaitForReactionAsync(player2, new TimeSpan(0, 1, 0));

                if (res.TimedOut)
                {
                    await invite.ModifyAsync("Timed out.");
                }
                else
                {
                    if (!keepMsgs)
                    {
                        await invite.DeleteAsync();
                    }
                    await ctx.TriggerTypingAsync();

                    DiscordMember player1 = await ctx.Guild.GetMemberAsync(ctx.Message.Author.Id);

                    (DiscordMember? winner, string renderedBoard) =
                        await PlayReversiRound(ctx, player1, player2, keepMsgs);

                    if (winner is null)
                    {
                        ctx.Guild.IncrementMoney(player1, -bet);
                        ctx.Guild.IncrementMoney(player2, -bet);
                    }
                    else
                    {
                        DiscordMember nonWinner = winner == player1 ? player2 : player1;
                        ctx.Guild.IncrementMoney(winner, bet);
                        ctx.Guild.IncrementMoney(nonWinner, -bet);
                    }
                    await ctx.RespondAsync(embed: new DiscordEmbedBuilder
                    {
                        Title       = "Reversi",
                        Description = winner == null
                            ? "The bank won"
                            : $"{(winner == player1 ? player1.DisplayName : player2.DisplayName)} won {bet}"
                    }.AddField("Board", renderedBoard).Build());
                }
            }
        }
 public static async Task Unreact(this MessageCreateEventArgs e, DiscordClient client, string name)
 {
     e.Message.DeleteReactionAsync(DiscordEmoji.FromName(client, name), client.CurrentUser);
 }
Exemple #4
0
 public async Task Roulette(CommandContext ctx, int size)
 {
     if (!(size == 4 || size == 8 || size == 24))
     {
         var emoji = DiscordEmoji.FromName(ctx.Client, ":warning:");
         var embed = new DiscordEmbedBuilder
         {
             Title       = "Providence Roulette",
             Description = $"{emoji} **Roulette Generation Failed**\n\t\t*Invalid Group Size*\n\t\t*Please specify a group size of 4, 8 or 24*",
             Color       = new DiscordColor(0xFF0000)
         };
         await ctx.RespondAsync("", embed : embed);
     }
     else if (size == 4)
     {
         int    randomIndex   = rng.Next(Dlist4.GetLength(0));
         int    randomIndexSR = rng.Next(SpecialRules.Length);
         string text          = Dlist4[randomIndex, 0];
         string text2         = Dlist4[randomIndex, 1];
         string text3         = SpecialRules[randomIndexSR];
         var    embed         = new DiscordEmbedBuilder();
         embed.WithTitle("Providence Roulette").WithDescription("*I have prepared your challenge.*").WithImageUrl(text2).WithColor(new DiscordColor(0, 216, 255));
         embed.AddField("**Duty**", "*" + text + "*", true);
         embed.AddField("**Type**", "*4-man Dungeon*", true);
         embed.AddField("**Special Rules**", "*" + text3 + "*", false);
         await ctx.RespondAsync("", embed : embed);
     }
     else if (size == 24)
     {
         int    randomIndex = rng.Next(Dlist24.Length);
         string text        = Dlist24[randomIndex];
         await ctx.RespondAsync($"🎲 [RouletteDutyOutput]: {text}");
     }
     else if (size == 8)
     {
         int    randomIndex   = rng.Next(Dlist8.GetLength(0));
         int    randomIndexSR = rng.Next(SpecialRules.Length - 1);
         int    bonusSRcheck  = rng.Next(1, 100);
         string text          = Dlist8[randomIndex, 0];
         string text2         = Dlist8[randomIndex, 1];
         string text3         = SpecialRules[randomIndexSR];
         string text4         = "*Watch your step, adventurers.*";
         string text5         = "";
         if (text != "StoryRaid" && text != "EX" && text != "Savage")
         {
             if (bonusSRcheck < 51)
             {
                 text4 = "*Let's keep this interesting, shall we?*";
                 text3 = "Minimum Item Level";
                 if (bonusSRcheck < 21)
                 {
                     text4 = "*Amuse me.*";
                     text5 = SpecialRules[rng.Next(2, 5)];
                     if (bonusSRcheck < 11)
                     {
                         text4 = "*Feed me.*";
                         text5 = SpecialRules[rng.Next(2, SpecialRules.Length - 1)];
                     }
                 }
             }
             var embed = new DiscordEmbedBuilder();
             embed.WithTitle("Providence Roulette").WithDescription(text4).WithImageUrl(text2).WithColor(new DiscordColor(255, 239, 0));
             embed.AddField("**Duty**", "*" + text + "*", true);
             embed.AddField("**Type**", "*8-Man Content*", true);
             if (bonusSRcheck > 20)
             {
                 embed.AddField("**Special Rules**", "*" + text3 + "*", false);
             }
             else
             {
                 embed.AddField("**Special Rules**", "*" + text3 + " and " + text5 + "*", false);
             }
             await ctx.RespondAsync("", embed : embed);
         }
         else if (text == "Savage")
         {
             randomIndex = rng.Next(DlistSavage.GetLength(0));
             text        = DlistSavage[randomIndex, 0];
             text2       = DlistSavage[randomIndex, 1];
             if (text != "The Second Binding Coil of Bahamut (Savage)")
             {
                 text4 = "*Suffer.*";
                 if (bonusSRcheck < 11)
                 {
                     text4 = "*Despair.*";
                     text3 = "Minimum Item Level";
                 }
                 var embed = new DiscordEmbedBuilder();
                 embed.WithTitle("Providence Roulette").WithDescription(text4).WithImageUrl(text2).WithColor(new DiscordColor(240, 84, 74));
                 embed.AddField("**Duty**", "*" + text + "*", true);
                 embed.AddField("**Type**", "*8-Man Savage*", true);
                 if (bonusSRcheck < 11)
                 {
                     embed.AddField("**Special Rules**", "*" + text3 + "*", false);
                 }
                 await ctx.RespondAsync("", embed : embed);
             }
             else
             {
                 if (bonusSRcheck > 2)
                 {
                     var embed = new DiscordEmbedBuilder();
                     embed.WithTitle("Providence Roulette").WithDescription("*Die.*").WithImageUrl(text2).WithColor(new DiscordColor(255, 0, 0));
                     embed.AddField("**Duty**", "*" + text + "*", true);
                     embed.AddField("**Type**", "*8-Man Graveyard*", true);
                     await ctx.RespondAsync("", embed : embed);
                 }
                 else
                 {
                     var embed = new DiscordEmbedBuilder();
                     embed.WithTitle("Providence Roulette").WithDescription("*AHAHAHAHAHA.*").WithImageUrl(text2).WithColor(new DiscordColor(255, 0, 0));
                     embed.AddField("**AHAHAHAHAHA**", "*" + text + "*", true);
                     embed.AddField("**AHAHAHAHAHA**", "*AHAHAHAHAHA*", true);
                     embed.AddField("**AHAHAHAHAHA**", "*" + "Minimum Item Level" + "*", false);
                     await ctx.RespondAsync("", embed : embed);
                 }
             }
         }
         else if (text == "StoryRaid")
         {
             randomIndex = rng.Next(DlistStoryRaid.GetLength(0));
             text        = DlistStoryRaid[randomIndex, 0];
             text2       = DlistStoryRaid[randomIndex, 1];
             if (bonusSRcheck < 76)
             {
                 text4 = "*Let's keep this interesting, shall we?*";
                 text3 = "Minimum Item Level";
                 if (bonusSRcheck < 25)
                 {
                     text4 = "*Amuse me.*";
                     text5 = SpecialRules[rng.Next(2, 5)];
                 }
             }
             var embed = new DiscordEmbedBuilder();
             embed.WithTitle("Providence Roulette").WithDescription(text4).WithImageUrl(text2).WithColor(new DiscordColor(254, 223, 0));
             embed.AddField("**Duty**", "*" + text + "*", true);
             embed.AddField("**Type**", "*8-Man Raid*", true);
             if (bonusSRcheck > 24)
             {
                 embed.AddField("**Special Rules**", "*" + text3 + "*", false);
             }
             else
             {
                 embed.AddField("**Special Rules**", "*" + text3 + " and " + text5 + "*", false);
             }
             await ctx.RespondAsync("", embed : embed);
         }
         else if (text == "EX")
         {
             randomIndex = rng.Next(DlistEX.GetLength(0));
             text        = DlistEX[randomIndex, 0];
             text2       = DlistEX[randomIndex, 1];
             if (bonusSRcheck < 76)
             {
                 text4 = "*Amuse me.*";
                 text3 = "Minimum Item Level";
                 if (bonusSRcheck < 25)
                 {
                     text4 = "*Feed me.*";
                     text5 = SpecialRules[rng.Next(2, 5)];
                 }
             }
             var embed = new DiscordEmbedBuilder();
             embed.WithTitle("Providence Roulette").WithDescription(text4).WithImageUrl(text2).WithColor(new DiscordColor(255, 165, 0));
             embed.AddField("**Duty**", "*" + text + "*", true);
             embed.AddField("**Type**", "*8-Man Extreme*", true);
             if (bonusSRcheck > 24)
             {
                 embed.AddField("**Special Rules**", "*" + text3 + "*", false);
             }
             else
             {
                 embed.AddField("**Special Rules**", "*" + text3 + " and " + text5 + "*", false);
             }
             await ctx.RespondAsync("", embed : embed);
         }
     }
 }
Exemple #5
0
 public async Task Test(CommandContext ctx)
 {
     await ctx.RespondAsync(DiscordEmoji.FromName(ctx.Client, ":ok_hand:").ToString());
 }
        [Description("Shows the current status of the Light's Hope classic server.")] // this will be displayed to tell users what this command does when they invoke help
        public async Task Status(CommandContext context)                              // this command takes no arguments
        {
            // let's trigger a typing indicator to let users know we're working
            await context.TriggerTypingAsync();

            // Use the default configuration for AngleSharp
            var config = Configuration.Default;

            // Create a new context for evaluating webpages with the given config
            var browseContext = BrowsingContext.New(config);

            // Source to be parsed
            string response = await client.GetStringAsync("https://status.lightshope.org/");

            // Create a virtual request to specify the document to load (here from our fixed string)
            var document = await browseContext.OpenAsync(req => req.Content(response));

            // Grab the first relevant section, <div class="alert ..."></div> from the doc
            var    generalStatusDiv = document.QuerySelector("div.alert");
            string generalStatus    = generalStatusDiv.TextContent;

            // let's make the message a bit more colourful
            DiscordEmoji generalStatusEmoji;

            if (generalStatus.Contains("operational"))
            {
                // Set to 👌
                generalStatusEmoji = DiscordEmoji.FromName(context.Client, ":ok_hand:");
            }
            else
            {
                // Set to 👎
                generalStatusEmoji = DiscordEmoji.FromName(context.Client, ":thumbsdown:");
            }

            // Grab all <small class="text-component-1 ..."></small> from the doc
            var allSmall = document.QuerySelectorAll("small.text-component-1");

            // the sixth element in this list is the Northdale server
            string serverStatus = $"Northdale Server is {allSmall[5].TextContent.ToLower()}";

            DiscordEmoji serverStatusEmoji;
            DiscordColor textColor;

            if (generalStatus.Contains("operational"))
            {
                // Set to 👌
                serverStatusEmoji = DiscordEmoji.FromName(context.Client, ":ok_hand:");

                textColor = DiscordColor.PhthaloGreen;
            }
            else
            {
                // Set to 👎
                serverStatusEmoji = DiscordEmoji.FromName(context.Client, ":thumbsdown:");

                textColor = DiscordColor.Red;
            }

            // wrap it into an embed
            var embed = new DiscordEmbedBuilder
            {
                Title       = "Light's Hope Status",
                Description = $"{serverStatusEmoji} {serverStatus} | {generalStatusEmoji} {generalStatus}",

                Timestamp = DateTime.Now
            };

            // text color green if operational, otherwise red
            embed.WithColor(textColor);

            // respond with content
            await context.RespondAsync(embed : embed);
        }
Exemple #7
0
        private DiscordEmbedBuilder GetTradeEmbed(CommandContext ctx, string name1, string name2, List <GameObject> itemFromP1, List <GameObject> itemFromP2, bool tradeP1Confirmed = false, bool tradeP2Confirmed = false, bool tradeP1Canceled = false, bool tradeP2Canceled = false)
        {
            DiscordEmoji emojiConfirmed = DiscordEmoji.FromName(ctx.Client, ":white_check_mark:");
            DiscordEmoji emojiCanceled  = DiscordEmoji.FromName(ctx.Client, ":x:");

            string title = $"Trade between **{name1}** and **{name2}**";

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

            foreach (GameObject go in itemFromP1)
            {
                itemsP1.Add($"{go.Name} - Quantity: {go.Quantity}");
            }

            name1 = $"**{name1}**";
            if (tradeP1Confirmed)
            {
                name1 += "   " + emojiConfirmed;
            }
            else if (tradeP1Canceled)
            {
                name1 += "   " + emojiCanceled;
            }


            //2 character2
            List <string> itemsP2 = new List <string>();

            foreach (GameObject go in itemFromP2)
            {
                itemsP2.Add($"{go.Name} - Quantity: {go.Quantity}");
            }

            name2 = $"**{name2}**";
            if (tradeP2Confirmed)
            {
                name2 += "   " + emojiConfirmed;
            }
            else if (tradeP2Canceled)
            {
                name2 += "   " + emojiCanceled;
            }


            List <CustomEmbedField> attributes = new List <CustomEmbedField>
            {
                //1 items from P1
                new CustomEmbedField()
                {
                    Name       = name1,
                    Attributes = itemsP1
                },
                //2 items from P2
                new CustomEmbedField()
                {
                    Name       = name2,
                    Attributes = itemsP2
                }
            };


            string description = $"**{Config.Instance.Prefix}confirm** to confirm, **{Config.Instance.Prefix}cancel** to cancel, **{Config.Instance.Prefix}add [itemName] [quantity]** to add an item, **{Config.Instance.Prefix}remove [itemName]** to remove an item";

            DiscordEmbedBuilder embed = dep.Embed.CreateDetailledEmbed(title, attributes, description: description, inline: true);

            return(embed);
        }
Exemple #8
0
        public async Task Punishment(CommandContext ctx)
        {
            try
            {
                var texts = new[] { "Here you go.", $"You just want a punishment? I like that {DiscordEmoji.FromName(ctx.Client, Config.Emojis.Smug)}", "You think you can earn a favor from me? ...maybe." };

                await ctx.RespondAsync(texts[Helpers.RandomGenerator.RandomInt(0, texts.Length)]).ConfigureAwait(false);
            }
            catch (Exception)
            {
                var texts = new[] { "Here you go.", $"You just want a punishment? I like that!", "You think you can earn a favor from me? ...maybe." };

                await ctx.RespondAsync(texts[Helpers.RandomGenerator.RandomInt(0, texts.Length)]).ConfigureAwait(false);
            }

            await PunishmentInternal(ctx);
        }
Exemple #9
0
        private async Task <bool> CheckLocked(CommandContext ctx, Users user, DiscordContext context)
        {
            if (user.LockTime != null && user.LockTime > DateTime.Now)
            {
                TimeSpan?timeUntilFree = user.LockTime - DateTime.Now;

                TimeSpan newTimeUntilFree =
                    TimeSpan.FromTicks(timeUntilFree.Value.Ticks * Helpers.RandomGenerator.RandomInt(1, 3));

                if (newTimeUntilFree > TimeSpan.FromDays(365))
                {
                    _ = ctx.RespondAsync("F**k off");
                    return(false);
                }

                var responseText = "Oho, it seems like I told you to stay away from spinning the wheel...\n" +
                                   $"That means you get some more extra time of no spinning {DiscordEmoji.FromName(ctx.Client, Config.Emojis.Blush)}";

                if (int.TryParse(user.LockReason, out int reasonInt))
                {
                    var reason = (UserSetting.LockReason)reasonInt;

                    switch (reason)
                    {
                    case UserSetting.LockReason.Cooldown:
                        responseText =
                            "Oho, it seems like I told you to stay away from spinning the wheel...\n" +
                            $"That means you get some more extra time of no spinning {DiscordEmoji.FromName(ctx.Client, Config.Emojis.Blush)}";
                        user.LockTime += newTimeUntilFree;
                        break;

                    case UserSetting.LockReason.Extension:
                        responseText =
                            "Hey! I already told you, that you'd get a longer lock on the Wheel! You still want more? Sure!";
                        user.LockTime += newTimeUntilFree / 2;
                        break;

                    case UserSetting.LockReason.Task:
                        responseText = "Haha, there's no way you were able to finish your Task so quickly. Do your Task, " +
                                       "and then I'll give you another minute to think about your Actions.";
                        user.LockTime += TimeSpan.FromMinutes(1);
                        break;
                    }
                }

                user.LockReason = ((int)UserSetting.LockReason.Extension).ToString();

                await ctx.RespondAsync(responseText);

                await context.SaveChangesAsync();

                return(false);
            }
            else
            {
                return(true);
            }
        }
Exemple #10
0
        public Task ListAsync(CommandContext ctx,
                              [RemainingText, Description("Specific trigger.")] string trigger)
        {
            if (!this.Shared.EmojiReactions.TryGetValue(ctx.Guild.Id, out ConcurrentHashSet <EmojiReaction> ereactions) || !ereactions.Any())
            {
                throw new CommandFailedException("This guild has no text reactions registered.");
            }

            IEnumerable <EmojiReaction> ers = ereactions.Where(t => t.IsMatch(trigger));

            if (!ers.Any())
            {
                throw new CommandFailedException("None of the reactions respond to such trigger.");
            }

            return(ctx.RespondAsync(embed: new DiscordEmbedBuilder {
                Title = "Text reaction that matches the trigger",
                Description = string.Join("\n", ers.Select(er => $"{Formatter.InlineCode(er.Id.ToString())} | {DiscordEmoji.FromName(ctx.Client, er.Response)} | {Formatter.InlineCode(string.Join(", ", er.TriggerStrings))}")),
                Color = this.ModuleColor
            }.Build()));
        }
Exemple #11
0
 public static async Task RespondWithReaction(CommandContext ctx)
 {
     var emoji = DiscordEmoji.FromName(ctx.Client, ":ok_hand:");
     await ctx.Message.CreateReactionAsync(emoji);
 }
Exemple #12
0
        public async Task Unlock(CommandContext ctx)
        {
            ulong userid = 0;

            if (ctx.Member != null)
            {
                userid = ctx.Member.Id;
            }
            else
            {
                userid = ctx.User.Id;
            }

            //first retrieve the interactivity module from the client
            var interactivity = ctx.Client.GetInteractivity();

            //specify the emoji
            var accept = DiscordEmoji.FromName(ctx.Client, ":white_check_mark:");
            var reject = DiscordEmoji.FromName(ctx.Client, ":x:");

            //announce
            var requestMsg = await ctx.RespondAsync($"Would you like to get notified whenever World of Warcraft (Retail) gets updated?");

            await Task.Delay(100);

            await requestMsg.CreateReactionAsync(accept); //check

            await Task.Delay(50);

            await requestMsg.CreateReactionAsync(reject); //cross

            await Task.Delay(50);

            var em = await interactivity.WaitForReactionAsync(xe => xe.Emoji == accept || xe.Emoji == reject, ctx.User, TimeSpan.FromSeconds(10));

            if (em.Result != null)
            {
                if (UpdateChecker.Instance == null)
                {
                    new UpdateChecker();
                }
                //user reacted
                if (em.Result.Emoji == accept)
                {
                    await ctx.RespondAsync("Subscribtion activated!");

                    if (UpdateChecker.Instance.SubscriberUsers.FindIndex(x => x == userid) == -1)
                    {
                        UpdateChecker.Instance.SubscriberUsers.Add(userid);
                    }
                }
                else
                {
                    var uIndex = UpdateChecker.Instance.SubscriberUsers.FindIndex(x => x == userid);
                    if (uIndex > -1)
                    {
                        UpdateChecker.Instance.SubscriberUsers.RemoveAt(uIndex);
                        await ctx.RespondAsync("Subscribtion removed!");
                    }
                    else
                    {
                        //nothing?
                    }
                }
                await requestMsg.DeleteAsync();
            }
            else
            {
                //timeout
                await requestMsg.DeleteAsync();
            }
        }
Exemple #13
0
 public EmojiAttribute(string unicode)
 {
     this.Emoji = DiscordEmoji.FromUnicode(Program.Client, unicode) ?? DiscordEmoji.FromName(Program.Client, unicode);
 }
Exemple #14
0
        public async Task apagar(CommandContext ctx)
        {
            List <EventoModel> eventos = new Evento().FindAll(_ => true);

            if (eventos.Count > 0)
            {
                List <Page> pages = new List <Page>();
                eventos.ForEach(async e => pages.Add(new Page($"", new DiscordEmbedBuilder(await EmbedExtended.AsyncEventoEmbed(e)))));
                PaginationEmojis emojis = new PaginationEmojis
                {
                    Left      = DiscordEmoji.FromName(ctx.Client, ":arrow_left:"),
                    Stop      = DiscordEmoji.FromName(ctx.Client, ":stop_button:"),
                    Right     = DiscordEmoji.FromName(ctx.Client, ":arrow_right:"),
                    SkipLeft  = null,
                    SkipRight = null
                };
                var msg = await ctx.RespondAsync(embed : EmbedBase.InputEmbed($"Selecione o evento. Depois clique em {emojis.Stop.ToString()} para confirmar."));

                await ctx.Channel.SendPaginatedMessageAsync(ctx.User, pages.ToArray(), emojis, PaginationBehaviour.WrapAround, PaginationDeletion.Default, TimeSpan.FromMinutes(30));

                var lastMsg = (await ctx.Channel.GetMessagesAfterAsync(msg.Id)).ToList().FirstOrDefault(x => x.Author == msg.Author && msg.Embeds.Count > 0);
                var id      = int.Parse(lastMsg.Embeds[0].Fields.ToList().Find(x => x.Name == "Id").Value);
                var evento  = eventos.Find(x => x.Id == id);
                await lastMsg.DeleteAsync();

                if (evento.Times == null)
                {
                    await ctx.RespondAsync(embed : EmbedBase.OutputEmbed("Não há nenhum time neste evento."));
                }
                else
                {
                    List <TimeModel> times    = new List <TimeModel>();
                    List <string>    nomes    = new List <string>();
                    Regex            getUlong = new Regex(@"(?<!\.)\d+(?!\.)");
                    evento.Times.ForEach(x => times.Add(new Time().Find(y => y.Id == x)));
                    times.ForEach(x => nomes.Add($"{x.Id} - {x.Nome}"));
                    await msg.ModifyAsync(embed : EmbedBase.InputEmbed("Time q será apagado [Número]"));

                    var list = await ctx.RespondAsync(embed : EmbedBase.OrderedListEmbed(nomes, $"Times em {evento.Nome}:"));

                    var responce = await ctx.Message.GetNextMessageAsync();

                    if (getUlong.IsMatch(responce.Result.Content))
                    {
                        int i = int.Parse(getUlong.Match(responce.Result.Content).ToString());
                        if (times.Any(x => x.Id == i))
                        {
                            new Time().Delete(x => x.Id == i);
                            await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Time apagado com sucesso."));
                        }
                        else
                        {
                            await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Número inválido. Comando Cancelado."));
                        }
                    }
                }
            }
            else
            {
                await ctx.RespondAsync(embed : EmbedBase.OutputEmbed("Não há nenhum evento ativo no momento. Considere criar um!"));
            }
        }
Exemple #15
0
        private static async Task DispatchTimer(TimerData tdata)
        {
            var timer  = tdata.DbTimer;
            var client = tdata.Context;

            if (timer.ActionType == TimerActionType.Reminder)
            {
                DiscordChannel chn = null;
                try
                {
                    chn = await client.GetChannelAsync((ulong)timer.ChannelId);
                }
                catch
                {
                    return;
                }

                if (chn == null)
                {
                    return;
                }

                var data  = timer.GetData <TimerReminderData>();
                var emoji = DiscordEmoji.FromName(client, ":alarm_clock:");
                var user  = (ulong)timer.UserId;
                var msg   = $"{emoji} <@!{user}>, you wanted to be reminded of the following:\n\n{data.ReminderText.BreakMentions()}";
                await chn.SafeMessageUnformattedAsync(msg, false);

                // ALWAYS filter stuff so i set it to false. No need to @everyone in a reminder.
            }
            else if (timer.ActionType == TimerActionType.Unban)
            {
                var data = timer.GetData <TimerUnbanData>();
                if (client.Guilds.Any(x => x.Key == (ulong)timer.GuildId))
                {
                    using (var db = tdata.Database.CreateContext())
                    {
                        var guild = client.Guilds[(ulong)timer.GuildId];
                        try
                        {
                            await guild.UnbanMemberAsync((ulong)data.UserId);
                        }
                        catch
                        {
                            // ignored
                        }

                        var settings = guild.GetGuildSettings(db);
                        await client.LogAutoActionAsync(guild, db, $"Member unbanned: {data.DisplayName}#{data.Discriminator} (ID: {data.UserId})");
                    }
                }
            }
            else if (timer.ActionType == TimerActionType.Unmute)
            {
                var data = timer.GetData <TimerUnmuteData>();
                if (client.Guilds.Any(x => x.Key == (ulong)timer.GuildId))
                {
                    using (var db = tdata.Database.CreateContext())
                    {
                        var guild  = client.Guilds[(ulong)timer.GuildId];
                        var member = await guild.GetMemberAsync((ulong)data.UserId);

                        var role = (DiscordRole)null;
                        try
                        {
                            role = guild.GetRole((ulong)data.MuteRoleId);
                        }
                        catch (Exception)
                        {
                            try
                            {
                                role = guild.GetRole(guild.GetGuildSettings(db).MuteRoleId);
                            }
                            catch (Exception)
                            {
                                await client.LogAutoActionAsync(guild, db, $"**[IMPORTANT]**\nFailed to unmute member: {data.DisplayName}#{data.Discriminator} (ID: {data.UserId})\nMute role does not exist!");

                                return;
                            }
                        }
                        await member.RevokeRoleAsync(role, "");

                        await client.LogAutoActionAsync(guild, db, $"Member unmuted: {data.DisplayName}#{data.Discriminator} (ID: {data.UserId})");
                    }
                }
            }
            else if (timer.ActionType == TimerActionType.Pin)
            {
                var data = timer.GetData <TimerPinData>();
                if (client.Guilds.Any(x => x.Key == (ulong)timer.GuildId))
                {
                    using (var db = tdata.Database.CreateContext())
                    {
                        var guild   = client.Guilds[(ulong)timer.GuildId];
                        var channel = guild.GetChannel((ulong)data.ChannelId);
                        var message = await channel.GetMessageAsync((ulong)data.MessageId);

                        await message.PinAsync();

                        await client.LogAutoActionAsync(guild, db, $"Scheduled pin: Message with ID: {data.MessageId} in Channel #{channel.Name} ({channel.Id})");
                    }
                }
            }
            else if (timer.ActionType == TimerActionType.Unpin)
            {
                var data = timer.GetData <TimerPinData>();
                if (client.Guilds.Any(x => x.Key == (ulong)timer.GuildId))
                {
                    using (var db = tdata.Database.CreateContext())
                    {
                        var guild   = client.Guilds[(ulong)timer.GuildId];
                        var channel = guild.GetChannel((ulong)data.ChannelId);
                        var message = await channel.GetMessageAsync((ulong)data.MessageId);

                        await message.UnpinAsync();

                        await client.LogAutoActionAsync(guild, db, $"Scheduled unpin: Message with ID: {data.MessageId} in Channel #{channel.Name} ({channel.Id})");
                    }
                }
            }
        }
Exemple #16
0
        public async Task kick(CommandContext ctx, [Description("O Membro q será kickado (Menção/ID)")] DiscordMember membro)
        {
            List <EventoModel> eventos = new Evento().FindAll(_ => true);

            if (eventos.Count > 0)
            {
                List <Page> pages = new List <Page>();
                eventos.ForEach(async x => pages.Add(new Page("", new DiscordEmbedBuilder(await EmbedExtended.AsyncEventoEmbed(x)))));
                PaginationEmojis emojis = new PaginationEmojis
                {
                    Left      = DiscordEmoji.FromName(ctx.Client, ":arrow_left:"),
                    Stop      = DiscordEmoji.FromName(ctx.Client, ":stop_button:"),
                    Right     = DiscordEmoji.FromName(ctx.Client, ":arrow_right:"),
                    SkipLeft  = null,
                    SkipRight = null
                };
                var msg = await ctx.RespondAsync(embed : EmbedBase.InputEmbed($"Selecione o evento que deseja adicionar o membro. Depois clique em {emojis.Stop.ToString()} para confirmar."));

                await ctx.Channel.SendPaginatedMessageAsync(ctx.User, pages.ToArray(), emojis, PaginationBehaviour.WrapAround, PaginationDeletion.Default, TimeSpan.FromMinutes(30));

                var lastMsg = (await ctx.Channel.GetMessagesAfterAsync(msg.Id)).ToList().FirstOrDefault(x => x.Author == msg.Author && msg.Embeds.Count > 0);
                var id      = int.Parse(lastMsg.Embeds[0].Fields.ToList().Find(x => x.Name == "Id").Value);
                var evento  = eventos.Find(x => x.Id == id);
                await lastMsg.DeleteAsync();

                List <TimeModel> times = new Time().FindAll(x => x.EventoId == id && x.LiderId == ctx.Member.Id);
                if (times.Count > 0)
                {
                    var time = times[0];
                    if (time.LiderId == membro.Id && membro.Id == ctx.Member.Id)
                    {
                        await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Você não pode kickar à si mesmo."));
                    }
                    else
                    {
                        if (time.Jogadores.Exists(x => x == membro.Id) || time.Reservas != null)
                        {
                            if (time.Reservas != null && time.Reservas.Exists(x => x == membro.Id))
                            {
                                time.Reservas.Remove(membro.Id);
                            }
                            else
                            {
                                time.Jogadores.Remove(membro.Id);
                            }
                            new Time().Update(x => x.Id == time.Id, time);
                            await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Membro kickado com sucesso!"));
                        }
                        else
                        {
                            await msg.ModifyAsync(embed : EmbedBase.OutputEmbed($"Esse membro não participa do time {time.Nome}"));
                        }
                    }
                }
                else
                {
                    await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Você não é lider de um time neste evento."));
                }
            }
            else
            {
                await ctx.RespondAsync(embed : EmbedBase.OutputEmbed("Não há eventos ativos no momento. Inscrição de times foi desativada."));
            }
        }
        [Description("Type the name of an existing item and it will show up with a link in chat.")] // this will be displayed to tell users what this command does when they invoke help
        public async Task Linkerator(CommandContext context, [Description("The item you want to link.")] string item)
        {
            // let's trigger a typing indicator to let users know we're working
            await context.TriggerTypingAsync();

            // Use the default configuration for AngleSharp
            var config = Configuration.Default;

            // Create a new context for evaluating webpages with the given config
            var browseContext = BrowsingContext.New(config);

            string apiKey             = Environment.GetEnvironmentVariable("GOOGLE_API_KEY");
            string customSearchEngine = Environment.GetEnvironmentVariable("SEARCH_ENGINE_KEY");
            var    svc = new Google.Apis.Customsearch.v1.CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer {
                ApiKey = apiKey
            });
            var listRequest = svc.Cse.List(item);

            listRequest.Cx  = customSearchEngine;
            listRequest.Num = 5; // get first 5 search results
            var searchItems = listRequest.Execute();

            // wrap it into an embed
            var embed = new DiscordEmbedBuilder();

            embed.WithFooter($"Search results for {item}...");

            bool itemFound  = false;
            var  searchItem = new Google.Apis.Customsearch.v1.Data.Result();

            if (searchItems.Items != null)
            {
                foreach (var currentItem in searchItems.Items)
                {
                    if (currentItem.Title.Contains("Item") && !itemFound)
                    {
                        itemFound  = true;
                        searchItem = currentItem;
                    }
                }
            }

            if (itemFound) // got a result, and it's an item!
            {
                embed.WithTitle(searchItem.Title.Replace(" - Item - World of Warcraft", ""));
                embed.WithDescription(searchItem.Snippet);
                embed.WithUrl(searchItem.Link);

                // Source to be parsed
                string response = await client.GetStringAsync(searchItem.Link);

                var document = await browseContext.OpenAsync(req => req.Content(response));

                // all <link> tags
                var links = document.QuerySelectorAll("link");
                foreach (var link in links)
                {
                    // looking for <link rel="image_src" href="item icon image">
                    if (link.HasAttribute("rel") && link.GetAttribute("rel").Contains("image_src") &&
                        link.HasAttribute("href"))
                    {
                        embed.WithThumbnailUrl(link.GetAttribute("href"));
                    }
                }
            }
            else // not an item
            {
                DiscordEmoji searchEmoji = DiscordEmoji.FromName(context.Client, ":grimacing:");
                embed.WithTitle($"{searchEmoji} Couldn't find a page for this item, is it possible you misspelled it or it isn't an item from Classic WoW?");
            }

            // respond with content
            await context.RespondAsync(embed : embed);
        }
Exemple #18
0
        public async Task sair(CommandContext ctx)
        {
            List <EventoModel> eventos = new Evento().FindAll(_ => true);

            if (eventos.Count > 0)
            {
                List <Page> pages = new List <Page>();
                eventos.ForEach(async e => pages.Add(new Page($"", new DiscordEmbedBuilder(await EmbedExtended.AsyncEventoEmbed(e)))));
                PaginationEmojis emojis = new PaginationEmojis
                {
                    Left      = DiscordEmoji.FromName(ctx.Client, ":arrow_left:"),
                    Stop      = DiscordEmoji.FromName(ctx.Client, ":stop_button:"),
                    Right     = DiscordEmoji.FromName(ctx.Client, ":arrow_right:"),
                    SkipLeft  = null,
                    SkipRight = null
                };
                var msg = await ctx.RespondAsync(embed : EmbedBase.InputEmbed($"Selecione o evento que deseja participar. Depois clique em {emojis.Stop.ToString()} para confirmar."));

                await ctx.Channel.SendPaginatedMessageAsync(ctx.User, pages.ToArray(), emojis, PaginationBehaviour.WrapAround, PaginationDeletion.Default, TimeSpan.FromMinutes(30));

                var lastMsg = (await ctx.Channel.GetMessagesAfterAsync(msg.Id)).ToList().FirstOrDefault(x => x.Author == msg.Author && msg.Embeds.Count > 0);
                var id      = int.Parse(lastMsg.Embeds[0].Fields.ToList().Find(x => x.Name == "Id").Value);
                var evento  = eventos.Find(x => x.Id == id);
                if (new Time().Find(x => x.EventoId == id && (x.Jogadores.Any(y => y == ctx.Member.Id) || x.Reservas.Any(y => y == ctx.Member.Id))) != null)
                {
                    var time = new Time().Find(x => x.EventoId == id && (x.Jogadores.Any(y => y == ctx.Member.Id) || x.Reservas.Any(y => y == ctx.Member.Id)));
                    await lastMsg.DeleteAsync();

                    if (time.LiderId != ctx.Member.Id)
                    {
                        await msg.ModifyAsync(embed : EmbedBase.InputEmbed($"Você deseja sair de {time.Nome}?.[s/n]"));

                        var input = await ctx.Message.GetNextMessageAsync();

                        switch (input.Result.Content.ToLowerInvariant().Trim()[0])
                        {
                        case 'y':
                        case 's':
                            if (time.Jogadores.Contains(ctx.Member.Id))
                            {
                                time.Jogadores.Remove(ctx.Member.Id);
                            }
                            if (time.Reservas.Contains(ctx.Member.Id))
                            {
                                time.Reservas.Remove(ctx.Member.Id);
                            }
                            new Time().Update(x => x.Id == time.Id, time);
                            await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Você saiu do time com sucesso!"));

                            break;

                        default:
                            await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Comando cancelado."));

                            break;
                        }
                    }
                    else
                    {
                        await msg.ModifyAsync(embed : EmbedBase.InputEmbed($"Você deseja **apagar** {time.Nome}?.[s/n]"));

                        var input = await ctx.Message.GetNextMessageAsync();

                        switch (input.Result.Content.ToLowerInvariant().Trim()[0])
                        {
                        case 'y':
                        case 's':
                            new Time().Delete(time);
                            await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Time apagado com sucesso!"));

                            break;

                        default:
                            await msg.ModifyAsync(embed : EmbedBase.OutputEmbed("Comando cancelado."));

                            break;
                        }
                    }
                }
                else
                {
                    await ctx.RespondAsync(embed : EmbedBase.OutputEmbed("Você não participa de nenhum time neste evento."));
                }
            }
            else
            {
                await ctx.RespondAsync(embed : EmbedBase.OutputEmbed("Não há eventos ativos no momento. Inscrição de times foi desativada."));
            }
        }
Exemple #19
0
 public override DiscordEmoji GetEmoji()
 {
     return(DiscordEmoji.FromName(Bot.Client, Emoji));
 }
Exemple #20
0
        public async Task TohoDBGet(CommandContext ctx, [RemainingText] string song)
        {
            var interactivity = ctx.Client.GetInteractivity();
            var init          = await ctx.RespondAsync("Searching");

            int select = 0;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://touhoudb.com/api/songs?query=" + song + "&maxResults=10&sort=FavoritedTimes&preferAccurateMatches=true&nameMatchMode=Auto&fields=Lyrics,PVs&lang=English");

            request.Method = "GET";
            request.Accept = "application/json";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (!((int)response.StatusCode == 200))
            {
                await ctx.RespondAsync("Song not found (Note: In weird cases it finds the song but still returns 0 results, since this crashes the bot, its not showing anything here)");

                return;
            }
            Stream       dataStream         = response.GetResponseStream();
            StreamReader reader             = new StreamReader(dataStream);
            string       responseFromServer = reader.ReadToEnd();
            //await ctx.RespondAsync("data got");
            var myresponse = JsonConvert.DeserializeObject <VocaDBGetData>(responseFromServer);

            response.Close();
            //await ctx.RespondAsync("data: " + myresponse.items[0].artistString);
            if (myresponse.items.Count == 0)
            {
                await init.ModifyAsync("nothing found uwu (Note: In weird cases it finds the song but still returns 0 results, since this crashes the bot, its not showing anything here)");

                return;
            }
            if (myresponse.items.Count > 1)
            {
                var embed2 = new DiscordEmbedBuilder
                {
                    Color       = new DiscordColor("#68D3D2"),
                    Title       = "TouhouDB Search",
                    Description = "Multiple entries were found, select one!"
                };
                int      an    = 0;
                string[] nums  = { ":one:", ":two:", ":three:", ":four:", ":five:", ":six:", ":seven:", ":eight:", ":nine:", ":keycap_ten:" };
                string   songs = "";
                var      blank = DiscordEmoji.FromGuildEmote(ctx.Client, 435447550196318218);
                foreach (var entries in myresponse.items)
                {
                    songs += $"React {DiscordEmoji.FromName(ctx.Client, nums[an])} for {entries.name} by {entries.artistString} \n";
                    await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, nums[an]));

                    an++;
                }
                embed2.AddField("Found Songs", songs);
                await init.ModifyAsync("", embed : embed2.Build());

                var one   = DiscordEmoji.FromName(ctx.Client, ":one:");
                var two   = DiscordEmoji.FromName(ctx.Client, ":two:");
                var three = DiscordEmoji.FromName(ctx.Client, ":three:");
                var four  = DiscordEmoji.FromName(ctx.Client, ":four:");
                var five  = DiscordEmoji.FromName(ctx.Client, ":five:");
                var six   = DiscordEmoji.FromName(ctx.Client, ":six:");
                var seven = DiscordEmoji.FromName(ctx.Client, ":seven:");
                var eight = DiscordEmoji.FromName(ctx.Client, ":eight:");
                var nine  = DiscordEmoji.FromName(ctx.Client, ":nine:");
                var ten   = DiscordEmoji.FromName(ctx.Client, ":keycap_ten:");
                try {
                    var reSelect = await interactivity.WaitForMessageReactionAsync(xe => (xe == one || xe == two || xe == three || xe == four || xe == five || xe == six || xe == seven || xe == eight || xe == nine || xe == ten), init, ctx.Message.Author, TimeSpan.FromSeconds(60));

                    if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":one:"))
                    {
                        select = 0;
                    }
                    else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":two:"))
                    {
                        select = 1;
                    }
                    else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":three:"))
                    {
                        select = 2;
                    }
                    else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":four:"))
                    {
                        select = 3;
                    }
                    else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":five:"))
                    {
                        select = 4;
                    }
                    else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":six:"))
                    {
                        select = 5;
                    }
                    else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":seven:"))
                    {
                        select = 6;
                    }
                    else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":eight:"))
                    {
                        select = 7;
                    }
                    else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":nine:"))
                    {
                        select = 8;
                    }
                    else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":keycap_ten:"))
                    {
                        select = 9;
                    }
                }
                catch
                {
                    return;
                }
                await init.DeleteAllReactionsAsync();
            }
            HttpWebRequest drequest = (HttpWebRequest)WebRequest.Create("https://touhoudb.com/api/songs/" + myresponse.items[select].id + "/derived?lang=English");

            drequest.Method = "GET";
            drequest.Accept = "application/json";
            HttpWebResponse dresponse = (HttpWebResponse)drequest.GetResponse();

            if (!((int)dresponse.StatusCode == 200))
            {
                await ctx.RespondAsync("Song not found (Note: In weird cases it finds the song but still returns 0 results, since this crashes the bot, its not showing anything here)");

                return;
            }
            Stream       ddataStream         = dresponse.GetResponseStream();
            StreamReader dreader             = new StreamReader(ddataStream);
            string       dresponseFromServer = dreader.ReadToEnd();

            dresponse.Close();
            //await ctx.RespondAsync("data got");
            //var myresponse = JsonConvert.DeserializeObject<VocaDBGetData>(responseFromServer);
            var   ddresponse = JsonConvert.DeserializeObject <List <VTUDBrGet> >(dresponseFromServer);
            int   oof2       = myresponse.items[select].pvs.FindIndex(x => x.url.Contains("youtu"));
            int   oof3       = myresponse.items[select].pvs.FindIndex(x => x.url.Contains("nico"));
            YTDLC got        = new YTDLC();

            BaseiInfo(ctx, init, select, myresponse, ddresponse);
            await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":pushpin:"));

            if (myresponse.items[select].lyrics.Count != 0)
            {
                await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":page_facing_up:"));
            }
            if (myresponse.items[select].pvs.Count != 0)
            {
                await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":movie_camera:"));

                if (myresponse.items[select].pvs.Any(x => (x.url.Contains("youtu") || x.url.Contains("nico"))))
                {
                    await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":arrow_double_down:"));
                }
            }
            if (ddresponse.Count != 0)
            {
                await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":revolving_hearts:"));
            }
            await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":x:"));

            bool loop = true;

            while (loop == true)
            {
                var emoji  = DiscordEmoji.FromName(ctx.Client, ":pushpin:");
                var emoji2 = DiscordEmoji.FromName(ctx.Client, ":page_facing_up:");
                var emoji3 = DiscordEmoji.FromName(ctx.Client, ":movie_camera:");
                var emoji4 = DiscordEmoji.FromName(ctx.Client, ":x:");
                var emoji5 = DiscordEmoji.FromName(ctx.Client, ":revolving_hearts:");//:arrow_double_down:
                //var emoji6 = DiscordEmoji.FromName(ctx.Client, ":arrow_double_down:");
                try
                {
                    var reSelect = await interactivity.WaitForMessageReactionAsync(xe => (xe == emoji || xe == emoji2 || xe == emoji3 || xe == emoji4 || xe == emoji5), init, ctx.Message.Author, TimeSpan.FromSeconds(123));

                    if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":pushpin:"))
                    {
                        BaseiInfo(ctx, init, select, myresponse, ddresponse);
                    }
                    else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":page_facing_up:"))
                    {
                        LyricEm(ctx, init, select, myresponse, ddresponse);
                    }
                    else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":movie_camera:"))
                    {
                        PVShowInfo(ctx, init, select, myresponse, ddresponse, oof2);
                    }
                    else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":revolving_hearts:"))
                    {
                        Derratives(ctx, init, select, myresponse, ddresponse);
                    }
                    else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":x:"))
                    {
                        loop = false;
                        await init.DeleteAllReactionsAsync();
                    }
                    else
                    {
                        loop = false;
                        await init.DeleteAllReactionsAsync();
                    }
                }
                catch
                {
                    return;
                }
            }
        }
Exemple #21
0
        public async Task role(CommandContext ctx, [Description("Operação (add/del)")] string operation)
        {
            switch (operation)
            {
            case "add":
                var message = await ctx.RespondAsync(embed : EmbedBase.InputEmbed("Canal do discord (ID/Menção)"));

                var responce = await ctx.Message.GetNextMessageAsync();

                Regex getUlong = new Regex(@"(?<!\.)\d+(?!\.)");
                var   match    = getUlong.Match(responce.Result.Content).ToString();
                if (!String.IsNullOrWhiteSpace(match))
                {
                    ulong id = ulong.Parse(match);
                    if (new ReactChannel().Find(x => x.DiscordID == id) != null)
                    {
                        DiscordChannel ch    = ctx.Guild.GetChannel(id);
                        var            cat   = new ReactCategory().FindAll(_ => true);
                        List <string>  names = new List <string>();
                        cat.ForEach(x => names.Add(x.Name));
                        await message.ModifyAsync(embed : EmbedBase.InputEmbed("Numero da categoria que você quer apagar"));

                        var list = await ctx.RespondAsync(embed : EmbedBase.OrderedListEmbed(names, "Categorias"));

                        responce = await responce.Result.GetNextMessageAsync();

                        match = getUlong.Match(responce.Result.Content).ToString();
                        if (!String.IsNullOrWhiteSpace(match))
                        {
                            var i = int.Parse(match);
                            if (i <= names.Count)
                            {
                                var category = cat[i];
                                await list.DeleteAsync();

                                await message.ModifyAsync(embed : EmbedBase.InputEmbed("Emoji (Id/Menção)"));

                                responce = await responce.Result.GetNextMessageAsync();

                                var getEmoji = new Regex(@"(\:\w*\:)");
                                match = getEmoji.Match(responce.Result.Content).ToString();
                                if (!String.IsNullOrWhiteSpace(match))
                                {
                                    var emoji = DiscordEmoji.FromName(ctx.Client, match);
                                    await message.ModifyAsync(embed : EmbedBase.InputEmbed("Cargo (Id/Menção)"));

                                    responce = await responce.Result.GetNextMessageAsync();

                                    match = getUlong.Match(responce.Result.Content).ToString();
                                    if (!String.IsNullOrWhiteSpace(match))
                                    {
                                        id = ulong.Parse(match);
                                        var            role      = ctx.Guild.GetRole(id);
                                        ReactRoleModel roleModel = new ReactRoleModel
                                        {
                                            RoleId     = role.Id,
                                            EmojiId    = emoji.Id,
                                            CategoryId = category.Id
                                        };
                                        new ReactRole().Insert(roleModel);
                                        var catmsg = await ch.GetMessageAsync(category.MessageId);

                                        await catmsg.CreateReactionAsync(emoji);

                                        category = new ReactCategory().Find(x => x.Id == category.Id);
                                        await catmsg.ModifyAsync(embed : await EmbedExtended.ReactCategory(category));

                                        await message.ModifyAsync(embed : EmbedBase.OutputEmbed("Cargo adicionado com sucesso!"));
                                    }
                                    else
                                    {
                                        await message.ModifyAsync(embed : EmbedBase.OutputEmbed("Mensagem inválida. Comando Cancelado"));
                                    }
                                }
                                else
                                {
                                    await message.ModifyAsync(embed : EmbedBase.OutputEmbed("Mensagem inválida. Comando Cancelado"));
                                }
                            }
                        }
                        else
                        {
                            await message.ModifyAsync(embed : EmbedBase.OutputEmbed("Número inválido. Comando Cancelado"));
                        }
                    }
                }
                else
                {
                    await message.ModifyAsync(embed : EmbedBase.OutputEmbed("Mensagem inválida. Comando Cancelado"));
                }
                break;

            case "del":
                message = await ctx.RespondAsync(embed : EmbedBase.InputEmbed("Canal do discord (ID/Menção)"));

                responce = await ctx.Message.GetNextMessageAsync();

                getUlong = new Regex(@"(?<!\.)\d+(?!\.)");
                match    = getUlong.Match(responce.Result.Content).ToString();
                if (!String.IsNullOrWhiteSpace(match))
                {
                    ulong id = ulong.Parse(match);
                    if (new ReactChannel().Find(x => x.DiscordID == id) != null)
                    {
                        DiscordChannel ch    = ctx.Guild.GetChannel(id);
                        var            cat   = new ReactCategory().FindAll(_ => true);
                        List <string>  names = new List <string>();
                        cat.ForEach(x => names.Add(x.Name));
                        await message.ModifyAsync(embed : EmbedBase.InputEmbed("Numero da categoria que você quer apagar"));

                        var list = await ctx.RespondAsync(embed : EmbedBase.OrderedListEmbed(names, "Categorias"));

                        responce = await responce.Result.GetNextMessageAsync();

                        match = getUlong.Match(responce.Result.Content).ToString();
                        if (!String.IsNullOrWhiteSpace(match))
                        {
                            var i = int.Parse(match);
                            if (i <= names.Count)
                            {
                                var category = cat[i];
                                List <ReactRoleModel> roles = new List <ReactRoleModel>();
                                if (category.Roles != null)
                                {
                                    category.Roles.ForEach(x => roles.Add(new ReactRole().Find(y => y.Id == x)));
                                }
                                if (roles.Count > 0)
                                {
                                    List <string> role_string = new List <string>();
                                    foreach (var r in roles)
                                    {
                                        var role  = ctx.Guild.GetRole(r.RoleId);
                                        var emoji = DiscordEmoji.FromGuildEmote(ctx.Client, r.EmojiId);
                                        role_string.Add($"{emoji} - {role.Name}");
                                    }
                                    await list.ModifyAsync(embed : EmbedBase.OrderedListEmbed(role_string, "Cargos"));

                                    await message.ModifyAsync(embed : EmbedBase.InputEmbed("Numero do cargo à ser deletado"));

                                    responce = await responce.Result.GetNextMessageAsync();

                                    match = getUlong.Match(responce.Result.Content).ToString();
                                    if (!String.IsNullOrWhiteSpace(match))
                                    {
                                        i = int.Parse(match);
                                        if (roles.Count >= i)
                                        {
                                            var rr = roles[i];
                                            await list.DeleteAsync();

                                            var emoji = DiscordEmoji.FromGuildEmote(ctx.Client, rr.EmojiId);
                                            new ReactRole().Delete(rr);
                                            category = new ReactCategory().Find(x => x.Id == category.Id);
                                            var catmsg = await ch.GetMessageAsync(category.MessageId);

                                            var members = await catmsg.GetReactionsAsync(emoji);

                                            members.ToList().ForEach(async x => await catmsg.DeleteReactionAsync(emoji, x));
                                            await catmsg.ModifyAsync(embed : await EmbedExtended.ReactCategory(category));

                                            await message.ModifyAsync(embed : EmbedBase.OutputEmbed("Cargo apagado com sucesso!"));
                                        }
                                    }
                                }
                                else
                                {
                                    await list.DeleteAsync();

                                    await message.ModifyAsync(embed : EmbedBase.OutputEmbed("Essa categoria não possui cargos."));
                                }
                            }
                        }
                    }
                }
                break;
            }
        }
Exemple #22
0
        public async void LyricEm(CommandContext ctx, DiscordMessage init, int select, dynamic myresponse, dynamic dresponse)
        {
            try
            {
                try { await init.DeleteReactionAsync(DiscordEmoji.FromName(ctx.Client, ":page_facing_up:"), ctx.Message.Author); }
                catch { }
                var    interactivity = ctx.Client.GetInteractivity();
                int    lyse          = 0;
                string tumurl        = "";
                if (myresponse.items[select].pvs.Count != 0)
                {
                    tumurl = myresponse.items[select].pvs[0].thumbUrl;
                }
                var emim = new DiscordEmbedBuilder
                {
                    Color        = new DiscordColor("#68D3D2"),
                    Title        = "Results!",
                    ThumbnailUrl = tumurl
                };

                emim.AddField("Artist", myresponse.items[select].artistString, true);
                emim.AddField("Title", myresponse.items[select].defaultName, true);
                emim.WithFooter("Requested by " + ctx.Message.Author.Username, ctx.Message.Author.AvatarUrl);
                if (myresponse.items[select].lyrics.Count > 1)
                {
                    await init.DeleteAllReactionsAsync();

                    var embed2 = new DiscordEmbedBuilder
                    {
                        Color       = new DiscordColor("#68D3D2"),
                        Title       = "Lyrics Entries!",
                        Description = "Multiple entries were found, select one!"
                    };
                    int      an    = 0;
                    string[] nums  = { ":one:", ":two:", ":three:", ":four:", ":five:", ":six:", ":seven:", ":eight:", ":nine:", ":keycap_ten:" };
                    var      blank = DiscordEmoji.FromGuildEmote(ctx.Client, 435447550196318218);
                    foreach (var entries in myresponse.items[select].lyrics)
                    {
                        if (an == 10)
                        {
                            break;
                        }
                        embed2.AddField("React " + DiscordEmoji.FromName(ctx.Client, nums[an]), $"[{entries.translationType}] + {entries.cultureCode.ToUpper()} by {entries.source}");
                        await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, nums[an]));

                        an++;
                    }
                    await init.ModifyAsync(null, embed : embed2.Build());

                    var one   = DiscordEmoji.FromName(ctx.Client, ":one:");
                    var two   = DiscordEmoji.FromName(ctx.Client, ":two:");
                    var three = DiscordEmoji.FromName(ctx.Client, ":three:");
                    var four  = DiscordEmoji.FromName(ctx.Client, ":four:");
                    var five  = DiscordEmoji.FromName(ctx.Client, ":five:");
                    var six   = DiscordEmoji.FromName(ctx.Client, ":six:");
                    var seven = DiscordEmoji.FromName(ctx.Client, ":seven:");
                    var eight = DiscordEmoji.FromName(ctx.Client, ":eight:");
                    var nine  = DiscordEmoji.FromName(ctx.Client, ":nine:");
                    var ten   = DiscordEmoji.FromName(ctx.Client, ":keycap_ten:");
                    try
                    {
                        var reSelect = await interactivity.WaitForMessageReactionAsync(xe => (xe == one || xe == two || xe == three || xe == four || xe == five || xe == six || xe == seven || xe == eight || xe == nine || xe == ten), init, ctx.Message.Author, TimeSpan.FromSeconds(30));

                        if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":one:"))
                        {
                            lyse = 0;
                        }
                        else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":two:"))
                        {
                            lyse = 1;
                        }
                        else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":three:"))
                        {
                            lyse = 2;
                        }
                        else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":four:"))
                        {
                            lyse = 3;
                        }
                        else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":five:"))
                        {
                            lyse = 4;
                        }
                        else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":six:"))
                        {
                            lyse = 5;
                        }
                        else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":seven:"))
                        {
                            lyse = 6;
                        }
                        else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":eight:"))
                        {
                            lyse = 7;
                        }
                        else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":nine:"))
                        {
                            lyse = 8;
                        }
                        else if (reSelect.Emoji == DiscordEmoji.FromName(ctx.Client, ":keycap_ten:"))
                        {
                            lyse = 9;
                        }
                    }
                    catch
                    {
                        return;
                    }
                    await init.DeleteAllReactionsAsync();

                    await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":pushpin:"));

                    if (myresponse.items[select].lyrics.Count != 0)
                    {
                        await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":page_facing_up:"));
                    }
                    if (myresponse.items[select].pvs.Count != 0)
                    {
                        await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":movie_camera:"));

                        await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":arrow_double_down:"));
                    }
                    if (dresponse.Count != 0)
                    {
                        await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":revolving_hearts:"));
                    }
                    await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":x:"));
                }
                if (myresponse.items[select].lyrics[lyse].translationType.Length != 0)
                {
                    emim.AddField("Language", myresponse.items[select].lyrics[lyse].translationType, true);
                }
                if (myresponse.items[select].lyrics[lyse].source.Length != 0)
                {
                    emim.AddField("Source", myresponse.items[select].lyrics[lyse].source, true);
                }
                if (myresponse.items[select].lyrics[lyse].translationType.Length != 0)
                {
                    emim.AddField("Type", myresponse.items[select].lyrics[lyse].translationType, true);
                }
                if (myresponse.items[select].lyrics[lyse].url.Length != 0)
                {
                    emim.AddField("Link", myresponse.items[select].lyrics[lyse].url, true);
                }
                else
                {
                    emim.AddField("Link", $"https://vocadb.net/S/{myresponse.items[select].id}", true);
                }
                if (myresponse.items[select].lyrics[lyse].value.Length > 2000)
                {
                    emim.WithDescription("Lyrics too long, look at the link uwu");
                }
                else
                {
                    emim.WithDescription(myresponse.items[select].lyrics[lyse].value);
                }

                var end = emim.Build();

                await init.ModifyAsync(null, embed : end);
            }
            catch
            {
                await ctx.RespondAsync("Error lmao report this to Speyd3r#3939 tell him shit in the lyrics thing broke");
            }
        }
        private void ProcessQueue()
        {
            _logger.Trace($"SubscriptionProcessor::ProcessQueue");

            new Thread(async() =>
            {
                while (true)
                {
                    if (_queue.Count == 0)
                    {
                        Thread.Sleep(50);
                        continue;
                    }

                    if (_queue.Count > Strings.MaxQueueCountWarning)
                    {
                        _logger.Warn($"Subscription queue is {_queue.Count:N0} items long.");
                    }

                    var item = _queue.Dequeue();
                    if (item == null || item?.Subscription == null || item?.Member == null || item?.Embed == null)
                    {
                        continue;
                    }

                    // Check if user is receiving messages too fast.
                    var maxNotificationsPerMinute = _whConfig.MaxNotificationsPerMinute;
                    if (item.Subscription.Limiter.IsLimited(maxNotificationsPerMinute))
                    {
                        _logger.Warn($"{item.Member.Username} notifications rate limited, waiting {(60 - item.Subscription.Limiter.TimeLeft.TotalSeconds)} seconds...", item.Subscription.Limiter.TimeLeft.TotalSeconds.ToString("N0"));
                        // Send ratelimited notification to user if not already sent to adjust subscription settings to more reasonable settings.
                        if (!item.Subscription.RateLimitNotificationSent)
                        {
                            if (!_servers.ContainsKey(item.Subscription.GuildId))
                            {
                                continue;
                            }

                            var server       = _servers[item.Subscription.GuildId].Guilds[item.Subscription.GuildId];
                            var emoji        = DiscordEmoji.FromName(_servers.FirstOrDefault().Value, ":no_entry:");
                            var guildIconUrl = _servers.ContainsKey(item.Subscription.GuildId) ? _servers[item.Subscription.GuildId].Guilds[item.Subscription.GuildId]?.IconUrl : string.Empty;
                            // TODO: Localize
                            var rateLimitMessage = $"{emoji} Your notification subscriptions have exceeded {maxNotificationsPerMinute:N0}) per minute and are now being rate limited." +
                                                   $"Please adjust your subscriptions to receive a maximum of {maxNotificationsPerMinute:N0} notifications within a {NotificationLimiter.ThresholdTimeout} second time span.";
                            var eb = new DiscordEmbedBuilder
                            {
                                Title       = "Rate Limited",
                                Description = rateLimitMessage,
                                Color       = DiscordColor.Red,
                                Footer      = new DiscordEmbedBuilder.EmbedFooter
                                {
                                    Text    = $"{server?.Name} | {DateTime.Now}",
                                    IconUrl = server?.IconUrl
                                }
                            };

                            await _servers[item.Subscription.GuildId].SendDirectMessage(item.Member, string.Empty, eb.Build());
                            item.Subscription.RateLimitNotificationSent = true;
                            item.Subscription.Enabled = false;
                            if (!item.Subscription.Update())
                            {
                                _logger.Error($"Failed to disable {item.Subscription.UserId}'s subscriptions");
                            }
                        }
                        continue;
                    }

                    // Ratelimit is up, allow for ratelimiting again
                    item.Subscription.RateLimitNotificationSent = false;

                    if (!_servers.ContainsKey(item.Subscription.GuildId))
                    {
                        _logger.Error($"User subscription for guild that's not configured. UserId={item.Subscription.UserId} GuildId={item.Subscription.GuildId}");
                        continue;
                    }

                    // Send text message notification to user if a phone number is set
                    if (!string.IsNullOrEmpty(item.Subscription.PhoneNumber))
                    {
                        // Check if user is in the allowed text message list or server owner
                        if (_whConfig.Twilio.UserIds.Contains(item.Member.Id) ||
                            _whConfig.Servers[item.Subscription.GuildId].OwnerId == item.Member.Id)
                        {
                            // Send text message (max 160 characters)
                            if (item.Pokemon != null && IsUltraRare(_whConfig.Twilio, item.Pokemon))
                            {
                                var result = Utils.SendSmsMessage(StripEmbed(item), _whConfig.Twilio, item.Subscription.PhoneNumber);
                                if (!result)
                                {
                                    _logger.Error($"Failed to send text message to phone number '{item.Subscription.PhoneNumber}' for user {item.Subscription.UserId}");
                                }
                            }
                        }
                    }

                    // Send direct message notification to user
                    var client = _servers[item.Subscription.GuildId];
                    await client.SendDirectMessage(item.Member, item.Embed);
                    _logger.Info($"[WEBHOOK] Notified user {item.Member.Username} of {item.Description}.");
                    Thread.Sleep(10);
                }
            })
            {
                IsBackground = true
            }.Start();
        }
Exemple #24
0
        public async Task Support(CommandContext ctx)
        {
            if (SupportBlacklistEntry.IsBlacklisted(ctx.User.Id))
            {
                await ctx.RespondAsync("Создание тикетов заблокировано. Свяжитесь с администрацией для выяснения");

                return;
            }

            DmMessageListener.DmHandled.Add(ctx.User);

            try
            {
                var guild = await ctx.Client.GetGuildAsync(Bot.BotSettings.Guild);


                //Создание эмбеда тикета и заполнение по шаблону
                var ticketEmbed = new DiscordEmbedBuilder
                {
                    Title       = "Sea of Thieves RU | Создание тикета",
                    Description = "Выберите категорию вашего запроса через реакцию‎\n‎",
                    Color       = new DiscordColor("#e67e22")
                };

                ticketEmbed.AddField($"{SupportEmoji[SupportType.Admin]} {SupportNames[SupportType.Admin]}", "Связь с администрацией, используйте только для **ВАЖНЫХ** вопросов", true);
                ticketEmbed.AddField($"{SupportEmoji[SupportType.Moderator]} {SupportNames[SupportType.Moderator]}", "Вопросы по поводу модерации, нарушений и так далее. (Отвечают модераторы и администраторы)", true);
                ticketEmbed.AddField($"{SupportEmoji[SupportType.Developer]} {SupportNames[SupportType.Developer]}", "По вопросам бота, техническим вопросам, помощь с командами и их ошибками.", true);
                ticketEmbed.AddField($"{SupportEmoji[SupportType.Donate]} {SupportNames[SupportType.Donate]}", "По вопросам рекламы и при проблемах с донатами.", true);
                ticketEmbed.AddField($"{SupportEmoji[SupportType.FleetCaptain]} {SupportNames[SupportType.FleetCaptain]}", "По вопросам рейдов и нарушений в рейдах. (Ошибки при выдаче роли -> к `Разработчикам`)", true);
                ticketEmbed.AddField($"{SupportEmoji[SupportType.Events]} {SupportNames[SupportType.Events]}", "По вопросам ивентов на сервере. Как игровых так и внутри сервера.", true);

                ticketEmbed.WithFooter("‎\n" +
                                       "При злоупотреблении системой тикетов вы будете заблокированы.\n" +
                                       "Дождитесь загрузки всех вариантов ответа. У вас есть минута на выбор варианта");

                var ticketMessage = await ctx.RespondAsync(embed : ticketEmbed.Build());

                var interactivity = ctx.Client.GetInteractivity();

                //Создаем предложенные реакции.
                foreach (var emoji in SupportEmoji.Values)
                {
                    await ticketMessage.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, emoji));

                    await Task.Delay(400);
                }

                //Шаблон закрытого тикета
                var errorEmbed = new DiscordEmbedBuilder()
                {
                    Title       = "Sea of Thieves RU | Создание тикета закрыто",
                    Description = "Произошла ошибка при создании тикета.",
                    Color       = new DiscordColor("#e74c3c"),
                };
                errorEmbed.WithThumbnail(guild.IconUrl);
                errorEmbed.WithTimestamp(DateTime.Now);

                //Ждем одну из предложенных реакций. (Минута времени)
                var em = await interactivity.WaitForReactionAsync(x => SupportEmoji.Values.Contains(x.Emoji.GetDiscordName()), ctx.User, TimeSpan.FromSeconds(60));

                if (!em.TimedOut)
                {
                    new Task(async() =>
                    {
                        foreach (var emoji in SupportEmoji.Values)
                        {
                            await ticketMessage.DeleteOwnReactionAsync(DiscordEmoji.FromName(ctx.Client, emoji));
                            await Task.Delay(400);
                        }
                    }).Start();

                    var selectedCategory = SupportEmoji.FirstOrDefault(x => x.Value == em.Result.Emoji.GetDiscordName()).Key;

                    //Успешное продолжение создания тикета
                    //Запрос описания проблемы
                    ticketEmbed = new DiscordEmbedBuilder
                    {
                        Title       = "Sea of Thieves RU | Ожидание вопроса",
                        Description = "Опишите ваш вопрос коротким сообщением.\n‎",
                        Color       = new DiscordColor("#e67e22")
                    };
                    ticketEmbed.WithThumbnail(guild.IconUrl);

                    ticketEmbed.AddField("Выбранная категория", $"{SupportEmoji[selectedCategory]} {SupportNames[selectedCategory]}", true);

                    ticketEmbed.WithFooter("‎\nУ вас есть 5 минут для ввода вопроса.");

                    await ticketMessage.ModifyAsync(embed : ticketEmbed.Build());

                    var emsg = await interactivity.WaitForMessageAsync(x => x.Author.Id == ctx.User.Id && !x.Content.StartsWith(Bot.BotSettings.Prefix), TimeSpan.FromMinutes(5));

                    if (!emsg.TimedOut)
                    {
                        //Запрос подтверждения тикета.
                        ticketEmbed = new DiscordEmbedBuilder(ticketEmbed)
                        {
                            Title       = "Sea of Thieves RU | Подтверждение тикета",
                            Description = "Подтвердите ваш тикет для отправки. \n" +
                                          "`✅ отравить` `❌ отменить` \n‎",
                            Color = new DiscordColor("#e67e22")
                        };

                        ticketEmbed.AddField("Вопрос", emsg.Result.Content, true);

                        ticketEmbed.WithFooter("‎\nДождитесь загрузки всех вариантов ответа. У вас есть минута на выбор варианта");

                        await ticketMessage.ModifyAsync(embed : ticketEmbed.Build());

                        //Реакции подтверждения
                        var yesEmoji = DiscordEmoji.FromName(ctx.Client, ":white_check_mark:");
                        var noEmoji  = DiscordEmoji.FromName(ctx.Client, ":x:");

                        await ticketMessage.CreateReactionAsync(yesEmoji);

                        await Task.Delay(400);

                        await ticketMessage.CreateReactionAsync(noEmoji);

                        //Ждем ответа на подтверждение
                        em = await interactivity.WaitForReactionAsync(x => x.Emoji == yesEmoji || x.Emoji == noEmoji, ctx.User, TimeSpan.FromSeconds(60));

                        if (!em.TimedOut)
                        {
                            await ticketMessage.DeleteOwnReactionAsync(yesEmoji);

                            await Task.Delay(400);

                            await ticketMessage.DeleteOwnReactionAsync(noEmoji);

                            if (em.Result.Emoji == yesEmoji)
                            {
                                //Создание канала для ответа
                                var supportChannel = await guild.CreateChannelAsync($"{DiscordEmoji.FromName(ctx.Client, SupportEmoji[selectedCategory])} {ctx.User.Username}", ChannelType.Text,
                                                                                    guild.GetChannel(Bot.BotSettings.SupportCategory));

                                //Выдача прав на канал
                                await supportChannel.AddOverwriteAsync(await guild.GetMemberAsync(ctx.User.Id), Permissions.AccessChannels);

                                switch (selectedCategory)
                                {
                                case SupportType.Admin:
                                case SupportType.Developer:
                                case SupportType.Donate:
                                    //Do nothing
                                    break;

                                case SupportType.Moderator:
                                case SupportType.Events:
                                    await supportChannel.AddOverwriteAsync(guild.GetRole(Bot.BotSettings.ModeratorsRole), Permissions.AccessChannels);

                                    break;

                                case SupportType.FleetCaptain:
                                    await supportChannel.AddOverwriteAsync(guild.GetRole(Bot.BotSettings.FleetCaptainRole), Permissions.AccessChannels);

                                    break;
                                }

                                //Сохраняем в базу данных
                                var ticketData = TicketSQL.Create(supportChannel.Id, ctx.User.Id, ctx.Channel.Id, ticketMessage.Id,
                                                                  emsg.Result.Content, DateTime.Now, SupportNames[selectedCategory]);

                                //Обновляем тикет в лс
                                ticketEmbed = new DiscordEmbedBuilder(ticketEmbed)
                                {
                                    Description = "Тикет был создан.\n‎",
                                    Color       = new DiscordColor("#f1c40f")
                                };
                                ticketEmbed.WithFooter($"‎\nID: {ticketData.ChannelId}");
                                ticketEmbed.WithTimestamp(DateTime.Now);

                                await ticketMessage.ModifyAsync(embed : ticketEmbed.Build());

                                await ctx.RespondAsync($"Ваш запрос был отравлен. Ждите ответ в {supportChannel.Mention}.");

                                //Обновляем тикет для отправки в канал
                                ticketEmbed = new DiscordEmbedBuilder(ticketEmbed)
                                {
                                    Title       = "Sea of Thieves RU | Тикет",
                                    Description = "Ожидайте ответ на ваш запрос.\n‎"
                                }
                                .WithAuthor(ctx.User.ToString(), iconUrl: ctx.User.AvatarUrl)
                                .WithFooter($"‎\nID: {ticketData.ChannelId}");

                                var message = await supportChannel.SendMessageAsync($"Тикет от пользователя: {ctx.User.Mention}", embed : ticketEmbed.Build());

                                ticketData.MessageId = message.Id;
                            }
                            else
                            {
                                ticketEmbed = new DiscordEmbedBuilder(errorEmbed)
                                              .WithDescription("Тикет был отменён.");

                                await ticketMessage.ModifyAsync(embed : ticketEmbed.Build());
                            }
                        }
                        else
                        {
                            await ticketMessage.DeleteOwnReactionAsync(yesEmoji);

                            await Task.Delay(400);

                            await ticketMessage.DeleteOwnReactionAsync(noEmoji);

                            ticketEmbed = new DiscordEmbedBuilder(errorEmbed)
                                          .WithDescription("Время выбора истекло.");

                            await ticketMessage.ModifyAsync(embed : ticketEmbed.Build());
                        }
                    }
                    else
                    {
                        ticketEmbed = new DiscordEmbedBuilder(errorEmbed)
                                      .WithDescription("Время ввода вопроса истекло.");

                        await ticketMessage.ModifyAsync(embed : ticketEmbed.Build());
                    }
                }
                else
                {
                    new Task(async() =>
                    {
                        foreach (var emoji in SupportEmoji.Values)
                        {
                            await ticketMessage.DeleteOwnReactionAsync(DiscordEmoji.FromName(ctx.Client, emoji));
                            await Task.Delay(400);
                        }
                    }).Start();
                    ticketEmbed = new DiscordEmbedBuilder(errorEmbed)
                                  .WithDescription("Время выбора категории тикета истекло.");

                    await ticketMessage.ModifyAsync(embed : ticketEmbed.Build());
                }
                DmMessageListener.DmHandled.Remove(ctx.User);
            }
            catch (Exception ex)
            {
                DmMessageListener.DmHandled.Remove(ctx.User);
                throw ex;
            }
        }
Exemple #25
0
        private async Task ProfanityFilterRemove(DiscordClient dClient, MessageReactionAddEventArgs args)
        {
            if (args.User.Id == dClient.CurrentUser.Id || (args.Channel?.Id != SBGChannels.Bloonside && !args.Emoji.Equals(DiscordEmoji.FromName(this.dClient, ":wastebasket:"))))
            {
                return;
            }

            DiscordChannel bloonside = await this.dClient.GetChannelAsync(SBGChannels.Bloonside);

            DiscordMessage foulEmbed = await bloonside.GetMessageAsync(args.Message.Id);

            if (args.Message.Channel.Id == SBGChannels.Bloonside && foulEmbed.Author.Id == dClient.CurrentUser.Id && foulEmbed.Embeds.Count > 0 && foulEmbed.Embeds[0].Title.Contains("Censor"))
            {
                await foulEmbed.DeleteAsync();
            }

            return;
        }
Exemple #26
0
        public async Task Adicionar(ExecucaoDeAudio execucaoDeAudio)
        {
            if (StatusDaFila == EnumeradorDeStatusDaFila.Parada)
            {
                StatusDaFila = EnumeradorDeStatusDaFila.Executando;
                try
                {
                    await AoExecutarMusica?.Invoke(execucaoDeAudio);
                }
                catch
                {
                    await execucaoDeAudio.CommandContext.Message.DeleteOwnReactionAsync(DiscordEmoji.FromName(execucaoDeAudio.CommandContext.Client, ":arrows_counterclockwise:"));

                    await execucaoDeAudio.CommandContext.Message.CreateReactionAsync(DiscordEmoji.FromName(execucaoDeAudio.CommandContext.Client, ":thumbsdown:"));

                    Fila.Clear();
                    StatusDaFila = EnumeradorDeStatusDaFila.Parada;
                    await execucaoDeAudio.CommandContext.Message.RespondAsync(content : "Erro ao executar o comando, a fila de audios foi limpa");
                }
            }
            else
            {
                Fila.Enqueue(execucaoDeAudio);
            }
        }
 public static async Task React(this MessageCreateEventArgs e, DiscordClient client, string name)
 {
     e.Message.CreateReactionAsync(DiscordEmoji.FromName(client, name));
 }
        public async Task AdicionaCategoriaAsync(CommandContext ctx, DiscordChannel canalReactRole = null, [RemainingText] string nomeDaCategoriaReactRole = null)
        {
            await ctx.TriggerTypingAsync();

            new Thread(async() =>
            {
                try
                {
                    await ctx.TriggerTypingAsync();

                    DiscordEmbedBuilder embed = new DiscordEmbedBuilder();

                    if (canalReactRole == null || string.IsNullOrWhiteSpace(nomeDaCategoriaReactRole))
                    {
                        embed.WithColor(Program.Bot.Utilities.HelpCommandsColor())
                        .WithAuthor("Como executar este comando:", null, Values.infoLogo)
                        .AddField("PC/Mobile", $"{ctx.Prefix}rr cat.add Canal[Id] Nome[Jogos: FPS]")
                        .WithFooter($"Comando requisitado pelo: {Program.Bot.Utilities.DiscordNick(ctx.Member)}", iconUrl: ctx.Member.AvatarUrl)
                        .WithTimestamp(DateTime.Now);

                        await ctx.RespondAsync(embed: embed.Build());
                        return;
                    }

                    IMongoDatabase local             = Program.Bot.LocalDB;
                    IMongoCollection <Reacts> reacts = local.GetCollection <Reacts>(Values.Mongo.reacts);
                    IMongoCollection <Jogos> jogos   = local.GetCollection <Jogos>(Values.Mongo.jogos);

                    InteractivityExtension interactivity = ctx.Client.GetInteractivity();

                    embed.WithAuthor("Deseja colocar como descrição da categoria a frase padrão: \"Clique na reação para obter o cargo. Remova a reação para tirar o cargo.\" ou " +
                                     "você deseja digitar a frase?", null, Values.logoUBGE)
                    .WithColor(Program.Bot.Utilities.RandomColorEmbed())
                    .WithDescription("Aperte: :white_check_mark: para selecionar a frase padrão.\n" +
                                     "Aperte: :x: para você digitar a frase da categoria.")
                    .WithThumbnailUrl(ctx.Member.AvatarUrl);

                    DiscordMessage MsgEmbed = await ctx.RespondAsync(embed: embed.Build());
                    await MsgEmbed.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":white_check_mark:"));
                    await MsgEmbed.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":x:"));

                    DiscordEmoji Reacao = (await interactivity.WaitForReactionAsync(MsgEmbed, ctx.User, TimeSpan.FromMinutes(30))).Result?.Emoji;

                    if (Reacao == DiscordEmoji.FromName(ctx.Client, ":white_check_mark:"))
                    {
                        await MsgEmbed.DeleteAsync();

                        Program.Bot.Utilities.ClearEmbed(embed);

                        embed.WithAuthor(nomeDaCategoriaReactRole, null, Values.logoUBGE)
                        .WithColor(new DiscordColor(0x32363c))
                        .WithDescription("Clique na reação para obter o cargo. Remova a reação para tirar o cargo.\n\n");

                        //string CaminhoImg = Directory.GetCurrentDirectory() + @"\ImagemCategorias.png";
                        //await SelecioneSeusJogos.SendFileAsync(CaminhoImg);

                        DiscordMessage msgEmbedReactRole = await canalReactRole.SendMessageAsync(embed: embed.Build());

                        await reacts.InsertOneAsync(new Reacts
                        {
                            categoria    = nomeDaCategoriaReactRole,
                            idDaMensagem = msgEmbedReactRole.Id,
                            idDoCanal    = canalReactRole.Id,
                            servidor     = ctx.Guild.Id,
                        });

                        await jogos.InsertOneAsync(new Jogos
                        {
                            nomeDaCategoria = nomeDaCategoriaReactRole,
                            idDoEmoji       = 0,
                            idDoCargo       = 0
                        });

                        Program.Bot.Utilities.ClearEmbed(embed);

                        embed.WithAuthor("Categoria adicionada!", null, Values.logoUBGE)
                        .WithColor(Program.Bot.Utilities.RandomColorEmbed())
                        .WithDescription($"A categoria: \"{nomeDaCategoriaReactRole}\" foi adicionada com sucesso!\n\n" +
                                         $"Para ir até ela, {Formatter.MaskedUrl("clique aqui", msgEmbedReactRole.JumpLink, "clique aqui")}.")
                        .WithThumbnailUrl(ctx.Member.AvatarUrl)
                        .WithTimestamp(DateTime.Now)
                        .WithFooter($"Comando requisitado pelo: {Program.Bot.Utilities.DiscordNick(ctx.Member)}", iconUrl: ctx.Member.AvatarUrl);

                        await ctx.RespondAsync(embed: embed.Build());
                    }
                    else if (Reacao == DiscordEmoji.FromName(ctx.Client, ":x:"))
                    {
                        await MsgEmbed.DeleteAsync();

                        Program.Bot.Utilities.ClearEmbed(embed);

                        embed.WithAuthor("Digite a frase que irá ficar na descrição da categoria.", null, Values.logoUBGE)
                        .WithColor(Program.Bot.Utilities.RandomColorEmbed());

                        DiscordMessage mensagemFraseEmbedReactRole = await ctx.RespondAsync(embed: embed.Build());
                        string Input = await Program.Bot.Utilities.GetAnswer(interactivity, ctx);

                        Program.Bot.Utilities.ClearEmbed(embed);

                        embed.WithAuthor(nomeDaCategoriaReactRole, null, Values.logoUBGE)
                        .WithColor(new DiscordColor(0x32363c))
                        .WithDescription($"{Input}\n\n");

                        //string CaminhoImg = Directory.GetCurrentDirectory() + @"\ImagemCategorias.png";
                        //await SelecioneSeusJogos.SendFileAsync(CaminhoImg);

                        DiscordMessage msgEmbedReactRole = await canalReactRole.SendMessageAsync(embed: embed.Build());

                        await reacts.InsertOneAsync(new Reacts
                        {
                            categoria    = nomeDaCategoriaReactRole,
                            idDaMensagem = msgEmbedReactRole.Id,
                            idDoCanal    = canalReactRole.Id,
                            servidor     = ctx.Guild.Id
                        });

                        Program.Bot.Utilities.ClearEmbed(embed);

                        embed.WithAuthor("Categoria adicionada!", null, Values.logoUBGE)
                        .WithColor(Program.Bot.Utilities.RandomColorEmbed())
                        .WithDescription($"A categoria: \"{nomeDaCategoriaReactRole}\" foi adicionada com sucesso!\n\n" +
                                         $"Para ir até ela, {Formatter.MaskedUrl("clique aqui", msgEmbedReactRole.JumpLink, "clique aqui")}.")
                        .WithThumbnailUrl(ctx.Member.AvatarUrl)
                        .WithTimestamp(DateTime.Now)
                        .WithFooter($"Comando requisitado pelo: {Program.Bot.Utilities.DiscordNick(ctx.Member)}", iconUrl: ctx.Member.AvatarUrl);

                        await ctx.RespondAsync(embed: embed.Build());
                    }
                    else
                    {
                        return;
                    }
                }
                catch (UnauthorizedException)
                {
                    await ctx.RespondAsync($"{ctx.Member.Mention}, não tenho autorização para enviar a mensagem do ReactRole nesse canal, por favor ative-a!");
                }
                catch (Exception exception)
                {
                    await Program.Bot.Logger.Error(Log.TypeError.Commands, exception);
                }
            }).Start();
        }
Exemple #29
0
        public async Task GetListOfRooms(CommandContext ctx)
        {
            List <ulong> roomsInThisServer = new List <ulong>();

            foreach (var room in BotHandler.openRooms)
            {
                if (room.Value.guild.Id == ctx.Guild.Id)
                {
                    roomsInThisServer.Add(room.Key);
                }
            }

            if (roomsInThisServer.Count() == 0)
            {
                await ctx.RespondAsync(new DiscordEmbedBuilder {
                    Title       = "There Are No Rooms In This Server",
                    Description = "You can create a room using \"room create\"",
                    Color       = DiscordColor.Azure
                }).ConfigureAwait(false);

                return;
            }

            var interactivity = ctx.Client.GetInteractivity();

            List <DSharpPlus.Interactivity.Page> allMenuPages = new List <DSharpPlus.Interactivity.Page>();

            DSharpPlus.Interactivity.PaginationEmojis paginationEmojis = new DSharpPlus.Interactivity.PaginationEmojis
            {
                SkipLeft  = DiscordEmoji.FromName(ctx.Client, ":rewind:"),
                Left      = DiscordEmoji.FromName(ctx.Client, ":arrow_left:"),
                Stop      = DiscordEmoji.FromName(ctx.Client, ":no_entry_sign:"),
                Right     = DiscordEmoji.FromName(ctx.Client, ":arrow_right:"),
                SkipRight = DiscordEmoji.FromName(ctx.Client, ":fast_forward:")
            };

            int roomsPerPage = Math.Min(10, roomsInThisServer.Count());
            int totalPages   = roomsInThisServer.Count() / roomsPerPage;

            if (roomsInThisServer.Count() % roomsPerPage != 0)
            {
                totalPages++;
            }

            for (int page = 1; page <= totalPages; page++)
            {
                string description = $"Page {page}/{totalPages}\n";

                for (int i = (page - 1) * roomsPerPage; i < page * roomsPerPage && i < roomsInThisServer.Count(); i++)
                {
                    description += $"\n{i + 1}) {BotHandler.openRooms[roomsInThisServer[i]].roomName} ({(await ctx.Client.GetUserAsync(roomsInThisServer[i])).Username})";
                }

                DSharpPlus.Interactivity.Page menuPage = new DSharpPlus.Interactivity.Page(embed: new DiscordEmbedBuilder
                {
                    Title       = "List of Rooms",
                    Description = description,
                    Color       = DiscordColor.Azure,
                    Footer      = new DiscordEmbedBuilder.EmbedFooter {
                        Text = $"Total Rooms: {roomsInThisServer.Count()}"
                    }
                });

                allMenuPages.Add(menuPage);
            }

            await interactivity.SendPaginatedMessageAsync(ctx.Channel, ctx.User, allMenuPages, paginationEmojis, DSharpPlus.Interactivity.Enums.PaginationBehaviour.WrapAround, timeoutoverride : TimeSpan.FromMinutes(3));
        }
Exemple #30
0
        public async Task GetDbStatus(CommandContext ctx)
        {
            await ctx.TriggerTypingAsync();

            var userId = ctx.User?.Id ?? 0;

            Log.Info($"Requesting {nameof(GetDbStatus)} by {userId}...");
            if (userId != _coder)
            {
                var emoji = DiscordEmoji.FromName(ctx.Client, ":no_entry:");
                var embed = new DiscordEmbedBuilder
                {
                    Title       = "Access denied",
                    Description = $"{emoji} You may be a *coder*, but you are not **The Coder**!",
                    Color       = DiscordColor.Red
                };

                await ctx.RespondAsync("", embed : embed);

                return;
            }

            try
            {
                var provider = new DbProvider(_connectionString);
                var s        = provider.GetDataDiagnostic();

                var sb = new StringBuilder();

                sb.AppendLine($"Scheduled Players Per Hour: {s.ScheduledPlayersPerHour:N0}");
                sb.AppendLine($"Last Hour Players: {s.AvgPlayersPerHourLastHour:N0}");
                sb.AppendLine($"Avg Players Per Hour Last 2 Hours: {s.AvgPlayersPerHourLast2Hours:N0}");
                sb.AppendLine($"Avg Players Per Hour Last 6 Hours: {s.AvgPlayersPerHourLast6Hours:N0}");
                sb.AppendLine($"Avg Players Per Hour Last Day: {s.AvgPlayersPerHourLastDay:N0}");
                sb.AppendLine();
                sb.AppendLine(
                    $"Delay on the last 48h/72h/96h: {s.Last48HDelay:N1}; {s.Last72HDelay:N1}; {s.Last96HDelay:N1}");
                sb.AppendLine($"Total Players: {s.TotalPlayers:N0}; Enabled Clans: {s.TotalEnabledClans};");
                sb.AppendLine($"Players Queue Length: {s.PlayersQueueLenght}");
                sb.AppendLine($"Membership Queue Length: {s.MembershipQueueLenght}");
                sb.AppendLine($"Calculate Queue Length: {s.CalculateQueueLenght}");

                var embed = new DiscordEmbedBuilder
                {
                    Title       = "Database Status",
                    Description = sb.ToString(),
                    Color       = DiscordColor.Goldenrod,
                    Author      = new DiscordEmbedBuilder.EmbedAuthor
                    {
                        Name = "WoTClans",
                        Url  = "https://wotclans.com.br"
                    },
                    Footer = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = $"Retrieved at {s.Moment:yyyy-MM-dd HH:mm} UTC."
                    }
                };

                await ctx.RespondAsync("", embed : embed);

                Log.Debug($"{nameof(GetDbStatus)} returned ok.");
            }
            catch (Exception ex)
            {
                Log.Error($"{nameof(GetDbStatus)}", ex);
                await ctx.RespondAsync(
                    $"Sorry, {ctx.User?.Mention}. There was an error... the *Coder* will be notified of `{ex.Message}`.");
            }
        }