示例#1
0
        internal static async Task HandleReactionAdded(ISocketMessageChannel channel, SocketReaction reaction)
        {
            if (ReactionCommands.TryGetValue(reaction.Emote.Name, out ReactionCommand reactionCommand))
            {
                SocketGuildUser user = Var.Guild.GetUser(reaction.UserId);

                if (user != null)
                {
                    AccessLevel userLevel = SettingsModel.GetUserAccessLevel(user);
                    if (reactionCommand.HasPermission(userLevel))
                    {
                        IMessage message = await channel.GetMessageAsync(reaction.MessageId);

                        ReactionContext context = new ReactionContext(message, user, channel, reaction);
                        try
                        {
                            await reactionCommand.HandleReaction(context);
                        }
                        catch (Exception e)
                        {
                            await SendCommandExecutionExceptionMessage(e, context, reactionCommand);
                        }
                    }
                }
            }
        }
示例#2
0
        private async Task HandleReaction(Cacheable <IUserMessage, ulong> message, ISocketMessageChannel channel, SocketReaction reaction)
        {
            if (reaction.UserId == discord.CurrentUser.Id)
            {
                return;                 // If the reaction was added by the bot, ignore.
            }
            if (!Menus.TryGetValue(message.Id, out Menu menu))
            {
                return;                 // If it can't find a menu attached to this message, ignore.
            }
            if (!await menu.JudgeCriteriaAsync(reaction))
            {
                return;                 // If the conditions on the menu fail, ignore.
            }

            // Let the menu handle the reaction
            _ = Task.Run(async() =>
            {
                var msg = (RestUserMessage)await channel.GetMessageAsync(message.Id);
                msg?.RemoveReactionAsync(reaction.Emote, reaction.User.Value);
                if (await menu.HandleButtonPress(reaction))
                {
                    Menus.Remove(message.Id);
                }
                await Task.Delay(500);
            });
        }
示例#3
0
        private async Task OnReactionAdded(Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel channelSocket,
                                           SocketReaction emoteSocket)
        {
            var msg = await channelSocket.GetMessageAsync(emoteSocket.MessageId);

            // If message is not by bot or reaction added by bot
            if (!msg.Author.IsBot || emoteSocket.UserId == _client.CurrentUser.Id)
            {
                return;
            }

            // var users = await msg.GetReactionUsersAsync(new Emoji("✅"), Int32.MaxValue).FlattenAsync();
            switch (emoteSocket.Emote.Name)
            {
            case EmojiUnicode.Confirm:
                EmbedBuilder embedBuilder = await SendMedia(msg);

                var mediaMsg = await channelSocket.SendMessageAsync(embed : embedBuilder.Build());

                await mediaMsg.AddReactionAsync(new Emoji(EmojiUnicode.Heart));

                break;

            case EmojiUnicode.Heart:
                SocketUser user   = _client.GetUser(emoteSocket.UserId);
                string     answer = await SaveMedia(msg, user);

                await channelSocket.SendMessageAsync(answer);

                break;

            default: return;
            }
        }
示例#4
0
        public static async Task ReactionRemoved(Cacheable <IUserMessage, ulong> message, ISocketMessageChannel channel, SocketReaction emoji)
        {
            if (channel.Id == DiscordBot.roleChannelID && message.Id == DiscordBot.roleMessageID && emoji.UserId != DiscordBot.client.CurrentUser.Id)
            {
                SocketGuild     guild = DiscordBot.client.GetGuild(DiscordBot.mainGuildId);
                SocketGuildUser user  = guild.GetUser(emoji.UserId);
                switch (emoji.Emote.Name)
                {
                case "🔔":
                    await user.RemoveRoleAsync(guild.GetRole(DiscordBot.notificationRoleID));

                    break;

                case "🕵":
                    await user.RemoveRoleAsync(guild.GetRole(DiscordBot.cyberSecurityRoleId));

                    break;

                case "💻":
                    await user.RemoveRoleAsync(guild.GetRole(DiscordBot.programmingRoleID));

                    break;

                default:
                    await(await channel.GetMessageAsync(message.Id) as RestUserMessage).RemoveReactionAsync(emoji.Emote, user);
                    break;
                }
            }
            else
            {
                return;
            }
        }
示例#5
0
        private async Task Client_ReactionAdded(Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
        {
            var currentEmbed = embeds.List.FirstOrDefault(x => x.MessageId == arg3.MessageId);

            if (currentEmbed == null)
            {
                return;
            }
            if (arg3.UserId == 332106465412251648)
            {
                return;
            }

            var msg = await arg2.GetMessageAsync(currentEmbed.MessageId) as SocketUserMessage;

            if (arg3.Emote.Name == "◀")
            {
                if (currentEmbed.CurrentPage != 1)
                {
                    await msg.ModifyAsync(x => x.Embed = currentEmbed.GetEmbed(false));
                }
                await arg3.Message.Value.RemoveReactionAsync(arg3.Emote, arg3.User.Value);
            }
            else if (arg3.Emote.Name == "▶")
            {
                await msg.ModifyAsync(x => x.Embed = currentEmbed.GetEmbed(true));

                await arg3.Message.Value.RemoveReactionAsync(arg3.Emote, arg3.User.Value);
            }
            else
            {
                await arg3.Message.Value.RemoveReactionAsync(arg3.Emote, arg3.User.Value);
            }
        }
示例#6
0
        private async void AddUser()
        {
            if (_raidService.AddUser(_raid.RaidId, _user, _role, _availability, _usedAccount, out string resultMessage))
            {
                try
                {
                    await UserExtensions.SendMessageAsync(_user, resultMessage);

                    IUserMessage userMessage = (IUserMessage)await _channel.GetMessageAsync(_raid.MessageId);

                    await userMessage.ModifyAsync(msg => msg.Embed = _raid.CreateRaidMessage());

                    await _logService.LogRaid($"{_raid.Users[_user.Id].Nickname} signed up as {_availability}", _raid);
                }
                catch { }
                finally
                {
                    _conversationService.CloseConversation(_user.Id);
                }
            }
            else
            {
                resultMessage += $"\n\n{CreateSignUpMessage(_raid)}";
                await UserExtensions.SendMessageAsync(_user, resultMessage);
            }
        }
        //Kudos to Sol's mate
        async Task OnReactAddedAsync(Cacheable <IUserMessage, ulong> message, ISocketMessageChannel channel, SocketReaction reaction)
        {
            if (!reaction.User.IsSpecified || !JiraReporter.Settings.CheckAllowed(reaction.User.Value as SocketUser))
            {
                return;
            }

            string type;

            if (reaction.Emote.Name == "🐛")
            {
                type = "Bug";
            }
            else if (reaction.Emote.Name == "🚀")
            {
                type = "Story";
            }
            else
            {
                return;
            }

            SocketTextChannel textChannel = channel as SocketTextChannel;

            RestUserMessage userMessage = channel.GetMessageAsync(message.Id).Result as RestUserMessage;

            Task.Run(() => new JiraReporter().Report(reaction.User.Value, client, userMessage, new InteractiveService(client, TimeSpan.FromMinutes(5)), type));
        }
示例#8
0
        /// <summary>
        /// The event method that gets called whenever a reaction is placed on a message
        /// </summary>
        /// <param name="message">the message the reaction was added to</param>
        /// <param name="channel">the discord channel the message came from</param>
        /// <param name="reaction">the reaction on the message from the channel</param>
        /// <returns></returns>
        public async Task ReactionAdded(Cacheable <IUserMessage, ulong> message, ISocketMessageChannel channel, SocketReaction reaction)
        {
            // check if the esi token needs to be refreshed and refresh it
            await RefreshEsiToken();

            if (!channel.Name.Equals(_channelToWatch, StringComparison.OrdinalIgnoreCase))
            {
                Log("Reaction received in channel bot is not watching.  Ignoring message");
                return;
            }

            // check to make sure the user who placed the reaction on the message is an approved user and
            // that the reaction is one we care about
            if (!_approvedDiscordUsers.Contains(reaction.User.ToString()))
            {
                Log($"Unapproved user added reaction to message: {reaction.User}");
                return;
            }
            if (!reaction.Emote.Name.Equals("sendmail", StringComparison.OrdinalIgnoreCase))
            {
                Log($"Other emote detected on message: {reaction.Emote.Name}");
                return;
            }

            var discordMessage = await channel.GetMessageAsync(message.Id);

            if (discordMessage == null)
            {
                Log($"Unable to find discord message from channel {channel.Name}");
                return;
            }

            await BuildAndSendMessage(discordMessage);
        }
示例#9
0
        public static async Task ReactionAdded(Cacheable <IUserMessage, ulong> message, ISocketMessageChannel channel, SocketReaction reaction)
        {
            // Gets the guild channel, guild (through the guild channel), role and user.
            IGuildChannel guildChannel        = channel as IGuildChannel;
            IGuild        guild               = guildChannel.Guild as IGuild;
            IMessage      introductionMessage = await channel.GetMessageAsync(message.Id);

            SocketGuildUser messageAuthor = await guild.GetUserAsync(introductionMessage.Author.Id) as SocketGuildUser;

            SocketGuildUser reactedUser = await guild.GetUserAsync(reaction.UserId) as SocketGuildUser;

            IRole newUserRole   = guild.Roles.FirstOrDefault(x => x.Id == newUserRoleId);
            IRole moderatorRole = guild.Roles.FirstOrDefault(x => x.Id == moderatorRoleId);
            IRole adminRole     = guild.Roles.FirstOrDefault(x => x.Id == adminRoleId);

            // Checks if the reaction was in the correct channel.
            if (channel.Id == welcomeChannelId)
            {
                // Checks if the reaction occurred at the right message.
                if (messageAuthor.Roles.Contains(newUserRole))
                {
                    if (reactedUser.Roles.Contains(moderatorRole) || reactedUser.Roles.Contains(adminRole))
                    {
                        // Checks if the reaction was the correct emoij.
                        if (reaction.Emote.Name.Equals(reactionEmote))
                        {
                            await messageAuthor.RemoveRoleAsync(newUserRole);
                        }
                    }
                }
            }

            return;
        }
示例#10
0
        /// <summary>
        /// Handles reactions added to messages
        /// </summary>
        public static async Task ReactionAddedHandler(Cacheable <IUserMessage, ulong> message, ISocketMessageChannel channel, SocketReaction reaction)
        {
            IUserMessage reactionMessage;

            if (reaction.Message.IsSpecified)
            {
                reactionMessage = reaction.Message.Value;
            }
            else
            {
                reactionMessage = await channel.GetMessageAsync(reaction.MessageId) as IUserMessage;
            }
            SocketTextChannel textChannel = channel as SocketTextChannel;

            if ((reactionMessage != null) && (textChannel != null) && reactionMessage.Author.Id == BotCore.Client.CurrentUser.Id && reaction.User.Value.Id != BotCore.Client.CurrentUser.Id)
            {
                if (InteractiveMessages.TryGetValue(reactionMessage.Id, out InteractiveMessage interactiveMessage))
                {
                    MessageInteractionContext context = new MessageInteractionContext(reaction, reactionMessage, textChannel);
                    if (context.IsDefined)
                    {
                        await interactiveMessage.HandleInteraction(context);
                    }
                }
            }
        }
示例#11
0
        public async Task ReactionRemoved(Cacheable <IUserMessage, ulong> cachedMessage, ISocketMessageChannel channel, SocketReaction reaction)
        {
            //Don't trigger if the emoji is wrong, or if the user is bot
            if (reaction.User.IsSpecified && reaction.User.Value.IsBot)
            {
                return;
            }

            if (reaction.Emote.Name != _emoji)
            {
                return;
            }

            //If there's an error reply when the reaction is removed, delete that reply,
            //remove the cached error, remove it from the cached replies, and remove
            //all reactions from the original messages
            if (_errorReplies.TryGetValue(cachedMessage.Id, out var botReplyId))
            {
                var msg = await channel.GetMessageAsync(botReplyId);

                await msg.DeleteAsync();

                _associatedErrors.Remove(cachedMessage.Id);
                _errorReplies.Remove(cachedMessage.Id);

                var originalMessage = await cachedMessage.GetOrDownloadAsync();

                await originalMessage.RemoveAllReactionsAsync();
            }
        }
示例#12
0
        public static async Task ReactionAdded(Cacheable <IUserMessage, ulong> message, ISocketMessageChannel channel, SocketReaction reaction)
        {
            if (reaction.Emote.Name == "commend")
            {
                IUserMessage msg = (IUserMessage)channel.GetMessageAsync(message.Id).Result;

                IUser author = msg.Author;

                if (author.IsBot)
                {
                    return;
                }

                IUser sender = reaction.User.Value;

                using (VooperContext context = new VooperContext(VoopAI.DBOptions))
                {
                    User senderData = context.Users.FirstOrDefault(u => u.discord_id == sender.Id);

                    if (senderData == null || author.Id == sender.Id || senderData.discord_last_commend_hour == DateTime.Now.Hour)
                    {
                        await msg.RemoveReactionAsync(reaction.Emote, sender);
                    }
                    else
                    {
                        await AddCommend(author, sender, message.Id);
                    }
                }
            }
        }
        public static async Task UpdateBillboardAsync(IGuild guild, IUserMessage message, ISocketMessageChannel channel,
                                                      GovernanceVote vote, SuggestionType type)
        {
            var msg = GetBillboardMessage(type);

            var billboard = (IUserMessage)await channel.GetMessageAsync(vote.VoteBillboardId);

            if (billboard == null)
            {
                return;
            }

            if (type == SuggestionType.Vote)
            {
                var embed = await AddVotesAsync(guild, new EmbedBuilder(), message);

                await billboard.ModifyAsync(props =>
                {
                    props.Content = msg;
                    props.Embed   = embed.WithTitle("Votes").Build();
                });
            }
            else
            {
                await billboard.ModifyAsync(props =>
                {
                    props.Content = msg;
                    props.Embed   = null;
                });
            }
        }
        private async Task ReactionAdded(Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
        {
            if (arg3.UserId == bot.CurrentUser.Id)
            {
                return;
            }

            var message = await arg2.GetMessageAsync(arg1.Id);

            if (message == null || !(arg2 is SocketGuildChannel))
            {
                return;
            }

            var embed = message.Embeds.FirstOrDefault();

            if (embed == null || string.IsNullOrEmpty(embed.Description))
            {
                return;
            }

            var guildConfig = Config.GetServerConfig(((SocketGuildChannel)arg2).Guild.Id, ChatTypes.Discord);
            //var message = arg1.Value;
            var channel = (SocketGuildChannel)arg2;
            var user    = channel.Guild.GetUser(arg3.UserId);

            var parser = GetParser(guildConfig);
            var post   = parser.ParsePostFromPostMessage(message.Embeds.First().Description, guildConfig);

            if (post != null && user != null)
            {
                if (DeleteEmojis.Contains(arg3.Emote.Name))//thumbs down will be quick way to delete a raid by poster/admin
                {
                    await DeletePost(post, user.Id, user.GuildPermissions.Administrator || user.GuildPermissions.ManageGuild);
                }
                else
                {
                    var joinedUser = post.JoinedUsers.FirstOrDefault(x => x.Id == user.Id);
                    if (joinedUser != null)
                    {
                        joinedUser.PeopleCount++;
                    }
                    else
                    {
                        post.JoinedUsers.Add(new PokemonRaidJoinedUser(user.Id, guildConfig.Id, post.UniqueId, user.Username, 1));
                    }

                    var messages = await MakePost(post, parser);

                    var tasks = new List <Task>();
                    foreach (var resultmessage in messages.Where(x => x.Channel.Id != message.Channel.Id))
                    {
                        tasks.Add(resultmessage.AddReactionAsync(arg3.Emote.Name));
                    }

                    Task.WaitAll(tasks.ToArray());
                    Config.Save();
                }
            }
        }
示例#15
0
        private async Task ReactionAdded(Cacheable <IUserMessage, ulong> cachableMessage, ISocketMessageChannel channel, SocketReaction reaction)
        {
            try {
                if (channel == null)
                {
                    return;
                }

                IGuild   guild   = ((IGuildChannel)channel).Guild;
                IMessage message = await channel.GetMessageAsync(cachableMessage.Id);

                if (message.Author.Id == Cirilla.Client.CurrentUser.Id)
                {
                    ulong      id   = message.MentionedUserIds.FirstOrDefault();
                    IGuildUser user = await guild.GetUserAsync(id);

                    if (id != 0)
                    {
                        Kick(user, (IUserMessage)message, guild);
                    }
                }
            } catch {
                // error
            }
        }
示例#16
0
        private async Task OnReactionRemoved(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction reaction)
        {
            // Check if reaction on message was a reaction on a tracked message
            ulong eventTrackingId = 0;

            foreach (ulong id in Config.messageIdTracker)
            {
                if (reaction.MessageId == id)
                {
                    eventTrackingId = id;
                }
            }

            // Ignore bot reactions
            if (reaction.User.Value.IsBot)
            {
                return;
            }

            // Execute correct handler
            try {
                var message = channel.GetMessageAsync(eventTrackingId).Result as RestUserMessage;
                var em      = message.Embeds.First();

                // If tracked message is an event
                if (em.Footer.Value.ToString().Contains("Event"))
                {
                    await HandleEventAsync(cache, channel, reaction, message, false);
                }
            } catch (Exception e) {
                await LogAsync(new LogMessage(LogSeverity.Debug, "bot", e.ToString()));
            }
        }
示例#17
0
        private static async Task OnReactionRemoved(ulong MessageID, ISocketMessageChannel NewMsg, SocketReaction react)
        {
            if (MessageID == ServerConfigData.ServerRoleSetUpMsgID && react.UserId != Program.ServerConfigData.PointersAnonUserID["Quantum Bot"])
            {
                foreach (KeyValuePair <string, ChannelRoles> EmoteData in Program.ChannelRolesData)
                {
                    if (react.Emote.Equals(EmoteData.Value.ChannelReactEmote))
                    {
                        await(react.User.Value as SocketGuildUser).RemoveRoleAsync((NewMsg as SocketGuildChannel).Guild.GetRole(EmoteData.Value.RoleID));

                        //NO LOGIC CHECK FOR WHO GETS WHAT ROLES
                        await(NewMsg as SocketGuildChannel).Guild.GetTextChannel(ServerConfigData.PointersAnonChatID["Bot History"]).SendMessageAsync($"User <@{react.UserId}> removed role {EmoteData.Key}");
                        return;
                    }
                }

                return;
            }


            foreach (BulletinEvent bulletinEvent in Program.BulletinBoardData.BulletinEvents)
            {
                if (MessageID == bulletinEvent.MsgID && react.UserId != Program.ServerConfigData.PointersAnonUserID["Quantum Bot"] && react.Emote.Equals(BulletinBoardData.BulletinAttendingEmote))
                {
                    if (bulletinEvent.AttendingUsers.Contains(react.UserId) == true)
                    {
                        bulletinEvent.AttendingUsers.Remove(react.UserId);
                        await(NewMsg as SocketGuildChannel).Guild.GetTextChannel(ServerConfigData.PointersAnonChatID["Bot History"]).SendMessageAsync($"User <@{react.UserId}> is no longer going to the Event \"{bulletinEvent.Title}\"");
                    }

                    var builder = new EmbedBuilder()
                                  .WithTitle(bulletinEvent.Title)
                                  .WithUrl($"{bulletinEvent.EventURL}")
                                  .WithColor(new Color(0, 0, 255))
                                  .WithDescription($"{bulletinEvent.Description}")
                                  .WithThumbnailUrl($"{bulletinEvent.IconURL}")
                                  .AddField($"Time", bulletinEvent.EventDate.ToString("MMMM d yyyy \ndddd h:mm tt"), true)
                                  .AddField($"Location", $"{bulletinEvent.Location}", true)
                                  .AddField($"Cost", $"{bulletinEvent.Cost}", true)
                                  .AddField($"Capacity", $"{bulletinEvent.Capacity}", true)
                                  .AddField($"Attending", $"{bulletinEvent.AttendingUsers.Count}", true)
                                  .WithFooter($"By {(await NewMsg.GetUserAsync(bulletinEvent.author) as SocketGuildUser).Nickname}", $"{bulletinEvent.authorIconURL}")
                                  .WithTimestamp(bulletinEvent.embedCreated);

                    var embed = builder.Build();

                    var msg = await NewMsg.GetMessageAsync(MessageID) as IUserMessage;

                    await msg.ModifyAsync(x => x.Embed = embed);

                    //add atending emote
                    SaveBulletinBoardDataToFile();
                    await msg.AddReactionAsync(BulletinBoardData.BulletinAttendingEmote);

                    return;
                }
            }
        }
示例#18
0
文件: Program.cs 项目: Xwilarg/Hista
        private async Task ReactionAdded(Cacheable <IUserMessage, ulong> msg, ISocketMessageChannel chan, SocketReaction reaction)
        {
            if (roles.ContainsKey(reaction.Emote.Name))
            {
                var role = roles[reaction.Emote.Name];
                if (msg.Id == role.Item1)
                {
                    IGuildUser author = (IGuildUser)reaction.User.Value;
                    if (!author.RoleIds.Contains(role.Item2.Id))
                    {
                        await author.AddRoleAsync(role.Item2);
                    }
                }
            }
            if (factions.ContainsKey(reaction.Emote.Name))
            {
                var role = factions[reaction.Emote.Name];
                if (msg.Id == role.Item1)
                {
                    if (factionBlacklist.Contains(reaction.UserId)) // We ignore blacklisted users
                    {
                        await(await msg.GetOrDownloadAsync()).RemoveReactionAsync(reaction.Emote, reaction.User.Value);
                        return;
                    }
                    IGuildUser author = (IGuildUser)reaction.User.Value;
                    foreach (var elem in factions) // If the user was already in another faction
                    {
                        if (elem.Key == reaction.Emote.Name)
                        {
                            continue;
                        }
                        var elemMsg = (IUserMessage)await chan.GetMessageAsync(elem.Value.Item1);

                        KeyValuePair <IEmote, ReactionMetadata>?react = elemMsg.Reactions.FirstOrDefault(x => x.Value.IsMe && x.Key.Name == elem.Key);
                        if (react != null)
                        {
                            await author.RemoveRoleAsync(elem.Value.Item2);

                            await elemMsg.RemoveReactionAsync(react.Value.Key, reaction.User.Value);

                            break;
                        }
                    }
                    if (!author.RoleIds.Contains(role.Item2.Id))
                    {
                        await author.AddRoleAsync(role.Item2);
                    }
                    if (defaultFactions.ContainsKey(author.GuildId))
                    {
                        ulong id = defaultFactions[author.GuildId].Id;
                        if (author.RoleIds.Any(x => x == id))
                        {
                            await author.RemoveRoleAsync(defaultFactions[author.GuildId]);
                        }
                    }
                }
            }
        }
示例#19
0
        private async Task _client_ReactionAdded(Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
        {
            var amount = 0;

            if (arg3.Emote.Name == "10")
            {
                amount = 10;
            }

            if (arg3.Emote.Name == "50")
            {
                amount = 50;
            }

            if (amount == 0)
            {
                return;
            }

            var message = await arg2.GetMessageAsync(arg3.MessageId);

            var toId   = message.Author.Id;
            var fromId = arg3.UserId;

            //if(toId == fromId)
            //{
            //    return;
            //}

            IDMChannel fromDmChannel = null;

            if (arg3.User.IsSpecified)
            {
                fromDmChannel = await arg3.User.Value.GetOrCreateDMChannelAsync();
            }
            else
            {
                var user = await _rclient.GetUserAsync(fromId);

                fromDmChannel = await user.GetOrCreateDMChannelAsync();
            }
            var toDmChannel = await message.Author.GetOrCreateDMChannelAsync();



            using (var scope = Services.CreateScope())
            {
                var service = ActivatorUtilities.CreateInstance <ReactionSendService>(scope.ServiceProvider);
                await service.SendCoin(fromId, toId, amount, fromDmChannel, toDmChannel);
            }


            //arg2.GetMessageAsync()
            await Task.Yield();

            Console.WriteLine();
        }
示例#20
0
        public async Task <IMessage> GetMessage(ulong messageId, ISocketMessageChannel channel)
        {
            if (testMode)
            {
                return(null);
            }

            return(await channel.GetMessageAsync(messageId));
        }
示例#21
0
        private async Task OnReactionsClearedAsync(Cacheable <IUserMessage, UInt64> cachedMessage, ISocketMessageChannel channel)
        {
            var message = cachedMessage.HasValue
                ? cachedMessage.Value
                : await channel.GetMessageAsync(cachedMessage.Id) as IUserMessage;

            var emojis = this._userRoles.Where(r => r.MessageId == message.Id)
                         .Select(r => r.EmojiId.HasValue ? (IEmote)Emote.Parse($"<:rs:{r.EmojiId}>") : new Emoji(r.EmojiName));

            await message.AddReactionsAsync(emojis.ToArray());
        }
示例#22
0
        protected override async Task HandleReactionAsync(
            Cacheable <IUserMessage, ulong> cachedMessage,
            ISocketMessageChannel channel,
            SocketReaction reaction)
        {
            var message = await channel.GetMessageAsync(reaction.MessageId).ConfigureAwait(false);

            if (message is RestUserMessage userMessage)
            {
                await SendToBestChannelAsync(userMessage).ConfigureAwait(false);
            }
        }
示例#23
0
        private Task HandleUpdate(Cacheable <IMessage, ulong> before, SocketMessage after, ISocketMessageChannel channel)
        {
            if (!(after is SocketUserMessage afterSocket))
            {
                return(Task.CompletedTask);
            }
            _ = Task.Run(async() =>
            {
                ulong?id;
                if ((id = GetOurMessageIdFromCache(before.Id)) != null)
                {
                    var botMessage = await channel.GetMessageAsync(id.Value) as IUserMessage;
                    if (botMessage == null)
                    {
                        return;
                    }
                    int argPos = 0;
                    if (!afterSocket.HasMentionPrefix(_client.CurrentUser, ref argPos))
                    {
                        return;
                    }
                    var reply = await BuildReply(afterSocket, after.Content.Substring(argPos));

                    if (reply.Item1 == null && reply.Item2 == null && reply.Item3 == null)
                    {
                        return;
                    }
                    var pagination         = (PaginationService)_services.GetService(typeof(PaginationService));
                    var isPaginatedMessage = pagination.IsPaginatedMessage(id.Value);
                    if (reply.Item3 != null)
                    {
                        if (isPaginatedMessage)
                        {
                            await pagination.UpdatePaginatedMessageAsync(botMessage, reply.Item3);
                        }
                        else
                        {
                            await pagination.EditMessageToPaginatedMessageAsync(botMessage, reply.Item3);
                        }
                    }
                    else
                    {
                        if (isPaginatedMessage)
                        {
                            pagination.StopTrackingPaginatedMessage(id.Value);
                            _ = botMessage.RemoveAllReactionsAsync();
                        }
                        await botMessage.ModifyAsync(x => { x.Content = reply.Item1; x.Embed = reply.Item2?.Build(); });
                    }
                }
            });
            return(Task.CompletedTask);
        }
示例#24
0
        private Task OnMessageModified(Cacheable <IMessage, ulong> cacheable, SocketMessage after, ISocketMessageChannel channel)
        {
            _ = Task.Run(async() =>
            {
                // Prevent the double reply that happens when the message is "updated" with an embed or image/video preview.
                if (string.IsNullOrEmpty(after?.Content) || after.Source != MessageSource.User)
                {
                    return;
                }
                IMessage before = cacheable.Value;
                if (string.IsNullOrEmpty(before?.Content) || before.Content == after.Content)
                {
                    return;
                }

                if (TryGetValue(cacheable.Id, out ulong responseId))
                {
                    var response = await channel.GetMessageAsync(responseId);
                    if (response == null)
                    {
                        await _logger(new LogMessage(LogSeverity.Warning, "CmdCache", $"A command message ({cacheable.Id}) associated to a response was found but the response ({responseId}) was already deleted."));
                        TryRemove(cacheable.Id);
                    }
                    else
                    {
                        if (response.Attachments.Count > 0)
                        {
                            await _logger(new LogMessage(LogSeverity.Verbose, "CmdCache", $"Attachment found on response ({responseId}). Deleting the response..."));
                            _ = response.DeleteAsync();
                            TryRemove(cacheable.Id);
                        }
                        else
                        {
                            await _logger(new LogMessage(LogSeverity.Verbose, "CmdCache", $"Found a response associated to command message ({cacheable.Id}) in cache."));
                            if (response.Reactions.Count > 0)
                            {
                                bool manageMessages = response.Author is IGuildUser guildUser && guildUser.GetPermissions((IGuildChannel)response.Channel).ManageMessages;

                                if (manageMessages)
                                {
                                    await _logger(new LogMessage(LogSeverity.Verbose, "CmdCache", $"Removing all reactions from response ({responseId})..."));
                                    await response.RemoveAllReactionsAsync();
                                }
                            }
                        }
                    }
                }
                _ = _cmdHandler(after);
            });

            return(Task.CompletedTask);
        }
示例#25
0
文件: Program.cs 项目: otooleam/Nona
        /// <summary>
        /// Handles the Reaction Added event.
        /// </summary>
        /// <param name="cachedMessage">Message that was reaction is on.</param>
        /// <param name="originChannel">Channel where the message is located.</param>
        /// <param name="reaction">Reaction made on the message.</param>
        /// <returns>Task Complete.</returns>
        private async Task <Task> HandleReactionAdded(Cacheable <IUserMessage, ulong> cachedMessage,
                                                      ISocketMessageChannel originChannel, SocketReaction reaction)
        {
            IMessage message = await originChannel.GetMessageAsync(cachedMessage.Id);

            SocketGuildChannel chnl = message.Channel as SocketGuildChannel;
            ulong guild             = chnl.Guild.Id;

            IUser user = reaction.User.Value;


            if (message != null && reaction.User.IsSpecified && !user.IsBot)
            {
                if (RaidCommandParent.IsRaidMessage(message.Id))
                {
                    await RaidCommandParent.RaidMessageReactionHandle(message, reaction);
                }
                else if (RaidCommandParent.IsRaidSubMessage(message.Id))
                {
                    await RaidCommandParent.RaidSubMessageReactionHandle(message, reaction);
                }
                else if (RaidCommandParent.IsRaidGuideMessage(message.Id))
                {
                    await RaidCommandParent.RaidGuideMessageReactionHandle(message, reaction);
                }
                else if (DexCommandParent.IsDexSelectMessage(message.Id))
                {
                    await DexCommandParent.DexSelectMessageReactionHandle(message, reaction, guild);
                }
                else if (DexCommandParent.IsDexMessage(message.Id))
                {
                    await DexCommandParent.DexMessageReactionHandle(message, reaction, guild);
                }
                else if (DexCommandParent.IsCatchMessage(message.Id))
                {
                    await DexCommandParent.CatchMessageReactionHandle(message, reaction);
                }
                else if (POICommands.IsPOISubMessage(message.Id))
                {
                    await POICommands.POIMessageReactionHandle(message, reaction, guild);
                }
                else if (HelpCommands.IsHelpMessage(message.Id))
                {
                    await HelpCommands.HelpMessageReactionHandle(message, reaction, guild);
                }
                else if (Connections.IsNotifyMessage(message.Id))
                {
                    await Connections.NotifyMessageReactionHandle(message, reaction, chnl.Guild);
                }
            }
            return(Task.CompletedTask);
        }
示例#26
0
        public async Task Handle(Cacheable <IUserMessage, ulong> msg, ISocketMessageChannel chan, SocketReaction r)
        {
            if (r.UserId == Program._client.CurrentUser.Id)
            {
                return;
            }
            if (r.MessageId == BotConfig.GetCachedConfig().InternalMessageId)
            {
                if (r.Emote.Name == "🔄")
                {
                    var actualMessage = await chan.GetMessageAsync(r.MessageId);

                    await actualMessage.RemoveReactionAsync(r.Emote, r.UserId);

                    if (!debounce && !ServerStateManager.Instance().IsWorking) // ignore attempts to spam the button
                    {
                        debounce = true;
                        var status = await ServerStateManager.Instance().GetState();

                        if (status.InstanceState.Code == 80)
                        {
                            Console.WriteLine("User ID" + r.UserId + " initated a server start.");
                            ThreadPool.QueueUserWorkItem(async delegate
                            {
                                try
                                {
                                    await ServerStateManager.Instance().StartServer();
                                }
                                catch (AmazonEC2Exception e)
                                {
                                    Console.WriteLine("AWS threw an error.");
                                    Console.Write(e.Message);
                                    ServerStateManager.Instance().IsWorking = false;
                                    await Embeds.EditMessage(Embeds.ServerStopped("The server could not be started previously due to an error. Please wait a bit and try again, or ask an admin if this persists. This mainly happens after starting a server when it's just been stopped."));
                                }
                            });
                        }
                        else
                        {
                            Console.WriteLine("Rejecting refresh as server is not stopped.");
                            if (Program._client.GetUser(r.UserId) != null)
                            {
                                var usr = await chan.GetUserAsync(r.UserId);

                                await usr.SendMessageAsync(embed : Embeds.Error("The server must be stopped for the refresh button to work."));
                            }
                        }
                        debounce = false;
                    }
                }
            }
        }
示例#27
0
        public static async Task deleteMessageWithId(ISocketMessageChannel channel, ulong id)
        {
            if (id == 0 || channel == null)
            {
                return;
            }
            var msg = await channel.GetMessageAsync(id);

            if (msg != null)
            {
                await msg.DeleteAsync();
            }
        }
示例#28
0
        public async Task Update(string messageID, string update)
        {
            var message = await _responseChannel.GetMessageAsync(Convert.ToUInt64(messageID));

            if (message is RestUserMessage rumess)
            {
                var embed = DiscordHelper.CreateEmbeddedMessage(update);

                await rumess.ModifyAsync(msg => msg.Embed = embed);

                _lastMessagedInteractedWith = rumess;
            }
        }
示例#29
0
        public async Task UnpinEventMessage(ISocketMessageChannel channel, Event @event)
        {
            if (@event.MessageId == null)
            {
                return;
            }
            IUserMessage msg = ((IUserMessage)await channel.GetMessageAsync(Convert.ToUInt64(@event.MessageId)));

            if (msg != null)
            {
                await msg.UnpinAsync();
            }
        }
示例#30
0
        private async Task <Task> ClearReactionsAfterDelay(ISocketMessageChannel channel)
        {
            while (activeMBEmbeds.Count > 0)
            {
                Log.Write("MB Windows - Checking For Inactive MB Windows from total of " + activeMBEmbeds.Count, "Bot");

                DateTime runTime = DateTime.Now;

                foreach (KeyValuePair <ulong, ActiveMBWindow> mb in activeMBEmbeds)
                {
                    if ((runTime - mb.Value.LastInteractedWith).TotalSeconds > 20)
                    {
                        Log.Write("MB Windows - Clearing MB Command: " + mb.Key, "Bot");

                        IMessage message = await channel.GetMessageAsync(mb.Key);

                        // Convert to UserMessage so we can edit the embed to remove the react help message
                        if (message is IUserMessage userMessage)
                        {
                            // Get the embed and duplicate
                            IEmbed       embed   = message.Embeds.FirstOrDefault();
                            EmbedBuilder builder = new EmbedBuilder()
                                                   .WithTitle(embed.Title)
                                                   .WithColor(embed?.Color ?? Color.Teal)
                                                   .WithDescription(embed?.Description)
                                                   .WithThumbnailUrl(embed?.Thumbnail?.Url ?? string.Empty);

                            // Get MB field and duplicate - remove reaction hint text
                            EmbedField field = embed?.Fields.GetFirst() ?? default;
                            builder.AddField(new EmbedFieldBuilder()
                                             .WithName(field.Name)
                                             .WithValue(field.Value.Substring(0, field.Value.Length - 124)));

                            await userMessage.ModifyAsync(x => x.Embed = builder.Build());
                        }

                        // Remove reactions
                        await message.RemoveAllReactionsAsync();

                        activeMBEmbeds.Remove(mb.Key);
                    }
                }

                Log.Write("MB Windows - Begin Wait", "Bot");
                await Task.Delay(15000);
            }

            Log.Write("MB Windows - All MB Windows Inactive", "Bot");
            Program.DiscordClient.ReactionAdded -= this.OnReactionAdded;
            return(Task.CompletedTask);
        }