Exemplo n.º 1
0
        private async Task CheckReactions(RestUserMessage sm, RoleSelector rsm, bool dupchecker = false)
        {
            for (int i = 0; i < sm.Reactions.Count; i++)
            {
                var rd = sm.Reactions.ElementAt(i);

                var t = await sm.GetReactionUsersAsync(rd.Key, 100).FlattenAsync();

                if (!rd.Value.IsMe)
                {
                    foreach (var bb in t)
                    {
                        await sm.RemoveReactionAsync(rd.Key, bb);
                    }
                }
                else if (!dupchecker)
                {
                    var p = rsm.roles.Where(s => s.EmoteCheckCompare(rd.Key.Name)).ToList();
                    if (p.Count == 0)
                    {
                        foreach (var bb in t)
                        {
                            await sm.RemoveReactionAsync(rd.Key, bb);
                        }
                    }
                }
            }

            if (!dupchecker)
            {
                await GetEmotes(sm, rsm);
            }
        }
Exemplo n.º 2
0
 internal static Tuple <IUser, Emote> GetFirstReaction(RestUserMessage msg, List <Emote> emotes, ulong expectedUser = 0)
 {
     foreach (Emote emote in emotes)
     {
         IReadOnlyCollection <IUser> reactions = null;
         if (expectedUser == 0)
         {
             reactions = msg.GetReactionUsersAsync(emote).Result;
         }
         else
         {
             reactions = msg.GetReactionUsersAsync(emote, 100, expectedUser).Result;
         }
         for (int i = 0; i < reactions.Count; ++i)
         {
             IUser reactor = reactions.ElementAt(i);
             if (!reactor.IsBot)
             {
                 return(new Tuple <IUser, Emote>(reactor, emote));
             }
         }
     }
     return(null);
 }
Exemplo n.º 3
0
        private async Task <bool> AskNeinJa(int num, RestUserMessage message)
        {
            int choice = -1;

            do
            {
                for (int i = 0; i < VoteNeinJa.Length; i++)
                {
                    var arr = (await message.GetReactionUsersAsync(VoteNeinJa[i], 2)
                               .FlattenAsync().ConfigureAwait(false)).ToArray();
                    if (arr.Length > 1)
                    {
                        choice = i;
                        break;
                    }
                }
            }while (choice == -1);
            Console.WriteLine($"{PlayerName(num)} just voted {(DEBUG ? (choice == 1 ? "Ja" : "Nein") : "")}.");
            return(choice == 1);
        }
Exemplo n.º 4
0
        private static async Task CheckReactions(this Event.Instance self, Event evt, RestUserMessage message, IEmote emote, int index)
        {
            IEnumerable <IUser> checkedUsers = await message.GetReactionUsersAsync(emote, 99).FlattenAsync();

            if (!checkedUsers.Contains(Program.DiscordClient.CurrentUser))
            {
                await message.AddReactionAsync(emote);
            }

            foreach (IUser user in checkedUsers)
            {
                if (user.Id == Program.DiscordClient.CurrentUser.Id)
                {
                    continue;
                }

                evt.SetAttendeeStatus(user.Id, index);

                SocketUser socketUser = Program.DiscordClient.GetUser(user.Id);
                await message.RemoveReactionAsync(emote, socketUser);
            }
        }
Exemplo n.º 5
0
        // General Role Select Refresh
        public static async Task RefreshChannelConfiguration()
        {
            var inputs = new List <string>();

            // Get last 100 messages currently in the channel
            var msgs = await Channel_Config.GetMessagesAsync(100).FlattenAsync();

            // Delete useless messages, add content of remaining ones for processing
            foreach (var msg in msgs)
            {
                var content = msg.Content;
                if (content.Contains(@"Template: Name | #channel | @role | :emoji:. Use !Refresh to update changes."))
                {
                    continue;
                }
                else if (ChannelSelectController.InputMessageFormatValid(content))
                {
                    inputs.Add(content);
                }
                else
                {
                    await msg.DeleteAsync();
                }
            }

            // Refresh the configurations
            var processMsg = ChannelSelectController.RefreshChannelList(inputs);

            await LogMessage(processMsg);

            // Generate Embed Message
            var embeddedMessage = await GenerateEmbeddedMessage();

            // Get all messages in the select channel and delete everything except the last message which should be Pneumas
            var configmsgs = await Channel_Select.GetMessagesAsync(100).FlattenAsync();

            RestUserMessage lastMsg = null;

            foreach (var msg in configmsgs)
            {
                if (msg == configmsgs.Last() && msg.Author.Id == Client.CurrentUser.Id)
                {
                    lastMsg = (RestUserMessage)msg;
                }
                else
                {
                    await msg.DeleteAsync();
                }
            }

            // Edit if the last message exists and is Pneuma's, else delete and create a new one
            if (lastMsg == null)
            {
                lastMsg = await Channel_Select.SendMessageAsync(null, false, embeddedMessage);
            }
            else
            {
                await lastMsg.ModifyAsync(x => x.Embed = embeddedMessage);
            }
            MainMessage = lastMsg;


            // Verify all emojis exist on message
            foreach (var selection in ChannelSelectController.ChannelList)
            {
                var emoji = await Guild.GetEmoteAsync(selection.EmojiId);

                // Verify if Pneuma has done the emote
                var emojiUses = await MainMessage.GetReactionUsersAsync(emoji, 100).FlattenAsync();

                if (!emojiUses.Any(u => u.Id == Client.CurrentUser.Id))
                {
                    await MainMessage.AddReactionAsync(emoji);
                }
            }
        }
Exemplo n.º 6
0
        private async Task ReactionAwait(RestUserMessage msg, string nameMsg, List <string> pageContent)
        {
            int    page            = 0;
            var    userId          = Context.User.Id;
            IEmote reactionBack    = new Emoji("⬅️");
            IEmote reactionForward = new Emoji("➡️");
            await msg.AddReactionAsync(reactionBack).ConfigureAwait(false);

            System.Threading.Thread.Sleep(300);
            await msg.AddReactionAsync(reactionForward).ConfigureAwait(false);

            var sw = new Stopwatch();

            sw.Start();

            while (sw.ElapsedMilliseconds < 30_000)
            {
                var collectorBack = await msg.GetReactionUsersAsync(reactionBack, 100).FlattenAsync().ConfigureAwait(false);

                var collectorForward = await msg.GetReactionUsersAsync(reactionForward, 100).FlattenAsync().ConfigureAwait(false);

                IUser?UserReactionBack    = collectorBack.FirstOrDefault(x => x.Id == userId && !x.IsBot);
                IUser?UserReactionForward = collectorForward.FirstOrDefault(x => x.Id == userId && !x.IsBot);

                if (UserReactionBack != null && page > 0)
                {
                    page--;
                    var embedBack = new EmbedBuilder {
                        Color = Color.DarkBlue
                    }.AddField(x =>
                    {
                        x.Name     = nameMsg;
                        x.Value    = pageContent[page];
                        x.IsInline = false;
                    }).WithFooter(x =>
                    {
                        x.IconUrl = "https://i.imgur.com/nXNBrlr.png";
                        x.Text    = $"Page {page + 1 } of {pageContent.Count}";
                    }).Build();

                    await msg.RemoveReactionAsync(reactionBack, UserReactionBack);

                    await msg.ModifyAsync(msg => msg.Embed = embedBack).ConfigureAwait(false);

                    sw.Restart();
                }
                else if (UserReactionForward != null && page < pageContent.Count - 1)
                {
                    page++;
                    var embedForward = new EmbedBuilder {
                        Color = Color.DarkBlue
                    }.AddField(x =>
                    {
                        x.Name     = nameMsg;
                        x.Value    = pageContent[page];
                        x.IsInline = false;
                    }).WithFooter(x =>
                    {
                        x.IconUrl = "https://i.imgur.com/nXNBrlr.png";
                        x.Text    = $"Page {page + 1} of {pageContent.Count}";
                    }).Build();

                    await msg.RemoveReactionAsync(reactionForward, UserReactionForward);

                    await msg.ModifyAsync(msg => msg.Embed = embedForward).ConfigureAwait(false);

                    sw.Restart();
                }
            }
            await msg.DeleteAsync().ConfigureAwait(false);
        }
Exemplo n.º 7
0
        private async Task FilterWalletsByReactions(RestUserMessage message)
        {
            Dictionary <ulong, List <IEmote> > reactionsPerUser = new Dictionary <ulong, List <IEmote> >();
            List <ulong> invalidUsers = new List <ulong>();

            foreach (var emote in message.Reactions.Keys)
            {
                Emote guildEmote = emote as Emote;
                try
                {
                    var usersReacted = await message.GetReactionUsersAsync(emote.Name + ":" + guildEmote.Id);

                    foreach (IUser user in usersReacted)
                    {
                        if (!reactionsPerUser.ContainsKey(user.Id))
                        {
                            reactionsPerUser[user.Id] = new List <IEmote>();
                        }

                        reactionsPerUser[user.Id].Add(emote);
                    }
                }
                catch (Exception e)
                {
                    _logger.LogCritical(e.Message, e);
                }
            }

            foreach (var walletPair in _wallets)
            {
                var user = walletPair.Key;
                if (!reactionsPerUser.ContainsKey(user.Id))
                {
                    await user.SendMessageAsync($"Oh my, you did not react to the rain announcement post with {_requiredReactions[user.Id]}! No shells for you...");

                    invalidUsers.Add(user.Id);
                    _logger.LogWarning($"Filtered {user.Username} - {walletPair.Value.Address}: NO REACTION");
                }
                else if (!reactionsPerUser[user.Id].Any(e => e.Name == _requiredReactions[user.Id].Name))
                {
                    await user.SendMessageAsync($"Oh my, you did not react to the rain announcement post with {_requiredReactions[user.Id]}! No shells for you...");

                    invalidUsers.Add(user.Id);
                    _logger.LogWarning($"Filtered {user.Username} - {walletPair.Value.Address}: WRONG REACTION");
                }
                else if (reactionsPerUser[user.Id].Count > 1)
                {
                    await user.SendMessageAsync($"Oh my, you reacted to the rain announcement post with **more** than {_requiredReactions[user.Id]}! No shells for you...");

                    invalidUsers.Add(user.Id);
                    _logger.LogWarning($"Filtered {user.Username} - {walletPair.Value.Address}: TOO MANY REACTIONS");
                }
                else
                {
                    _logger.LogInformation($"Wallet OK: {user.Username} - {walletPair.Value.Address}");
                }
            }

            foreach (var invalidUser in invalidUsers)
            {
                TurtleWallet unused;
                _wallets.TryRemove(_discord.GetUser(invalidUser), out unused);
            }
        }
Exemplo n.º 8
0
        public static async Task Giveaway(IGuild guild, IMessage message, uint timeInHours, uint money, IRole role = null)
        {
            await message.DeleteAsync();

            string reward = "";

            var emoji = new Emoji("🎊");
            var coin  = Messages.coin;

            if (money == 0 && role == null)
            {
                return;
            }
            if (money == 0 && role != null)
            {
                reward = $"👤 {role.Mention}";
            }
            if (money != 0 && role == null)
            {
                reward = $"{coin} {money}";
            }
            if (money != 0 && role != null)
            {
                reward = $"{coin} {money}\n👤 {role.Mention}";
            }

            var   GuildAccount      = GuildAccounts.GetAccount(guild);
            var   ContextGuild      = guild as SocketGuild;
            ulong GiveawayChannelID = GuildAccount.GiveawayChannelID;
            var   GiveawayChannel   = ContextGuild.GetChannel(GiveawayChannelID) as IMessageChannel;

            uint TimeInMilisecs = timeInHours * 3600000;

            var time  = DateTime.Now;
            var time2 = time.AddHours(TimeInMilisecs);
            var time3 = time2.ToString("HH:mm");

            EmbedBuilder eb = new EmbedBuilder();

            eb.WithAuthor("GIVEAWAY");
            eb.Author.WithIconUrl("https://freeiconshop.com/wp-content/uploads/edd/gift-flat.png");
            eb.WithDescription($"**Nagroda:**\n {reward}\n\n**Wyniki o:** {time3}");
            eb.WithFooter("👇 ZAREAGUJ ABY WZIĄĆ UDZIAŁ!");
            eb.WithColor(Color.Gold);

            RestUserMessage msg = (RestUserMessage)await GiveawayChannel.SendMessageAsync("@everyone", false, eb.Build());

            Global.GiveawayMessageID = msg.Id;
            await msg.AddReactionAsync(emoji);

            await Task.Delay(Convert.ToInt32(TimeInMilisecs));

            await msg.UpdateAsync();

            var    UsersThatReacted = (await msg.GetReactionUsersAsync(emoji)).Where(u => u.IsBot == false).ToArray();
            Random rand             = new Random();
            var    randomuser       = UsersThatReacted[rand.Next(UsersThatReacted.Length)];
            await GiveawayChannel.SendMessageAsync($":confetti_ball: GRATULACJE :confetti_ball:\n{randomuser.Mention} wygrywa.");

            try
            {
                var UserToAddRole = ContextGuild.GetUser(randomuser.Id);
                await UserToAddRole.AddRoleAsync(role);
            }
            catch { }
            try
            {
                var UserAccount = UserAccounts.GetAccount(randomuser);
                UserAccount.MoneyAccount += money;
                UserAccounts.SaveAccounts();
            }
            catch { }
        }
Exemplo n.º 9
0
        private async Task HandleEventAsync(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction reaction, RestUserMessage message, bool reactionAdded)
        {
            var           em     = message.Embeds.First();
            var           fields = em.Fields;
            List <string> att    = new List <string>();
            List <string> nAtt   = new List <string>();

            // Iterate over fields and grab data needed
            int    maxParticipants = 0;
            string dateTime        = "";

            for (int i = 0; i < fields.Count(); i++)
            {
                if (fields[i].Name == "When?")
                {
                    dateTime = fields[i].Value;
                }
                if (fields[i].Name == "Max Participants")
                {
                    maxParticipants = Int32.Parse(fields[i].Value);
                }
            }

            // Refresh both 'Attending' and 'Not attending' lists
            var attending = message.GetReactionUsersAsync(new Emoji("\u2705"), 100);

            attending.ForEach(users => {
                for (int i = 0; i < users.Count(); i++)
                {
                    if (!users.ElementAt(i).IsBot)
                    {
                        att.Add(users.ElementAt(i).Mention);
                    }
                }
            });
            var notAttending = message.GetReactionUsersAsync(new Emoji("\u274C"), 100);

            notAttending.ForEach(users => {
                for (int i = 0; i < users.Count(); i++)
                {
                    if (!users.ElementAt(i).IsBot)
                    {
                        nAtt.Add(users.ElementAt(i).Mention);
                    }
                }
            });

            // If reaction was added
            if (reactionAdded)
            {
                // Check if max participants have been reached
                if (att.Count > maxParticipants && maxParticipants != 0)
                {
                    await message.RemoveReactionAsync(new Emoji("\u2705"), reaction.User.Value);

                    return;
                }

                // Check for and handle double reactions
                if (reaction.Emote.Equals(new Emoji("\u2705")))
                {
                    foreach (string n in nAtt)
                    {
                        if (n == reaction.User.Value.Mention)
                        {
                            await message.RemoveReactionAsync(new Emoji("\u274C"), reaction.User.Value);

                            return;
                        }
                    }
                }
                if (reaction.Emote.Equals(new Emoji("\u274C")))
                {
                    foreach (string n in att)
                    {
                        if (n == reaction.User.Value.Mention)
                        {
                            await message.RemoveReactionAsync(new Emoji("\u2705"), reaction.User.Value);

                            return;
                        }
                    }
                }
            }

            var embed = await EmbedHandler.UpdateEventEmbed(em.Title, em.Description, maxParticipants, dateTime, em.Footer.Value.ToString(), att, nAtt);

            await message.ModifyAsync(q => {
                q.Embed = embed;
            });
        }
Exemplo n.º 10
0
        private async Task FilterWalletsByReactions(RestUserMessage message)
        {
            var reactionsPerUser = new Dictionary <ulong, List <IEmote> >();
            var invalidUsers     = new List <ulong>();

            var embed = new EmbedBuilder()
                        .WithColor(new Color(114, 137, 218))
                        .WithTitle($"REGISTRATION CLOSED! LET'S SEE WHO WAS A GOOD TURTLE")
                        .WithImageUrl(_config["rainImageUrlFilter"])
                        .Build();
            await message.ModifyAsync(m => m.Embed = embed);

            foreach (var emote in message.Reactions.Keys)
            {
                var guildEmote = emote as Emote;
                try
                {
                    var usersReacted = await message.GetReactionUsersAsync(emote.Name + ":" + guildEmote.Id);

                    foreach (var user in usersReacted)
                    {
                        if (!reactionsPerUser.ContainsKey(user.Id))
                        {
                            reactionsPerUser[user.Id] = new List <IEmote>();
                        }

                        reactionsPerUser[user.Id].Add(emote);
                    }
                }
                catch (Exception e)
                {
                    _logger.LogCritical(e.Message, e);
                }
            }

            await message.RemoveAllReactionsAsync();

            foreach (var walletPair in _wallets)
            {
                var user = walletPair.Key;
                if (!reactionsPerUser.ContainsKey(user.Id))
                {
                    await user.SendMessageAsync($"Oh my, you did not react to the rain announcement post with {_requiredReactions[user.Id]}! No shells for you...");

                    invalidUsers.Add(user.Id);
                    _logger.LogWarning($"Filtered {user.Username} - {walletPair.Value.Address}: NO REACTION");
                }
                else if (reactionsPerUser[user.Id].All(e => e.Name != _requiredReactions[user.Id].Name))
                {
                    await user.SendMessageAsync($"Oh my, you did not react to the rain announcement post with {_requiredReactions[user.Id]}! No shells for you...");

                    invalidUsers.Add(user.Id);
                    _logger.LogWarning($"Filtered {user.Username} - {walletPair.Value.Address}: WRONG REACTION");
                }
                else if (reactionsPerUser[user.Id].Count > 1)
                {
                    await user.SendMessageAsync($"Oh my, you reacted to the rain announcement post with **more** than {_requiredReactions[user.Id]}! No shells for you...");

                    invalidUsers.Add(user.Id);
                    _logger.LogWarning($"Filtered {user.Username} - {walletPair.Value.Address}: TOO MANY REACTIONS");
                }
                else
                {
                    _logger.LogInformation($"Wallet OK: {user.Username} - {walletPair.Value.Address}");
                }
            }

            foreach (var invalidUser in invalidUsers)
            {
                TurtleWallet unused;
                _wallets.TryRemove(_discord.GetUser(invalidUser), out unused);
            }
        }
Exemplo n.º 11
0
        private async void Timer_SendNextMessageEvent(object sender, ElapsedEventArgs e)
        {
            if (Waiting)
            {
                if (KickLast > 0)
                {
                    BanroyaleMessageDict.Remove(this.Message.Id);
                }

                var usersReac = (await Message.GetReactionUsersAsync(Emote, 100).FlattenAsync()).Select(x => x.Id).ToHashSet();
                var users     = Role.Members.Where(x => !usersReac.Contains(x.Id)).ToList();

                BanroyaleMessageDict.Remove(this.Message.Id);
                Waiting = false;

                if (await LostUsers(this, users))
                {
                    return;
                }
            }

            var rnd = new Random();
            int x   = rnd.Next(3);

            KickLast = Role.Members.Count();
            if (KickLast > 20)
            {
                KickLast = KickLast / 10 + x;
            }
            else if (KickLast > 5)
            {
                KickLast = x;
            }
            else
            {
                KickLast = x - 1 >= 0 ? x - 1 : 0;
            }

            int emoteCount = 4;
            var emotes     = BanroyaleUtil.DrawEmotes(emoteCount);
            int r          = rnd.Next(emoteCount);

            Emote = emotes[r];

            Message = await Channel.SendMessageAsync($"{Role.Mention}", embed : new EmbedBuilderPrepared($"Click the {Emote} reaction to stay in the game!\n" +
                                                                                                         $"{(KickLast > 0 ? $"Last **{KickLast}** participants to react will lose!" : "")}")
                                                     .WithColor(Color.Blue)
                                                     .Build());

            foreach (var emote in emotes)
            {
                _ = Message.AddReactionAsync(emote);
            }

            await BanroyaleMessageDb.AddMessage(new BanroyaleMessage
            {
                Active      = true,
                BanroyaleId = Banroyale.Id,
                MessageId   = Message.Id,
                EmoteId     = Emote.Id
            });

            if (KickLast > 0)
            {
                BanroyaleMessageDict.Add(Message.Id, this);
            }

            Waiting = true;

            double interval = new Random().Next(Banroyale.MaxFrequency - Banroyale.MinFrequency) + Banroyale.MinFrequency;

            Timer.Interval = interval * 1000;
            Timer.Start();
        }