Пример #1
0
        public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
        {
            using (MySqlConnection c = Database.GetConnection())
            {
                // Check if the user has permission to use this command.
                if (!Config.HasPermission(command.Member, "setticket"))
                {
                    DiscordEmbed error = new DiscordEmbedBuilder
                    {
                        Color       = DiscordColor.Red,
                        Description = "You do not have permission to use this command."
                    };
                    await command.RespondAsync("", false, error);

                    command.Client.Logger.Log(LogLevel.Information, "User tried to use the setticket command but did not have permission.");
                    return;
                }

                // Check if ticket exists in the database
                if (Database.IsOpenTicket(command.Channel.Id))
                {
                    DiscordEmbed error = new DiscordEmbedBuilder
                    {
                        Color       = DiscordColor.Red,
                        Description = "This channel is already a ticket."
                    };
                    await command.RespondAsync("", false, error);

                    return;
                }

                ulong    userID;
                string[] parsedMessage = Utilities.ParseIDs(command.RawArgumentString);

                if (!parsedMessage.Any())
                {
                    userID = command.Member.Id;
                }
                else if (!ulong.TryParse(parsedMessage[0], out userID))
                {
                    DiscordEmbed error = new DiscordEmbedBuilder
                    {
                        Color       = DiscordColor.Red,
                        Description = "Invalid ID/Mention. (Could not convert to numerical)"
                    };
                    await command.RespondAsync("", false, error);

                    return;
                }

                DiscordUser user = await command.Client.GetUserAsync(userID);

                if (user == null)
                {
                    DiscordEmbed error = new DiscordEmbedBuilder
                    {
                        Color       = DiscordColor.Red,
                        Description = "Invalid ID/Mention."
                    };
                    await command.RespondAsync("", false, error);

                    return;
                }

                long         id       = Database.NewTicket(userID, 0, command.Channel.Id);
                string       ticketID = id.ToString("00000");
                DiscordEmbed message  = new DiscordEmbedBuilder
                {
                    Color       = DiscordColor.Green,
                    Description = "Channel has been designated ticket " + ticketID + "."
                };
                await command.RespondAsync("", false, message);

                // Log it if the log channel exists
                DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel);
                if (logChannel != null)
                {
                    DiscordEmbed logMessage = new DiscordEmbedBuilder
                    {
                        Color       = DiscordColor.Green,
                        Description = command.Channel.Mention + " has been designated ticket " + ticketID + " by " + command.Member.Mention + "."
                    };
                    await logChannel.SendMessageAsync("", false, logMessage);
                }
            }
        }
Пример #2
0
        public override async Task <bool> ProcessStep(DiscordClient client, DiscordChannel channel, DiscordUser user)
        {
            var embedBuilder = new DiscordEmbedBuilder
            {
                Title       = $"Please Respond Below",
                Description = $"{user.Mention}, {_content}",
            };

            embedBuilder.AddField("To Stop The Dialogue", "Use the ?cancel command");

            if (_minValue.HasValue)
            {
                embedBuilder.AddField("Min Value:", $"{_minValue.Value}");
            }
            if (_maxValue.HasValue)
            {
                embedBuilder.AddField("Max Value:", $"{_maxValue.Value}");
            }

            var interactivity = client.GetInteractivity();

            while (true)
            {
                var embed = await channel.SendMessageAsync(embed : embedBuilder).ConfigureAwait(false);

                OnMessageAdded(embed);

                var messageResult = await interactivity.WaitForMessageAsync(
                    x => x.ChannelId == channel.Id && x.Author.Id == user.Id).ConfigureAwait(false);

                OnMessageAdded(messageResult.Result);

                if (messageResult.Result.Content.Equals("?cancel", StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }

                if (!int.TryParse(messageResult.Result.Content, out int inputValue))
                {
                    await TryAgain(channel, $"Your input is not an integer").ConfigureAwait(false);

                    continue;
                }

                if (_minValue.HasValue)
                {
                    if (inputValue < _minValue.Value)
                    {
                        await TryAgain(channel, $"Your input value: {inputValue} is smaller than: {_minValue}").ConfigureAwait(false);

                        continue;
                    }
                }
                if (_maxValue.HasValue)
                {
                    if (inputValue > _maxValue.Value)
                    {
                        await TryAgain(channel, $"Your input value {inputValue} is larger than {_maxValue}").ConfigureAwait(false);

                        continue;
                    }
                }

                OnValidResult(inputValue);

                return(false);
            }
        }
Пример #3
0
 public async Task SudoAsync(CommandContext ctx, DiscordUser user, [RemainingText] string content)
 {
     var cmd  = ctx.CommandsNext.FindCommand(content.AsMemory(), out var args);
     var fctx = ctx.CommandsNext.CreateFakeContext(user, ctx.Channel, content, ctx.Prefix, cmd, args);
     await ctx.CommandsNext.ExecuteCommandAsync(fctx).ConfigureAwait(false);
 }
Пример #4
0
 public static async Task <bool> GetDelayDeletingAsync(this DiscordUser user) => await user.GetAsync <bool>("delayDelete");
Пример #5
0
 public async Task InsertUserAsync(CommandContext context, DiscordUser user, byte level, [RemainingText] string reason)
 {
     await InsertUserAsync(context, user, level, reason, false);
 }
 public Task By(CommandContext ctx, DiscordUser moderator, [Description("Optional number of items to show. Default is 10")] int number = 10)
 => By(ctx, moderator.Id, number);
Пример #7
0
        public static async Task <DiscordMessage> SendDirectMessage(this DiscordClient client, DiscordUser user, string message, DiscordEmbed embed)
        {
            try
            {
                var dm = await client.CreateDmAsync(user);

                if (dm != null)
                {
                    var msg = await dm.SendMessageAsync(message, false, embed);

                    return(msg);
                }
            }
            catch (Exception)
            {
                //_logger.Error(ex);
                _logger.Error($"Failed to send DM to user {user.Username}.");
            }

            return(null);
        }
Пример #8
0
 public SlaveReport(DateTime datetime, DiscordUser user, int edges, int time, string outcome) : this(datetime, user, edges, time, (Outcome)Enum.Parse(typeof(Outcome), outcome))
 {
 }
Пример #9
0
 public async Task InvokeFromEmoji(DiscordUser user, DiscordMessageState question)
 {
     await OnAnswer(new AnswerArgs(user, question));
 }
Пример #10
0
 public Task ExecuteGroupAsync(CommandContext ctx,
                               [Description("Users to block.")] DiscordUser user,
                               [RemainingText, Description("Reason (max 60 chars).")] string reason)
 => this.AddAsync(ctx, reason, user);
Пример #11
0
        static async Task MainAsync(string[]    args)
        {
            DiscordUser    complimentedCutie   = null;
            int            complimentIteration = 0;
            Random         rnd    = new Random();
            Stream         imgyus = new MemoryStream(Properties.Resources._68964a1);
            DiscordChannel currentvoicechannel = null;

            Console.WriteLine("Starting server...");
            discord = new DiscordClient(new DiscordConfiguration
            {
                Token     = "Secret Token",
                TokenType = TokenType.Bot,
            }
                                        );
            voice = discord.UseVoiceNext();
            Console.WriteLine("Initilizing Client");
            discord.Ready += async e =>
            {
                Console.WriteLine("Server Ready!");
                await discord.UpdateStatusAsync(new DiscordGame("with herself~"));
            };
            voice.Client.MessageCreated += async e =>
            {
                if (e.Message.Content.StartsWith("-"))
                {
                    String messagesent = e.Message.Content.TrimStart('-');
                    String commandsent;
                    if (messagesent.Contains(' '))
                    {
                        commandsent = messagesent.Remove(messagesent.IndexOf(' ')).Trim().ToLower();
                    }
                    else
                    {
                        commandsent = messagesent.Trim().ToLower();
                    }
                    Console.WriteLine();
                    Console.WriteLine("------------------------");
                    Console.WriteLine("Command Information:");
                    Console.WriteLine(" Sender = " + e.Author.Username);
                    Console.WriteLine(" Message = " + e.Message.Content);
                    Console.WriteLine(" Command sent = " + commandsent);
                    switch (commandsent)
                    {
                    case "compliment":
                        Console.WriteLine(" Name = Compliment");
                        switch (e.Author.Username)
                        {
                        case "SpaceCadetKitty":
                            await e.Message.RespondAsync("<@" + e.Author.Id + "> Who's a cute kitty?");

                            break;

                        case "WatermelonFennec":
                            await e.Message.RespondAsync("<@" + e.Author.Id + "> Who's a cute fennec?");

                            break;

                        case "KingMuskDeer":
                            await e.Message.RespondAsync("<@" + e.Author.Id + "> Who's a cute frumpy little deer?");

                            break;

                        case "wizard":
                            await e.Message.RespondAsync("<@" + e.Author.Id + "> Who's a cutie pie?");

                            break;

                        default:
                            await e.Message.RespondAsync("<@" + e.Author.Id + "> I'm sure you have a cute personality!");

                            break;
                        }
                        complimentedCutie   = e.Author;
                        complimentIteration = 3;
                        break;

                    case "lewd":
                        Console.WriteLine(" Name = lewd");
                        switch (e.Author.Username)
                        {
                        case "SpaceCadetKitty":
                            await e.Message.RespondAsync("*Nibbles your neck* UwU");

                            break;

                        case "WatermelonFennec":
                            await e.Message.RespondAsync("*Plays with your thingie* ^w^");

                            break;

                        case "wizard":
                            await e.Message.RespondAsync("*Licks lips* So cute!");

                            break;

                        default:
                            await e.Message.RespondAsync("UwU what's this?");

                            break;
                        }
                        break;

                    case "ping":
                        Console.WriteLine(" Name = ping");
                        await e.Message.RespondAsync($"Pong!: My ping is {discord.Ping}ms");

                        break;

                    case "blow":
                        Console.WriteLine(" Name = blow");
                        if (e.MentionedUsers.Count == 1)
                        {
                            Console.WriteLine(" Destination = " + e.MentionedUsers[0].Username);
                            if (e.MentionedUsers[0].IsBot)
                            {
                                await e.Message.RespondAsync("<@" + e.Author.Id + "> Don't be silly. You can't blow a bot!");
                            }
                            else
                            {
                                await e.Message.RespondAsync("Hear that <@" + e.MentionedUsers[0].Id + ">? <@" + e.Author.Id + "> wants to blow you!");
                            }
                        }
                        else
                        {
                            Console.WriteLine("Exception = invalid user(s)");
                        }
                        break;

                    case "cuddle":
                        List <String> discorduserslist = new List <String>();
                        Console.WriteLine(" Name = cuddle");
                        if (e.MentionedUsers.Count > 0)
                        {
                            Console.WriteLine(" Destinations:");
                            String sendingmessage = "";
                            foreach (DiscordUser usr in e.MentionedUsers)
                            {
                                if (!discorduserslist.Contains(usr.Username))
                                {
                                    Console.WriteLine("  " + usr.Username);
                                    sendingmessage += "<@" + usr.Id + ">, ";
                                    discorduserslist.Add(usr.Username);
                                }
                            }
                            sendingmessage += "<@" + e.Author.Id + "> wants to cuddle up with you!";
                            await e.Message.RespondAsync(sendingmessage);
                        }
                        else
                        {
                            Console.WriteLine("Exception = too few users");
                        }
                        List <String> cuties = new List <String>()
                        {
                            "wizard", "SpaceCadetKitty", "WatermelonFennec", "Newt_Salad"
                        };
                        if (cuties.Contains(e.Author.Username) && !(e.Author.Username.Equals("wizard") && discorduserslist.Contains("WatermelonFennec")))
                        {
                            await e.Message.RespondAsync("So cute!");
                        }
                        break;

                    case "join":
                        Console.WriteLine(" Name = join");
                        //TODO implement later
                        break;

                    case "yus":
                        Console.WriteLine(" Name = yus");
                        await e.Message.RespondWithFileAsync(imgyus, "yus.jpg");

                        break;

                    case "help":
                        Console.WriteLine(" Name = help");
                        await e.Message.RespondAsync("```css\n" +
                                                     "#The-Fennec-Bot-Commands-are\n" +
                                                     "[-compliment] The Fennec Bot will pay you a compliment!\n" +
                                                     "[-lewd] The Fennec Bot will say somthing lewd UwU\n" +
                                                     "[-ping] The Fennec Bot will tell you its ping\n" +
                                                     "[-blow @username] You blow someone, so hot!\n" +
                                                     "[-cuddle @usernames] You cuddle up with someone, or multiple people!\n" +
                                                     "[-yus] yus\n" +
                                                     "[-join] New experimental feature that will play bad songs and memes!\n" +
                                                     "[-help] The Fennec Bot will list off all the commands for you```");

                        break;

                    //TODO add elaberate help command
                    //TODO add hug command
                    //TODO add knock knock command
                    default:
                        Console.WriteLine("Exception = invalid command");
                        break;
                    }
                    Console.WriteLine("------------------------");
                }
                if (e.Message.Author.IsBot && e.Message.Content.Equals("... but you can damn well try! >:3"))
                {
                    Console.WriteLine();
                    Console.WriteLine("------------------------");
                    Console.WriteLine("CODE RED, MADELINE BOT IS BEING LEWD!!!!");
                    switch (rnd.Next(4))
                    {
                    case 0:
                        Console.WriteLine("Fire the torpedoes!");
                        await e.Message.RespondAsync("UwU");

                        break;

                    case 1:
                        Console.WriteLine("Lets get kinky!");
                        await e.Message.RespondAsync("UwU");

                        break;

                    case 2:
                        Console.WriteLine("OH F**K, OH SHIT, I DON'T KNOW WHAT TO DO!");
                        await e.Message.RespondAsync("OwO");

                        break;

                    case 3:
                        Console.WriteLine("OMG OMG SO CUTE!");
                        await e.Message.RespondAsync("OwO");

                        break;

                    default:
                        Console.WriteLine("Exception = out of bounds");
                        break;
                    }
                    Console.WriteLine("------------------------");
                }
                if (complimentedCutie != null)
                {
                    complimentIteration--;
                    if (e.Author.Equals(complimentedCutie) && e.Message.Content.ToLower().StartsWith("me"))
                    {
                        Console.WriteLine();
                        Console.WriteLine("------------------------");
                        Console.WriteLine("Complimented cutie(" + complimentedCutie.Username + ") is questioning cuteness!");
                        Console.WriteLine("Sending secondary compliment!");
                        Console.WriteLine("------------------------");
                        await e.Message.RespondAsync("<@" + complimentedCutie.Id + "> It is you! You're the cutie!");

                        complimentIteration = 0;
                    }
                    if (complimentIteration == 0)
                    {
                        complimentedCutie = null;
                    }
                }
                //TODO Later if someone tries to message the other bot and its offline, reply with "sorry this bot is offline"
            };
            await discord.ConnectAsync();

            await Task.Delay(-1);
        }
Пример #12
0
 public static string Tag(this DiscordUser user) => Tag((DiscordMember)user);
Пример #13
0
            public async Task WaifuClaimerAffinity([Remainder] IUser u = null)
            {
                if (u?.Id == Context.User.Id)
                {
                    await ReplyErrorLocalized("waifu_egomaniac").ConfigureAwait(false);

                    return;
                }
                DiscordUser oldAff     = null;
                var         sucess     = false;
                var         cooldown   = false;
                var         difference = TimeSpan.Zero;

                using (var uow = DbHandler.UnitOfWork())
                {
                    var w      = uow.Waifus.ByWaifuUserId(Context.User.Id);
                    var newAff = u == null ? null : uow.DiscordUsers.GetOrCreate(u);
                    var now    = DateTime.UtcNow;
                    if (w?.Affinity?.UserId == (long?)u?.Id)
                    {
                    }
                    else if (affinityCooldowns.AddOrUpdate(Context.User.Id,
                                                           now,
                                                           (key, old) => ((difference = now.Subtract(old)) > _affinityLimit) ? now : old) != now)
                    {
                        cooldown = true;
                    }
                    else if (w == null)
                    {
                        var thisUser = uow.DiscordUsers.GetOrCreate(Context.User);
                        uow.Waifus.Add(new WaifuInfo()
                        {
                            Affinity = newAff,
                            Waifu    = thisUser,
                            Price    = 1,
                            Claimer  = null
                        });
                        sucess = true;

                        uow._context.WaifuUpdates.Add(new WaifuUpdate()
                        {
                            User       = thisUser,
                            Old        = null,
                            New        = newAff,
                            UpdateType = WaifuUpdateType.AffinityChanged
                        });
                    }
                    else
                    {
                        if (w.Affinity != null)
                        {
                            oldAff = w.Affinity;
                        }
                        w.Affinity = newAff;
                        sucess     = true;

                        uow._context.WaifuUpdates.Add(new WaifuUpdate()
                        {
                            User       = w.Waifu,
                            Old        = oldAff,
                            New        = newAff,
                            UpdateType = WaifuUpdateType.AffinityChanged
                        });
                    }

                    await uow.CompleteAsync().ConfigureAwait(false);
                }
                if (!sucess)
                {
                    if (cooldown)
                    {
                        var remaining = _affinityLimit.Subtract(difference);
                        await ReplyErrorLocalized("waifu_affinity_cooldown",
                                                  Format.Bold(((int)remaining.TotalHours).ToString()),
                                                  Format.Bold(remaining.Minutes.ToString())).ConfigureAwait(false);
                    }
                    else
                    {
                        await ReplyErrorLocalized("waifu_affinity_already").ConfigureAwait(false);
                    }
                    return;
                }
                if (u == null)
                {
                    await ReplyConfirmLocalized("waifu_affinity_reset").ConfigureAwait(false);
                }
                else if (oldAff == null)
                {
                    await ReplyConfirmLocalized("waifu_affinity_set", Format.Bold(u.ToString())).ConfigureAwait(false);
                }
                else
                {
                    await ReplyConfirmLocalized("waifu_affinity_changed", Format.Bold(oldAff.ToString()), Format.Bold(u.ToString())).ConfigureAwait(false);
                }
            }
Пример #14
0
        public override async Task <bool> ProcessStep(
            DiscordClient client,
            DiscordChannel channel,
            DiscordUser user)
        {
            var embedBuilder = new DiscordEmbedBuilder()
            {
                Title       = "Please respond below",
                Description = $"{user.Mention}, {content}"
            };

            if (minValue.HasValue)
            {
                embedBuilder.AddField(
                    "Min value: ",
                    $"`{minValue.Value}`");
            }
            if (maxValue.HasValue)
            {
                embedBuilder.AddField(
                    "Max value: ",
                    $"`{maxValue.Value}`");
            }

            InteractivityExtension interactivity = client.GetInteractivity();

            while (true)
            {
                DiscordMessage botMessage = await channel.SendMessageAsync(
                    embed : embedBuilder.Build());

                OnMessageAdded(botMessage);

                InteractivityResult <DiscordMessage> resultUserMessage = await interactivity.WaitForMessageAsync(
                    x => x.ChannelId == channel.Id &&
                    x.Author.Id == user.Id);

                OnMessageAdded(resultUserMessage.Result);

                string messageContent = resultUserMessage.Result.Content;

                if (!int.TryParse(messageContent, out int inputValue))
                {
                    await ShowTryAgain(
                        channel,
                        $"Your input is not an integer");

                    continue;
                }
                if (minValue.HasValue &&
                    inputValue < minValue.Value)
                {
                    await ShowTryAgain(
                        channel,
                        $"Your input, `{inputValue}`, is smaller than `{minValue.Value}`");

                    continue;
                }
                if (maxValue.HasValue &&
                    inputValue > maxValue.Value)
                {
                    await ShowTryAgain(
                        channel,
                        $"Your input, `{inputValue}`, is larger than `{maxValue.Value}`");

                    continue;
                }

                OnValidResult(inputValue);

                return(false);
            }
        }
Пример #15
0
 /// <summary>
 /// Waits for a specific reaction.
 /// </summary>
 /// <param name="predicate">predicate to match.</param>
 /// <param name="user">User that made the reaction.</param>
 /// <param name="timeoutoverride">Override timeout period.</param>
 /// <returns></returns>
 public async Task <InteractivityResult <MessageReactionAddEventArgs> > WaitForReactionAsync(Func <MessageReactionAddEventArgs, bool> predicate,
                                                                                             DiscordUser user, TimeSpan?timeoutoverride = null)
 => await WaitForReactionAsync(x => predicate(x) && x.User.Id == user.Id, timeoutoverride);
Пример #16
0
 public static DiscordEmbed RSILeaderboard(DiscordGuild guild, DiscordUser orgChampion, DiscordUser bot, LeaderboardInsight leaderboard, Leaderboard prevLeaderboard, DateTime dataDate)
 {
     /*
      * {
      * "content": "this `supports` __a__ **subset** *of* ~~markdown~~ 😃 ```js\nfunction foo(bar) {\n  console.log(bar);\n}\n\nfoo(1);```",
      * "embed": {
      * "title": ":checkered_flag: Racing results: 12 June 10am",
      * "description": "Here at The Corporation over the past hour:\n- Greatest Improvement: **OldVandeval** Up 2 places\n- Largest dropoff: **RikkordMemorialRaceway** down 6 spots.\n\n**ChrispyKoala** has been our organization champion for **3 hours!**",
      * "color": 13632027,
      * "footer": {
      * "icon_url": "https://images-ext-1.discordapp.net/external/dfJOA4gfNhMY1LZ45H1Dr-Mik599WVnbm1xuJD-uVk8/https/cdn.discordapp.com/icons/475101141193981953/8c077f3a43b75214e40b6b8b1d3689b8.jpg",
      * "text": "Star Citizen Tools by SC TradeMasters"
      * },
      * "thumbnail": {
      * "url": "https://images-ext-1.discordapp.net/external/jF88yjqX6Grv-weNThuUtWk6a9p34nqS_5XMevsttm8/%3Fsize%3D1024/https/cdn.discordapp.com/avatars/238837208029724674/ff3b7c03247d5def0460aa282d421af6.png?width=665&height=665"
      * },
      * "image": {
      * "url": "https://robertsspaceindustries.com/media/18235dq8cydhur/store_small/Misc-Razer-Murray-Ringz-Paint-V5.jpg"
      * },
      * "author": {
      * "name": "ChrispyKangaroo",
      * "url": "https://discordapp.com",
      * "icon_url": "https://images-ext-1.discordapp.net/external/dfJOA4gfNhMY1LZ45H1Dr-Mik599WVnbm1xuJD-uVk8/https/cdn.discordapp.com/icons/475101141193981953/8c077f3a43b75214e40b6b8b1d3689b8.jpg"
      * },
      * "fields": [
      * {
      * "name": "OLD VANDERVAL // :arrow_up: Corp: #13",
      * "value": "- *ChrispyKoala*   #7\n- *Chippy_X*   #12"
      * },
      * {
      * "name": "RIKKORD MEMORIAL RACEWAY // :arrow_double_down: Corp: #43",
      * "value": "- *ChrispyKoala*   #7\n- *Chippy_X*   #12"
      * },
      * {
      * "name": "DEFFORD LINK // Corp: #10",
      * "value": "- *ChrispyKoala*   #7\n- *Chippy_X*   #12"
      * }
      * ]
      * }
      * }
      */
     return(null);
 }
Пример #17
0
        /// <summary>
        /// Waits for a user to start typing.
        /// </summary>
        /// <param name="user">User that starts typing.</param>
        /// <param name="timeoutoverride">Override timeout period.</param>
        /// <returns></returns>
        public async Task <InteractivityResult <TypingStartEventArgs> > WaitForUserTypingAsync(DiscordUser user, TimeSpan?timeoutoverride = null)
        {
            if (!Utilities.HasTypingIntents(this.Client.Configuration.Intents))
            {
                throw new InvalidOperationException("No typing intents are enabled.");
            }

            var timeout = timeoutoverride ?? Config.Timeout;
            var returns = await this.TypingStartWaiter.WaitForMatch(
                new MatchRequest <TypingStartEventArgs>(x => x.User.Id == user.Id, timeout));

            return(new InteractivityResult <TypingStartEventArgs>(returns == null, returns));
        }
Пример #18
0
        public override async Task <bool> ProcessStep(DiscordClient client, DiscordChannel channel, DiscordUser user)
        {
            var embedBuilder = new DiscordEmbedBuilder
            {
                Title       = $"Пожалуйста введите сообщение",
                Description = $"{user.Mention},{_content}",
            };

            embedBuilder.AddField("Чтобы остановить диалог", "используйте команду -cancle");

            if (_minLenght.HasValue)
            {
                embedBuilder.AddField("Минимальная длина:", $"{_minLenght.Value} символа");
            }
            if (_maxLenght.HasValue)
            {
                embedBuilder.AddField("Максимальная длина:", $"{_maxLenght.Value} символа");
            }

            var iteractivity = client.GetInteractivity();

            while (true)
            {
                var embed = await channel.SendMessageAsync(embed : embedBuilder).ConfigureAwait(false);

                OnMessageAdded(embed);

                var messageResult = await iteractivity.WaitForMessageAsync(x => x.ChannelId == channel.Id && x.Author.Id == user.Id).ConfigureAwait(false);

                OnMessageAdded(messageResult.Result);

                if (messageResult.Result.Content.Equals("-cancel", StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }

                if (_minLenght.HasValue)
                {
                    if (messageResult.Result.Content.Length < _minLenght.Value)
                    {
                        await TryAgain(channel, $"Ваше сообщение слишком короткое, содержит  {_minLenght.Value - messageResult.Result.Content.Length} символ").ConfigureAwait(false);

                        continue;
                    }
                }

                OnValidResult(messageResult.Result.Content);
                return(false);
            }
        }
Пример #19
0
        public static async Task <DiscordMessage> SendDirectMessage(this DiscordClient client, DiscordUser user, DiscordEmbed embed)
        {
            if (embed == null)
            {
                return(null);
            }

            return(await client.SendDirectMessage(user, string.Empty, embed));
        }
Пример #20
0
        public static async Task <MessageReactionAddEventArgs> AwaitReaction(this Context ctx, DiscordMessage message, DiscordUser user = null, Func <MessageReactionAddEventArgs, bool> predicate = null, TimeSpan?timeout = null)
        {
            var tcs = new TaskCompletionSource <MessageReactionAddEventArgs>();

            Task Inner(MessageReactionAddEventArgs args)
            {
                if (message.Id != args.Message.Id)
                {
                    return(Task.CompletedTask);                               // Ignore reactions for different messages
                }
                if (user != null && user.Id != args.User.Id)
                {
                    return(Task.CompletedTask);                                         // Ignore messages from other users if a user was defined
                }
                if (predicate != null && !predicate.Invoke(args))
                {
                    return(Task.CompletedTask);                                              // Check predicate
                }
                tcs.SetResult(args);
                return(Task.CompletedTask);
            }

            ctx.Shard.MessageReactionAdded += Inner;
            try {
                return(await tcs.Task.TimeoutAfter(timeout));
            } finally {
                ctx.Shard.MessageReactionAdded -= Inner;
            }
        }
Пример #21
0
 //Fake property
 public static async Task SetDelayDeletingAsync(this DiscordUser user, bool enabled) => await user.SetAsync("delayDelete", enabled);
Пример #22
0
        public static async Task <bool> PromptYesNo(this Context ctx, String msgString, DiscordUser user = null, Duration?timeout = null, IEnumerable <IMention> mentions = null, bool matchFlag = true)
        {
            DiscordMessage message;

            if (matchFlag && ctx.MatchFlag("y", "yes"))
            {
                return(true);
            }
            else
            {
                message = await ctx.Reply(msgString, mentions : mentions);
            }
            var cts = new CancellationTokenSource();

            if (user == null)
            {
                user = ctx.Author;
            }
            if (timeout == null)
            {
                timeout = Duration.FromMinutes(5);
            }

            // "Fork" the task adding the reactions off so we don't have to wait for them to be finished to start listening for presses
            var _ = message.CreateReactionsBulk(new[] { Emojis.Success, Emojis.Error });

            bool ReactionPredicate(MessageReactionAddEventArgs e)
            {
                if (e.Channel.Id != message.ChannelId || e.Message.Id != message.Id)
                {
                    return(false);
                }
                if (e.User.Id != user.Id)
                {
                    return(false);
                }
                return(true);
            }

            bool MessagePredicate(MessageCreateEventArgs e)
            {
                if (e.Channel.Id != message.ChannelId)
                {
                    return(false);
                }
                if (e.Author.Id != user.Id)
                {
                    return(false);
                }

                var strings = new [] { "y", "yes", "n", "no" };

                foreach (var str in strings)
                {
                    if (e.Message.Content.Equals(str, StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(true);
                    }
                }

                return(false);
            }

            var messageTask  = ctx.Services.Resolve <HandlerQueue <MessageCreateEventArgs> >().WaitFor(MessagePredicate, timeout, cts.Token);
            var reactionTask = ctx.Services.Resolve <HandlerQueue <MessageReactionAddEventArgs> >().WaitFor(ReactionPredicate, timeout, cts.Token);

            var theTask = await Task.WhenAny(messageTask, reactionTask);

            cts.Cancel();

            if (theTask == messageTask)
            {
                var responseMsg = (await messageTask).Message;
                var positives   = new[] { "y", "yes" };
                foreach (var p in positives)
                {
                    if (responseMsg.Content.Equals(p, StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(true);
                    }
                }
                return(false);
            }

            if (theTask == reactionTask)
            {
                return((await reactionTask).Emoji.Name == Emojis.Success);
            }

            return(false);
        }
Пример #23
0
 public async Task LookupAsync(CommandContext context, DiscordUser user) => await RespondLookupAsync(context, user);
Пример #24
0
 public GuildSettings()
 {
     Channels          = new DiscordVoiceChannels();
     ConfigMaintainers = new DiscordUser[0];
 }
Пример #25
0
 public async Task BanUserAsync(CommandContext context, DiscordUser user, [Range(0, 3)] byte level, [RemainingText] string reason)
 {
     await InsertUserAsync(context, user, level, reason, true);
 }
Пример #26
0
 public UserAccount(DiscordUser user)
 {
     _user = user;
     id    = _user.GetID();
     name  = _user.GetUser().Username;
 }
Пример #27
0
        public async Task EditMentionablesAsync(CommandContext ctx, DiscordUser user)
        {
            var origcontent = $"Hey, silly! Listen!";
            var newContent  = $"Hey, {user.Mention}! Listen!";

            await ctx.Channel.SendMessageAsync("✔ should ping, ❌ should not ping.").ConfigureAwait(false);

            var test1Msg = await ctx.Channel.SendMessageAsync("✔ Default Behaviour: " + origcontent).ConfigureAwait(false);

            await new DiscordMessageBuilder()
            .WithContent("✔ Default Behaviour: " + newContent)
            .ModifyAsync(test1Msg)
            .ConfigureAwait(false);                                                                                                                                  //Should ping User

            var test2Msg = await ctx.Channel.SendMessageAsync("✔ UserMention(user): " + origcontent).ConfigureAwait(false);

            await new DiscordMessageBuilder()
            .WithContent("✔ UserMention(user): " + newContent)
            .WithAllowedMentions(new IMention[] { new UserMention(user) })
            .ModifyAsync(test2Msg)
            .ConfigureAwait(false);                                                                                                                                  //Should ping user

            var test3Msg = await ctx.Channel.SendMessageAsync("✔ UserMention(): " + origcontent).ConfigureAwait(false);

            await new DiscordMessageBuilder()
            .WithContent("✔ UserMention(): " + newContent)
            .WithAllowedMentions(new IMention[] { new UserMention() })
            .ModifyAsync(test3Msg)
            .ConfigureAwait(false);                                                                                                                                  //Should ping user

            var test4Msg = await ctx.Channel.SendMessageAsync("✔ User Mention Everyone & Self: " + origcontent).ConfigureAwait(false);

            await new DiscordMessageBuilder()
            .WithContent("✔ User Mention Everyone & Self: " + newContent)
            .WithAllowedMentions(new IMention[] { new UserMention(), new UserMention(user) })
            .ModifyAsync(test4Msg)
            .ConfigureAwait(false);                                                                                                                                  //Should ping user

            var test5Msg = await ctx.Channel.SendMessageAsync("✔ UserMention.All: " + origcontent).ConfigureAwait(false);

            await new DiscordMessageBuilder()
            .WithContent("✔ UserMention.All: " + newContent)
            .WithAllowedMentions(new IMention[] { UserMention.All })
            .ModifyAsync(test5Msg)
            .ConfigureAwait(false);                                                                                                                                  //Should ping user

            var test6Msg = await ctx.Channel.SendMessageAsync("❌ Empty Mention Array: " + origcontent).ConfigureAwait(false);

            await new DiscordMessageBuilder()
            .WithContent("❌ Empty Mention Array: " + newContent)
            .WithAllowedMentions(new IMention[0])
            .ModifyAsync(test6Msg)
            .ConfigureAwait(false);                                                                                                                                  //Should ping no one

            var test7Msg = await ctx.Channel.SendMessageAsync("❌ UserMention(SomeoneElse): " + origcontent).ConfigureAwait(false);

            await new DiscordMessageBuilder()
            .WithContent("❌ UserMention(SomeoneElse): " + newContent)
            .WithAllowedMentions(new IMention[] { new UserMention(777677298316214324) })
            .ModifyAsync(test7Msg)
            .ConfigureAwait(false);                                                                                                                                  //Should ping no one (@user was not pinged)

            var test8Msg = await ctx.Channel.SendMessageAsync("❌ Everyone(): " + origcontent).ConfigureAwait(false);

            await new DiscordMessageBuilder()
            .WithContent("❌ Everyone(): " + newContent)
            .WithAllowedMentions(new IMention[] { new EveryoneMention() })
            .ModifyAsync(test8Msg)
            .ConfigureAwait(false);                                                                                                                                  //Should ping no one (@everyone was not pinged)
        }
Пример #28
0
 /// <summary>
 /// Wait for a specific reaction.
 /// </summary>
 /// <param name="message">Message reaction was added to.</param>
 /// <param name="user">User that made the reaction.</param>
 /// <param name="timeoutoverride">override timeout period.</param>
 /// <returns></returns>
 public async Task <InteractivityResult <MessageReactionAddEventArgs> > WaitForReactionAsync(DiscordMessage message, DiscordUser user,
                                                                                             TimeSpan?timeoutoverride = null)
 => await WaitForReactionAsync(x => x.User.Id == user.Id && x.Message.Id == message.Id, timeoutoverride);
Пример #29
0
 public static string Mention(DiscordUser user, bool nickname     = false) => (nickname ? $"<@!{user.ID}>" : $"<@{user.ID}>");
Пример #30
0
 public bool IsInDatabase(DiscordUser member) => IsInDatabase(member.Id);