Пример #1
0
 private async Task UpdateReactions()
 {
     if (message != null)
     {
         try {
             await message.DeleteAllReactionsAsync("Clearing all reactions for page update");
         } catch (UnauthorizedException) {
             remindMe.BotMethods.Log(this, new LogEventArgs {
                 Message = $"ReminderList tried clearing reactions, but couldn't because it doesn't have permission. An alternative method will be used but only this bot's reactions will be removed.",
                 Type    = LogType.Warning
             });
             foreach (var reaction in message.Reactions)
             {
                 if (reaction.IsMe)
                 {
                     await message.DeleteOwnReactionAsync(reaction.Emoji);
                 }
             }
         }
         if (CanGoLeftPage)
         {
             await message.CreateReactionAsync(LeftArrowEmoji);
         }
         for (int i = 0; i < NumberOfRemindersOnPage; ++i)
         {
             await message.CreateReactionAsync(DigitEmojis[i]);
         }
         if (CanGoRightPage)
         {
             await message.CreateReactionAsync(RightArrowEmoji);
         }
     }
 }
Пример #2
0
        public static async Task <Reaction> AddAndWaitForYesNoReaction(this InteractivityExtension interactivity, DiscordMessage msg, DiscordUser user)
        {
            DiscordClient client = interactivity.Client;

            await msg.CreateReactionAsync(DiscordEmoji.FromName(client, ":regional_indicator_y:"));

            await msg.CreateReactionAsync(DiscordEmoji.FromName(client, ":regional_indicator_n:"));

            InteractivityResult <MessageReactionAddEventArgs> interactivityResult = await interactivity.WaitForReactionAsync(msg, user);

            if (interactivityResult.TimedOut || interactivityResult.Result.Emoji.Equals(DiscordEmoji.FromName(client, ":regional_indicator_n:")))
            {
                DiscordMessage snark = await interactivityResult.Result.Channel.SendMessageAsync($"{user.Mention}, well then why did you get my attention! Thanks for wasting my time. Let me clean up now. :triumph:");

                await Task.Delay(5000);

                await interactivityResult.Result.Channel.DeleteMessagesAsync(new List <DiscordMessage> {
                    msg, snark
                });

                return(interactivityResult.TimedOut ? Reaction.None : Reaction.No);
            }

            await msg.DeleteAllReactionsAsync();

            return(Reaction.Yes);
        }
Пример #3
0
        public static async Task <PolarReactionState> polarReaction(CommandContext ctx, DiscordMessage mes)
        {
            await mes.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":white_check_mark:"));

            await mes.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":x:"));

            // var collectedReactions = await mes.CollectReactionsAsync(TimeSpan.FromSeconds(60));
            // System.Collections.ObjectModel.ReadOnlyCollection<DSharpPlus.Interactivity.EventHandling.Reaction> collectedReactions;
            System.Collections.ObjectModel.ReadOnlyCollection <DSharpPlus.Interactivity.EventHandling.Reaction> collectedReactions;
            IEnumerable <DSharpPlus.Interactivity.EventHandling.Reaction> result = null;
            AsyncBinder checkReaction = async() => {
                collectedReactions = await mes.CollectReactionsAsync(TimeSpan.FromMilliseconds(500));

                result = collectedReactions.Where(r => new string[] { ":white_check_mark:", ":x:" }.Contains(r.Emoji.GetDiscordName()) && r.Users.Contains(ctx.Message.Author));
                return(result.Count() > 0);
            };

            await asyncExecuteFor(() => checkReaction(), TimeSpan.FromSeconds(60));

            if (result != null)
            {
                if (result.FirstOrDefault(r => r.Emoji.GetDiscordName() == ":white_check_mark:") != null)
                {
                    return(PolarReactionState.Yes);
                }
                else
                {
                    return(PolarReactionState.No);
                }
            }
            else
            {
                return(PolarReactionState.TimedOut);
            }
        }
Пример #4
0
        public static async Task SetAccountsReactions(this DiscordClient client, DiscordMessage message, bool deleteExisting = true)
        {
            if (client == null)
            {
                return;
            }

            if (deleteExisting)
            {
                await message.DeleteAllReactionsAsync();
            }

            await message.CreateReactionAsync(DiscordEmoji.FromName(client, ":one:"));

            await message.CreateReactionAsync(DiscordEmoji.FromName(client, ":two:"));

            await message.CreateReactionAsync(DiscordEmoji.FromName(client, ":three:"));

            await message.CreateReactionAsync(DiscordEmoji.FromName(client, ":four:"));

            //await message.CreateReactionAsync(DiscordEmoji.FromName(client, ":five:"));
            //await message.CreateReactionAsync(DiscordEmoji.FromName(client, ":six:"));
            //await message.CreateReactionAsync(DiscordEmoji.FromName(client, ":seven:"));
            //await message.CreateReactionAsync(DiscordEmoji.FromName(client, ":eight:"));
            //await message.CreateReactionAsync(DiscordEmoji.FromName(client, ":nine:"));
            //await message.CreateReactionAsync(DiscordEmoji.FromName(client, ":ten:"));
        }
Пример #5
0
        public async Task InitPaginationAsync(DiscordMessage message, CacheContentType contentType, string parameter)
        {
            using (var databaseContext = new DatabaseContext())
            {
                var paginatedMessage = new PaginatedMessage
                {
                    GuildId     = message.Channel.GuildId.ToString(),
                    MessageId   = message.Id.ToString(),
                    ContentType = contentType,
                    Parameter   = parameter,
                    CurrentPage = 1
                };

                await databaseContext.PaginatedMessages.AddAsync(paginatedMessage);

                await databaseContext.SaveChangesAsync();
            }

            await message.CreateReactionAsync(DiscordEmoji.FromName(Bot.Client, FirstEmojiName));

            await message.CreateReactionAsync(DiscordEmoji.FromName(Bot.Client, LeftEmojiName));

            await message.CreateReactionAsync(DiscordEmoji.FromName(Bot.Client, RightEmojiName));

            await message.CreateReactionAsync(DiscordEmoji.FromName(Bot.Client, LastEmojiName));

            _logger.Info($"New pagination for {contentType} added");
        }
Пример #6
0
        public static async Task <bool> PromptUserToConfirm(CommandContext Context, string PromptMessage, bool bDeleteOnComplete = true)
        {
            var Interactivity = Context.Client.GetExtension <InteractivityExtension>();
            await Context.TriggerTypingAsync();

            DiscordMessage Msg = await Context.RespondAsync(PromptMessage);

            await Msg.CreateReactionAsync(DiscordEmoji.FromName(Context.Client, ":white_check_mark:"));

            await Msg.CreateReactionAsync(DiscordEmoji.FromName(Context.Client, ":x:"));

            var ReactContext = await Interactivity.WaitForReactionAsync(x => x.Emoji.Name == "✅" || x.Emoji.Name == "❌", Msg, Context.User);


            if (bDeleteOnComplete)
            {
                await Msg.DeleteAsync();
            }

            if (ReactContext.Result != null && ReactContext.Result.Emoji.Name == "✅")
            {
                return(true);
            }

            return(false);
        }
Пример #7
0
        //public static async Task<DiscordMessage> GetFirstMessage(this DiscordClient client, string lobbyName)
        //{
        //    var lobbyChannel = client.GetChannelByName(lobbyName);
        //    if (lobbyChannel == null)
        //    {
        //        Utils.LogError(new Exception($"Unrecognized lobby name '{lobbyName}'."));
        //        return null;
        //    }

        //    var messages = await lobbyChannel.GetMessagesAsync();
        //    if (messages != null)
        //    {
        //        return messages[messages.Count - 1];
        //    }

        //    return null;
        //}

        #region Old Raid Lobby System
        //public static async Task<DiscordMessage> UpdateLobbyStatus(this DiscordClient client, RaidLobby lobby)
        //{
        //    if (lobby == null)
        //    {
        //        Utils.LogError(new Exception($"Failed to get lobby from database."));
        //        return null;
        //    }

        //    var lobbyChannel = await client.GetChannel(lobby.ChannelId);
        //    if (lobbyChannel == null)
        //    {
        //        Utils.LogError(new Exception($"Failed to get raid lobby channel from {lobby.LobbyName} ({lobby.ChannelId})."));
        //        return null;
        //    }

        //    var pinnedMessage = await lobbyChannel.GetMessageAsync(lobby.PinnedRaidMessageId);
        //    if (pinnedMessage == null)
        //    {
        //        Utils.LogError(new Exception($"Failed to get pinned raid lobby message from message id {lobby.PinnedRaidMessageId}."));
        //        return null;
        //    }

        //    return await pinnedMessage.ModifyAsync(new Optional<string>(await CreateLobbyStatus(client, lobby)));
        //}

        //public static async Task<DiscordMessage> SendLobbyStatus(this DiscordClient client, RaidLobby lobby, DiscordEmbed embed, bool pin)
        //{
        //    if (lobby == null)
        //    {
        //        Utils.LogError(new Exception($"Failed to get lobby from database."));
        //        return null;
        //    }

        //    var lobbyChannel = await client.GetChannel(lobby.ChannelId);
        //    if (lobbyChannel == null)
        //    {
        //        Utils.LogError(new Exception($"Failed to get raid lobby channel from {lobby.LobbyName} ({lobby.ChannelId})."));
        //        return null;
        //    }

        //    var message = await lobbyChannel.SendMessageAsync(await CreateLobbyStatus(client, lobby), false, embed);
        //    if (pin) await message.PinAsync();
        //    lobby.PinnedRaidMessageId = message.Id;

        //    return message;
        //}

        //public static async Task<string> RaidLobbyUserStatus(this DiscordClient client, RaidLobby lobby)
        //{
        //    var lobbyUserStatus = "**Raid Lobby User Status:**\r\n";

        //    foreach (var lobbyUser in lobby.UserCheckInList)
        //    {
        //        var user = await client.GetUser(lobbyUser.UserId);
        //        if (user == null)
        //        {
        //            Utils.LogError(new Exception($"Failed to find user {lobbyUser.UserId}"));
        //            return string.Empty;
        //        }

        //        var people = lobbyUser.UserCount;

        //        if (lobbyUser.IsCheckedIn && !lobbyUser.IsOnTheWay)
        //        {
        //            lobbyUserStatus += $"{user.Mention} **checked-in** at {lobbyUser.CheckInTime.ToLongTimeString()} and is ready to start.\r\n";
        //        }
        //        else
        //        {
        //            lobbyUserStatus += $"{user.Mention} was **on the way** at **{lobbyUser.OnTheWayTime.ToLongTimeString()}** with {lobbyUser.UserCount} participants and an ETA of {lobbyUser.ETA}.\r\n";
        //        }

        //        lobbyUserStatus +=
        //            $"{lobby.NumUsersOnTheWay} users on their way.\r\n" +
        //            $"{lobby.NumUsersCheckedIn} users already checked in and ready.\r\n" +
        //            $"**{lobby.NumUsersCheckedIn}/{lobby.NumUsersCheckedIn + lobby.NumUsersOnTheWay}** Users Ready!\r\n";
        //    }

        //    return lobbyUserStatus;
        //}

        //private static async Task<string> CreateLobbyStatus(DiscordClient client, RaidLobby lobby)
        //{
        //    return $"**{lobby.LobbyName} RAID LOBBY** ({DateTime.Now.ToLongDateString()})\r\n" +
        //           $"**{Convert.ToUInt32(lobby.MinutesLeft)} Minutes Left!**\r\n" + //TODO: Fix minutes left.
        //           $"Raid Boss: **{lobby.PokemonName}**\r\n" +
        //           $"Start Time: {lobby.StartTime.ToLongTimeString()}\r\n" +
        //           $"Expire Time: {lobby.ExpireTime.ToLongTimeString()}\r\n" +
        //           $"Gym Name: {lobby.GymName}\r\n" +
        //           $"Address: {lobby.Address}\r\n\r\n" +
        //           await RaidLobbyUserStatus(client, lobby);
        //}
        #endregion

        #endregion

        #region Raid Lobby Reaction Extensions

        public static async Task SetDefaultRaidReactions(this DiscordClient client, DiscordMessage message, bool isLobby, bool deleteExisting = true)
        {
            if (client == null)
            {
                return;
            }

            if (deleteExisting)
            {
                await message.DeleteAllReactionsAsync();

                await Utils.Wait(10);
            }

            await message.CreateReactionAsync(DiscordEmoji.FromName(client, ":arrow_right:"));

            await message.CreateReactionAsync(DiscordEmoji.FromName(client, ":white_check_mark:"));

            if (isLobby)
            {
                await message.CreateReactionAsync(DiscordEmoji.FromName(client, ":x:"));

                await message.CreateReactionAsync(DiscordEmoji.FromName(client, ":arrows_counterclockwise:"));
            }
        }
        public async Task AddGuildEvent(CommandContext context)
        {
            DiscordMessage msg = await context.RespondAsync($":wave: Hi, {context.User.Mention}! You wanted to create a new event?");

            await msg.CreateReactionAsync(DiscordEmoji.FromName(context.Client, ":regional_indicator_y:"));

            await msg.CreateReactionAsync(DiscordEmoji.FromName(context.Client, ":regional_indicator_n:"));

            InteractivityExtension interactivity = context.Client.GetInteractivity();

            InteractivityResult <MessageReactionAddEventArgs> interactivityResult = await interactivity.WaitForReactionAsync(msg, context.User);

            if (interactivityResult.TimedOut ||
                !interactivityResult.Result.Emoji.Equals(DiscordEmoji.FromName(context.Client, ":regional_indicator_y:")))
            {
                DiscordMessage snark = await context.RespondAsync("Well, thanks for wasting my time. Have a good day.");

                await Task.Delay(5000);

                await context.Channel.DeleteMessagesAsync(new List <DiscordMessage> {
                    msg, snark, context.Message
                });

                return;
            }

            await context.Message.DeleteAsync();

            await msg.DeleteAllReactionsAsync();

            await this.AddGuildEventInteractive(context, interactivity, msg);
        }
Пример #9
0
        private async Task OnGuildAvailable(DiscordClient dClient, GuildCreateEventArgs args)
        {
            if (args.Guild.Id != Guilds.Bloon)
            {
                return;
            }

            await this.dClient.Guilds[Guilds.Bloon].GetEmojisAsync();

            DiscordChannel settingsChannel = await this.dClient.GetChannelAsync(BloonChannels.Settings);

            IReadOnlyList <DiscordMessage> messages = await settingsChannel.GetMessagesAsync(this.featureManager.Features.Count);

            for (int i = 0; i < this.featureManager.Features.Count; i++)
            {
                Feature        feature  = this.featureManager.Features[i];
                DiscordMessage message  = messages.Where(m => m.Embeds[0]?.Title == feature.Name).FirstOrDefault();
                DiscordEmbed   newEmbed = CreateFeatureEmbed(feature);

                if (message == null)
                {
                    message = await settingsChannel.SendMessageAsync(embed : newEmbed);

                    await message.CreateReactionAsync(DiscordEmoji.FromGuildEmote(this.dClient, FeatureEmojis.ToggleOff));

                    await message.CreateReactionAsync(DiscordEmoji.FromGuildEmote(this.dClient, FeatureEmojis.ToggleOn));
                }
                else if (!IdenticalEmbed(message.Embeds[0], newEmbed))
                {
                    await message.ModifyAsync(embed : newEmbed);
                }
            }
        }
Пример #10
0
        public async Task ClosedPollThreeOption(CommandContext ctx, [RemainingText] string message)
        {
            string[] embedTitle   = message.Split('|');
            string   embedMessage = string.Empty;

            embedMessage += $"{DiscordEmoji.FromGuildEmote(ctx.Client, Variables.Emojis.Polls.Yes)} **Yes**\n";
            embedMessage += $"{DiscordEmoji.FromGuildEmote(ctx.Client, Variables.Emojis.Polls.No)} **No**\n";
            embedMessage += $"{DiscordEmoji.FromName(ctx.Client, ":regional_indicator_m:")} **Maybe**\n";

            DiscordEmbed pollEmbed = new DiscordEmbedBuilder
            {
                Footer = new DiscordEmbedBuilder.EmbedFooter
                {
                    IconUrl = DiscordEmoji.FromGuildEmote(ctx.Client, Variables.Emojis.Polls.InfoIcon).Url,
                    Text    = "Vote using reactions",
                },
                Color       = new DiscordColor(250, 250, 250),
                Timestamp   = DateTime.UtcNow,
                Title       = $"**{embedTitle[0]}**",
                Description = embedMessage,
            };
            DiscordMessage reactionMessage = await ctx.Channel.SendMessageAsync(embed : pollEmbed);

            await reactionMessage.CreateReactionAsync(DiscordEmoji.FromGuildEmote(ctx.Client, Variables.Emojis.Polls.Yes));

            await reactionMessage.CreateReactionAsync(DiscordEmoji.FromGuildEmote(ctx.Client, Variables.Emojis.Polls.No));

            await reactionMessage.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":regional_indicator_m:"));
        }
Пример #11
0
        public async Task <ReactionCollectionContext> CreatePollAsync(DiscordMessage m, TimeSpan timeout, List <DiscordEmoji> Emojis)
        {
            foreach (var em in Emojis)
            {
                await m.CreateReactionAsync(em);
            }

            var rcc = new ReactionCollectionContext();
            var tsc = new TaskCompletionSource <ReactionCollectionContext>();
            var ct  = new CancellationTokenSource(timeout);

            ct.Token.Register(() => tsc.TrySetResult(rcc));
            AsyncEventHandler <MessageReactionAddEventArgs> handler1 = async(e) =>
            {
                await Task.Yield();

                if (e.Message.Id == m.Id && Emojis.Count(x => x == e.Emoji) > 0)
                {
                    rcc.AddReaction(e.Emoji, e.User.Id);
                }
            };

            this.Client.MessageReactionAdded += handler1;

            AsyncEventHandler <MessageReactionRemoveEventArgs> handler2 = async(e) =>
            {
                await Task.Yield();

                if (e.Message.Id == m.Id && Emojis.Count(x => x == e.Emoji) > 0)
                {
                    rcc.RemoveReaction(e.Emoji, e.User.Id);
                }
            };

            this.Client.MessageReactionRemoved += handler2;

            AsyncEventHandler <MessageReactionsClearEventArgs> handler3 = async(e) =>
            {
                await Task.Yield();

                if (e.Message.Id == m.Id)
                {
                    rcc.ClearReactions();
                    foreach (var em in Emojis)
                    {
                        await m.CreateReactionAsync(em);
                    }
                }
            };

            this.Client.MessageReactionsCleared += handler3;

            var result = await tsc.Task;

            this.Client.MessageReactionAdded    -= handler1;
            this.Client.MessageReactionRemoved  -= handler2;
            this.Client.MessageReactionsCleared -= handler3;

            return(result);
        }
Пример #12
0
    public async Task ClearEmoji(CommandContext c)
    {
        if (c.Guild == null)
        {
            throw new InvalidOperationException("You cannot modify emojis in a DM.");
        }

        InteractivityModule i = c.Client.GetInteractivityModule();

        IReadOnlyList <DiscordGuildEmoji> emojis = await c.Guild.GetEmojisAsync();

        if (!emojis.Any())
        {
            await c.RespondAsync("You have no emoji on this server to remove.");

            return;
        }

        DiscordMessage m = await c.RespondAsync("Are you sure that you want to clear all emoji from this server?");

        await m.CreateReactionAsync(Reactions.YES);

        await m.CreateReactionAsync(Reactions.NO);

        ReactionContext react = await i.WaitForReactionAsync(x => x == Reactions.YES || x == Reactions.NO, c.User,
                                                             TimeSpan.FromSeconds(30));

        await m.DeleteAsync();

        if (react != null)
        {
            if (react.Message == m)
            {
                DiscordMessage clear = await c.RespondAsync("Alright, I'm clearing all of the emojis on this server... This will take a couple of minutes due to Discord's ratelimits.");

                foreach (DiscordGuildEmoji e in emojis)
                {
                    try { await c.Guild.DeleteEmojiAsync(e); }
                    catch (BadRequestException)
                    {
                        await c.RespondAsync("I failed to delete the emoji. Discord gave me a bad response.");

                        return;
                    }
                }
                await clear.ModifyAsync("I've cleared all of the emojis on this server.");
            }
            else
            {
                await c.RespondAsync("You did not react to the original message. Aborting.");

                return;
            }
        }
        else
        {
            await c.RespondAsync("No response was given. Aborting.");
        }
    }
Пример #13
0
        public async Task AddPendingGame(CommandContext ctx, DiscordMessage msg, PendingGame game)
        {
            await msg.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, Reactions.OK));

            await msg.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, Reactions.NO));

            PendingGames.Add(msg.Id, game);
        }
Пример #14
0
        public async Task Execute()
        {
            Log.Information("Checking Helprace for new posts..");

            HelpracePost post = await this.helpraceService.GetLatestAsync("all_topics");

            // Unable to fetch the latest post from helprace
            if (post == null)
            {
                this.bloonLog.Error($"Something went wrong fetching the latest helprace post! Check Log File");
                return;
            }
            else if (!await this.helpraceService.TryStoreNewAsync(post))
            {
                Log.Information("Finished Helprace checks early");
                return;
            }

            DiscordChannel sbgBugs = await this.dClient.GetChannelAsync(SBGChannels.Bugs);

            if (post.Title.Length > 128)
            {
                post.Title = post.Title.Truncate(128) + "...";
            }

            if (post.Body.Length > 256)
            {
                post.Body = post.Body.Truncate(256) + $"... [Read more](https://superbossgames.helprace.com/i{post.UID})";
            }

            DiscordEmbed hrEmbed = new DiscordEmbedBuilder
            {
                Author = new DiscordEmbedBuilder.EmbedAuthor
                {
                    Name = post.Author,
                    Url  = $"https://superbossgames.helprace.com/i{post.UID}",
                },
                Footer = new DiscordEmbedBuilder.EmbedFooter
                {
                    IconUrl = DiscordEmoji.FromGuildEmote(this.dClient, PlatformEmojis.Helprace).Url,
                    Text    = $"Helprace | Channel: {post.Channel.Replace("ideas", "Suggestions", StringComparison.Ordinal).Replace("problems", "Bugs", StringComparison.Ordinal)}",
                },
                Color       = new DiscordColor(23, 153, 177),
                Timestamp   = post.Timestamp,
                Title       = post.Title,
                Description = post.Body,
                Url         = $"https://superbossgames.helprace.com/i{post.UID}",
            };

            DiscordMessage message = await sbgBugs.SendMessageAsync(embed : hrEmbed);

            await message.CreateReactionAsync(DiscordEmoji.FromGuildEmote(this.dClient, ReputationEmojis.Up));

            await message.CreateReactionAsync(DiscordEmoji.FromGuildEmote(this.dClient, ReputationEmojis.Down));

            Log.Information("Finished Helprace Scraping");
        }
Пример #15
0
        public async Task Background(CommandContext ctx, int?page = null)
        {
            if (page == null || page <= 0)
            {
                page = 1;
            }
            var msgBuilder = new DiscordMessageBuilder()
                             .WithContent(CustomMethod.GetBackgroundList(ctx, (int)page))
                             .WithReply(ctx.Message.Id, true);
            DiscordMessage TopMessage = await ctx.RespondAsync(msgBuilder);

            DiscordEmoji left  = DiscordEmoji.FromName(ctx.Client, ":arrow_left:");
            DiscordEmoji right = DiscordEmoji.FromName(ctx.Client, ":arrow_right:");

            await TopMessage.CreateReactionAsync(left);

            await Task.Delay(300).ContinueWith(t => TopMessage.CreateReactionAsync(right));

            bool end = false;

            do
            {
                var result = TopMessage.WaitForReactionAsync(ctx.User, TimeSpan.FromSeconds(20));
                if (result.Result.TimedOut)
                {
                    end = result.Result.TimedOut;
                }
                else if (result.Result.Result.Emoji == left)
                {
                    await TopMessage.DeleteReactionAsync(result.Result.Result.Emoji, ctx.User);

                    if (page > 1)
                    {
                        page--;
                        await TopMessage.ModifyAsync(CustomMethod.GetBackgroundList(ctx, (int)page));
                    }
                }
                else if (result.Result.Result.Emoji == right)
                {
                    await TopMessage.DeleteReactionAsync(result.Result.Result.Emoji, ctx.User);

                    page++;
                    try
                    {
                        await TopMessage.ModifyAsync(CustomMethod.GetBackgroundList(ctx, (int)page));
                    }
                    catch (Exception)
                    {
                        page--;
                    }
                }
            } while (!end);
            await TopMessage.DeleteAllReactionsAsync();
        }
Пример #16
0
        internal static async Task MessagesUpdateAsync(DiscordMessage mess)
        {
            Duel d = duels.Find(cd => mess == cd);

            if (d != null)
            {
                if (d.duel.flag)
                {
                    await mess.DeleteAsync();

                    return;
                }

                DiscordMessage mess1 = null, mess2 = null;

                try { mess1 = await mess.Channel.GetMessageAsync(d.duel.message1); } catch { }
                try { mess2 = await mess.Channel.GetMessageAsync(d.duel.message2); } catch { }

                if (mess1?.Author.Id == mess.Author.Id)
                {
                    await mess1.DeleteAsync();
                }
                else if (mess2?.Author.Id == mess.Author.Id)
                {
                    await mess2.DeleteAsync();
                }

                if (mess.Author.Id == d.duel.duelist1)
                {
                    d.duel.message1 = mess.Id;
                }
                else
                {
                    d.duel.message2 = mess.Id;
                }

                await d.UpdateAsync();

                await mess.CreateReactionAsync(await mess.Channel.Guild.GetEmojiAsync(604972398424621066u));

                await mess.CreateReactionAsync(await mess.Channel.Guild.GetEmojiAsync(604973811154288660u));

                if (!IsDuelReactionAdded)
                {
                    Program.bot.MessageReactionAdded += DuelReactionsAdded;
                    IsDuelReactionAdded = true;
                }
            }
            else
            {
                await mess.DeleteAsync();
            }
        }
Пример #17
0
        public async Task GeneratePaginationReactions(DiscordMessage m)
        {
            await m.CreateReactionAsync(DiscordEmoji.FromUnicode(this.Client, "⏮"));

            await m.CreateReactionAsync(DiscordEmoji.FromUnicode(this.Client, "◀"));

            await m.CreateReactionAsync(DiscordEmoji.FromUnicode(this.Client, "⏹"));

            await m.CreateReactionAsync(DiscordEmoji.FromUnicode(this.Client, "▶"));

            await m.CreateReactionAsync(DiscordEmoji.FromUnicode(this.Client, "⏭"));
        }
        /// <summary>
        /// initializes the private data for the lobby
        /// </summary>
        /// <param name="context">the command context from which the lobby will be initialized</param>
        /// <returns></returns>
        public async Task<LobbyInitializationResult> Initialize(CommandContext context)
        {
            Context = context;

            _EmbedBuilder.Author = new DiscordEmbedBuilder.EmbedAuthor
            {
                IconUrl = Context.User.AvatarUrl
            };

            foreach (var player in _Players)
            {
                if (!CheckIfEmojiExistsOnServer(player.Emoji.DiscordEmojiAlive) || !CheckIfEmojiExistsOnServer(player.Emoji.DiscordEmojiDead))
                    return LobbyInitializationResult.MissingEmoji;

                player.Alive = DiscordEmoji.FromName(Context.Client, player.Emoji.DiscordEmojiAlive);
                player.Dead = DiscordEmoji.FromName(Context.Client, player.Emoji.DiscordEmojiDead);
                _ValidReactEmojis.Add(player.Alive);
            }

            CurrentGameStatus = await UpdateGameState(GameState.StartUp, null);
            _EmbedMessage = await Context.Channel.SendMessageAsync(embed: _EmbedBuilder);
            _ToBeDeletedMessages.Add(_EmbedMessage);

            if (!CheckIfEmojiExistsOnServer(_Configuration.LeaveLobbyEmojiName))
                return LobbyInitializationResult.MissingEmoji;

            if (!CheckIfEmojiExistsOnServer(_Configuration.PlayPauseEmojiName))
                return LobbyInitializationResult.MissingEmoji;

            if (!CheckIfEmojiExistsOnServer(_Configuration.EndGameEmojiName))
                return LobbyInitializationResult.MissingEmoji;

            _LeaveLobby = DiscordEmoji.FromName(Context.Client, _Configuration.LeaveLobbyEmojiName);
            _PlayGame = DiscordEmoji.FromName(Context.Client, _Configuration.PlayPauseEmojiName);
            _StopGame = DiscordEmoji.FromName(Context.Client, _Configuration.EndGameEmojiName);
            _ValidReactEmojis.AddRange(_LeaveLobby, _PlayGame, _StopGame);

            await _EmbedMessage.CreateReactionAsync(_PlayGame);
            await _EmbedMessage.CreateReactionAsync(_StopGame);

            foreach (var player in _Players)
            {
                await _EmbedMessage.CreateReactionAsync(player.Alive);
                await Task.Delay(250);
            }

            await _EmbedMessage.CreateReactionAsync(_LeaveLobby);

            _Interactivity = Context.Client.GetInteractivity();
            CurrentGameStatus = await UpdateGameState(GameState.InLobby, null);

            return LobbyInitializationResult.Success;
        }
Пример #19
0
 private Task WoteAsync(DiscordMessage message, bool dunno = false)
 {
     message.CreateReactionAsync(DiscordEmoji.FromName(Client, ":white_check_mark:"));
     HelperMethods.Delay();
     message.CreateReactionAsync(DiscordEmoji.FromName(Client, ":x:"));
     if (dunno)
     {
         HelperMethods.Delay();
         message.CreateReactionAsync(DiscordEmoji.FromGuildEmote(Client, 614346797141458974));
     }
     return(Task.CompletedTask);
 }
Пример #20
0
        public static async Task AddEmotions(DiscordClient discord, DiscordMessage message)
        {
            await message.CreateReactionAsync(DiscordEmoji.FromName(discord, GetEmoji.EmojiOne)).ConfigureAwait(false);

            await message.CreateReactionAsync(DiscordEmoji.FromName(discord, GetEmoji.EmojiTwo)).ConfigureAwait(false);

            await message.CreateReactionAsync(DiscordEmoji.FromName(discord, GetEmoji.EmojiThree)).ConfigureAwait(false);

            await message.CreateReactionAsync(DiscordEmoji.FromName(discord, GetEmoji.EmojiFour)).ConfigureAwait(false);

            await message.CreateReactionAsync(DiscordEmoji.FromName(discord, GetEmoji.EmojiFive)).ConfigureAwait(false);

            return;
        }
Пример #21
0
        protected async Task AddReactionButton(DiscordEmoji emoji, UIAction pressedAction)
        {
            await message.CreateReactionAsync(emoji);

            Flipper.Bot.MessageReactionAdded += async args =>
            {
                if (args.Message == message && args.Emoji == emoji && args.User != Flipper.Bot.CurrentUser)
                {
                    var press  = pressedAction(args.ToUIActionArgs());
                    var delete = message.DeleteReactionAsync(emoji, args.User);
                    await Task.WhenAll(press, delete);
                }
            };
        }
Пример #22
0
        public async Task Vote(CommandContext ctx, [Description("What to vote about?")][RemainingText] string topic)
        {
            await ctx.Message.DeleteAsync();

            DiscordMessage msg = await new DiscordMessageBuilder()
                                 .WithContent(topic)
                                 .SendAsync(ctx.Channel);
            DiscordEmoji up   = DiscordEmoji.FromName(ctx.Client, ":thumbsup:");
            DiscordEmoji down = DiscordEmoji.FromName(ctx.Client, ":thumbsdown:");
            await msg.CreateReactionAsync(up);

            await Task.Delay(500);

            await msg.CreateReactionAsync(down);
        }
Пример #23
0
        private static async Task Waifunator(DiscordMessage message)
        {
            if (!string.IsNullOrWhiteSpace(message.Content) && message.Author.Id.Equals(Settings.Default.limid) && message.Content.Contains("wife", StringComparison.OrdinalIgnoreCase))
            {
                await message.CreateReactionAsync(DiscordEmoji.FromName(SekiMain.DiscordClient, ":regional_indicator_w:")).ConfigureAwait(false);

                await message.CreateReactionAsync(DiscordEmoji.FromName(SekiMain.DiscordClient, ":regional_indicator_a:")).ConfigureAwait(false);

                await message.CreateReactionAsync(DiscordEmoji.FromName(SekiMain.DiscordClient, ":regional_indicator_i:")).ConfigureAwait(false);

                await message.CreateReactionAsync(DiscordEmoji.FromName(SekiMain.DiscordClient, ":regional_indicator_f:")).ConfigureAwait(false);

                await message.CreateReactionAsync(DiscordEmoji.FromName(SekiMain.DiscordClient, ":regional_indicator_u:")).ConfigureAwait(false);
            }
        }
Пример #24
0
 public static async Task CreateReactionsBulk(this DiscordMessage msg, string[] reactions)
 {
     foreach (var reaction in reactions)
     {
         await msg.CreateReactionAsync(DiscordEmoji.FromUnicode(reaction));
     }
 }
Пример #25
0
 private async Task SendReactions(DiscordMessage message, int missCount)
 {
     for (int i = 1; i < Math.Min(missCount + 1, ServerContext.numberEmojis.Length); i++)
     {
         await message.CreateReactionAsync(ServerContext.numberEmojis[i]);
     }
 }
Пример #26
0
        public async Task Sendreactiongear(CommandContext ctx, DiscordMessage embedMessage, bool userSelf)
        {
            if (userSelf == true)
            {
                DiscordEmoji gearEmoji = DiscordEmoji.FromName(ctx.Client, ":gear:");
                await embedMessage.CreateReactionAsync(gearEmoji).ConfigureAwait(false);

                var interactivity = ctx.Client.GetInteractivity();

                try
                {
                    var ReactionResult = await interactivity.WaitForReactionAsync(
                        x => x.Message == embedMessage &&
                        x.User == ctx.User &&
                        (x.Emoji == gearEmoji)).ConfigureAwait(false);

                    if (ReactionResult.Result.Emoji == gearEmoji)
                    {
                        await embedMessage.DeleteAsync(null);
                        await SetId(ctx, ctx.Member.Id, userSelf);

                        return;
                    }
                }
                catch
                {
                    await embedMessage.DeleteAllReactionsAsync(null);
                }
            }
        }
        /// <summary>
        /// Makes a poll and returns poll results.
        /// </summary>
        /// <param name="m">Message to create poll on.</param>
        /// <param name="emojis">Emojis to use for this poll.</param>
        /// <param name="behaviour">What to do when the poll ends.</param>
        /// <param name="timeout">override timeout period.</param>
        /// <returns></returns>
        public async Task <ReadOnlyCollection <PollEmoji> > DoPollAsync(DiscordMessage m, IEnumerable <DiscordEmoji> emojis, PollBehaviour?behaviour = default, TimeSpan?timeout = null)
        {
            if (!Utilities.HasReactionIntents(this.Client.Configuration.Intents))
            {
                throw new InvalidOperationException("No reaction intents are enabled.");
            }

            if (emojis.Count() < 1)
            {
                throw new ArgumentException("You need to provide at least one emoji for a poll!");
            }

            foreach (var em in emojis)
            {
                await m.CreateReactionAsync(em).ConfigureAwait(false);
            }
            var res = await Poller.DoPollAsync(new PollRequest(m, timeout ?? this.Config.Timeout, emojis)).ConfigureAwait(false);

            var pollbehaviour = behaviour ?? this.Config.PollBehaviour;
            var thismember    = await m.Channel.Guild.GetMemberAsync(this.Client.CurrentUser.Id).ConfigureAwait(false);

            if (pollbehaviour == PollBehaviour.DeleteEmojis && m.Channel.PermissionsFor(thismember).HasPermission(Permissions.ManageMessages))
            {
                await m.DeleteAllReactionsAsync().ConfigureAwait(false);
            }

            return(new ReadOnlyCollection <PollEmoji>(res.ToList()));
        }
Пример #28
0
 private async Task AddReactions(DiscordClient client, DiscordMessage message)
 {
     foreach (string emoji in _optionsEmoji.Take(_options.Count))
     {
         await message.CreateReactionAsync(DiscordEmoji.FromName(client, emoji));
     }
 }
        private async Task Initialize(DiscordMessage message, int pageNum)
        {
            if (Pages > 1)
            {
                await message.CreateReactionAsync(DiscordEmoji.FromUnicode(Left));

                await message.CreateReactionAsync(DiscordEmoji.FromUnicode(Stop));

                await message.CreateReactionAsync(DiscordEmoji.FromUnicode(Right));
            }
            else
            {
                await message.CreateReactionAsync(DiscordEmoji.FromUnicode(Stop));
            }
            await Pagination(message, pageNum);
        }
Пример #30
0
        /// <summary>
        /// This will detect if a message within the SBG guild contains a word that is stored in the naughtywords file.
        /// </summary>
        /// <param name="args">Message arguments.</param>
        /// <returns>Profantiy warning to AUG chat.</returns>
        private async Task CensorAsync(DiscordClient dClient, MessageCreateEventArgs args)
        {
            if (args.Author.IsBot)
            {
                return;
            }

            if (this.censorer.TryCensorContent(args.Message.Content, out string censored, out KeyValuePair <int, Regex> censor))
            {
                DiscordChannel      sbgMod = args.Message.Channel.Guild.GetChannel(SBGChannels.Bloonside);
                DiscordEmbedBuilder embed  = new DiscordEmbedBuilder
                {
                    Color       = new DiscordColor(255, 0, 0),
                    Description = $"\"{censored}\"",
                    Timestamp   = args.Message.Timestamp,
                    Title       = $"**Censor**",
                };
                embed.AddField("Author", args.Message.Author.Mention, true);
                embed.AddField("Pattern", $"`{censor.Value}` (Id: {censor.Key})", true);
                embed.AddField("Original Message", $"[Click Here]({args.Message.JumpLink})", true);

                DiscordMessage embedMessage = await sbgMod.SendMessageAsync(embed);

                await embedMessage.CreateReactionAsync(DiscordEmoji.FromName(this.dClient, ":wastebasket:"));
            }
        }