Esempio n. 1
0
 private async Task OnReactionAdded(Cacheable <IUserMessage, ulong> message, [NotNull] ISocketMessageChannel channel, [NotNull] SocketReaction reaction)
 {
     if (SentimentResponse.Happy.Contains(reaction.Emote.Name))
     {
         await TryLearn(await message.DownloadAsync(), reaction, Sentiment.Positive);
     }
     else if (SentimentResponse.Sad.Contains(reaction.Emote.Name))
     {
         await TryLearn(await message.DownloadAsync(), reaction, Sentiment.Negative);
     }
     else if (SentimentResponse.Neutral.Contains(reaction.Emote.Name))
     {
         await TryLearn(await message.DownloadAsync(), reaction, Sentiment.Neutral);
     }
 }
Esempio n. 2
0
        private async Task Client_ReactionRemoved(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel chan, SocketReaction reaction)
        {
            //for role removal after user unclicks a reaction.
            ulong reactionRole = DBTransaction.reactionRoleExists(reaction.MessageId, reaction.Emote.ToString());

            if (reactionRole != 0)
            {
                var message = await cache.DownloadAsync();

                //get guild to find role!
                var chnl         = message.Channel as SocketGuildChannel;
                var reactionUser = reaction.User.Value as IGuildUser;
                Console.WriteLine("Removing role from " + reaction.User.Value.Username + "!");
                try
                {
                    await reactionUser.RemoveRoleAsync(chnl.Guild.GetRole(reactionRole));
                }
                catch
                {
                    await reactionUser.SendMessageAsync("Sorry, something went wrong, I am either unable to modify roles or the chosen role is above me in settings. Contact an admin or Hoovier#4192 for assistance!");

                    return;
                }
                await reactionUser.SendMessageAsync("Hi " + reactionUser.Username + "! I removed the " + chnl.Guild.GetRole(reactionRole).Name + " role!");
            }
        }
Esempio n. 3
0
        private async Task HandleMessageDeleted(Cacheable <IMessage, ulong> cachedMessage, ISocketMessageChannel channel)
        {
            var old = cachedMessage.HasValue ? cachedMessage.Value : (await cachedMessage.DownloadAsync());

            if (old.Author.IsBot)
            {
                return;
            }

            var context      = new SocketCommandContext(client, old as SocketUserMessage);
            var logChannelId = await configRepo.GetLogChannel(context.Guild.Id);

            if (logChannelId == null)
            {
                return;
            }
            var logChannel = context.Guild.GetChannel(logChannelId.Value) as IMessageChannel;

            var embed = new EmbedBuilder();

            embed.Color = Color.Red;
            embed.WithDescription($"**Deleted**: {old.ToString()}");

            var user = old.Author;
            var text = $"{Formatter.NowBlock()} {Emotes.Cross} **{user.Username}**#{user.Discriminator} (ID: {user.Id})'s message has been deleted from <#{channel.Id}>:";

            await logChannel.SendMessageAsync(text : text, embed : embed.Build());
        }
Esempio n. 4
0
        async Task OnPhotoVoteReceivedAsync(Cacheable <IUserMessage, ulong> cacheable, ISocketMessageChannel channel,
                                            SocketReaction reaction)
        {
            var message = await cacheable.DownloadAsync();

            if (!message.Author.IsPhotoUser())
            {
                return;
            }

            var socketChannel = SocketGuild.GetTextChannel(channel.Id);

            if (socketChannel.Category.Id != Config.PhotoCategoryId)
            {
                return;
            }

            var photoMessage = Config.Photos.Find(element => element.MessageId == message.Id);

            if (photoMessage == null)
            {
                return;
            }

            if (reaction.Emote.IsUpvote())
            {
                photoMessage.Upvotes += 1;
            }
            if (reaction.Emote.IsDownvote())
            {
                photoMessage.Downvotes += 1;
            }

            await PhotoConfig.SaveAsync();
        }
Esempio n. 5
0
        public async void RemoveReactionPoints(IUser reactedUser, Cacheable <IUserMessage, ulong> messageWithReaction)
        {
            await Task.Run(async() =>
            {
                var receivingReactionUser = (await messageWithReaction.DownloadAsync()).Author;
                if (receivingReactionUser.IsBot)
                {
                    return;
                }
                if (receivingReactionUser.Id != reactedUser.Id)
                {
                    if (!DataControlManager.UserProfiles.Value.ContainsKey(receivingReactionUser.Id))
                    {
                        DataControlManager.UserProfiles.Value.Add(receivingReactionUser.Id, new UserProfile(receivingReactionUser.Id));
                    }
                }
                await DataControlManager.UserProfiles.Value[receivingReactionUser.Id].RemovePoints((long)ActionsCost.ReceivedReaction);
                await DataControlManager.UserProfiles.SaveAsync();

                if (reactedUser.IsBot)
                {
                    return;
                }
                if (!DataControlManager.UserProfiles.Value.ContainsKey(reactedUser.Id))
                {
                    DataControlManager.UserProfiles.Value.Add(reactedUser.Id, new UserProfile(reactedUser.Id));
                }
                await DataControlManager.UserProfiles.Value[reactedUser.Id].RemovePoints((long)ActionsCost.LeftReaction);
            });
        }
Esempio n. 6
0
        private async Task OnReactionAdded(Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
        {
            var msg = await arg1.DownloadAsync();

            var user  = arg3.User.Value;
            var emote = arg3.Emote;

            if (BotReactions.ViewMessage.Equals(emote) && !user.IsBot)
            {
                if (msg.Author.Id == Client.CurrentUser.Id && msg.Embeds.Any())
                {
                    IEmbed encipheredEmbed = msg.Embeds.First();
                    if (encipheredEmbed.Fields.Any())
                    {
                        EmbedField field = encipheredEmbed.Fields[0];
                        if (field.Name == EncipheredTitle)
                        {
                            DateTime dateTime   = encipheredEmbed.Timestamp.Value.DateTime;
                            string   enciphered = Desanitize(field.Value);
                            string   deciphered = Decipher(enciphered, dateTime, false);

                            var          author = encipheredEmbed.Author.Value;
                            EmbedBuilder embed  = new EmbedBuilder();
                            embed.WithColor(EmbedColor);
                            embed.WithAuthor(author.Name, author.IconUrl, author.Url);
                            embed.WithTimestamp(encipheredEmbed.Timestamp.Value);
                            embed.AddField(DecipheredTitle, deciphered);
                            var dm = await arg3.User.Value.GetOrCreateDMChannelAsync();

                            await dm.SendMessageAsync(null, false, embed.Build());
                        }
                    }
                }
            }
        }
Esempio n. 7
0
        private async Task OnReactionAdded(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel ch, SocketReaction reaction)
        {
            var                 dlTasks = new List <Task>();
            IUserMessage        msg     = null;
            Task <IUserMessage> msgTask = null;

            if (cache.HasValue)
            {
                msg = cache.Value;
            }
            else
            {
                msgTask = cache.DownloadAsync();
                dlTasks.Add(msgTask);
            }

            IGuildUser   user     = null;
            Task <IUser> userTask = null;

            if (reaction.User.IsSpecified)
            {
                user = reaction.User.Value as IGuildUser;
            }
            else
            {
                userTask = ch.GetUserAsync(reaction.UserId);
                dlTasks.Add(userTask);
            }
            await Task.WhenAll(dlTasks);

            if (msg == null)
            {
                msg = await msgTask;
            }
            if (user == null)
            {
                user = await userTask as IGuildUser;
            }

            // Don't process bot reaction
            if (user.IsBot || user.IsWebhook)
            {
                return;
            }

            try{
                _logger.LogDebug($"{user.Username}#{user.Discriminator}> reaction {reaction.Emote.Name}");
                var code = _automuteService.GetVCLinkedGameCode(user.VoiceChannel);
                if (code is null)
                {
                    return;
                }
                await _automuteService.OnReactionAdded(msg, user, reaction, code);
            }catch (Exception e) {
                _logger.LogDebug($"{e.GetType()} -- {e.Message}");
                using (_logger.BeginScope("")){ _logger.LogDebug(e.StackTrace); }
            }
        }
Esempio n. 8
0
        private async Task OnReactionAdded(Cacheable <IUserMessage, ulong> cacheableMessage, ISocketMessageChannel channel,
                                           SocketReaction reaction)
        {
            var message = await cacheableMessage.DownloadAsync();

            // Check if reaction is for one of the bot's messages
            if (_client.CurrentUser.Id != message.Author.Id)
            {
                return;
            }

            // Check if reaction is from bot
            if (_client.CurrentUser.Id == reaction.UserId)
            {
                return;
            }

            if (!(message.Channel is SocketTextChannel guildChannel))
            {
                return;
            }

            var parts = reaction.Emote.ToString()?.Split(':') ?? new string[0];

            var isSubscribing   = reaction.Emote.Name == _configuration["UserUpdates:Reactions:Subscribe"];
            var isUnsubscribing = reaction.Emote.Name == _configuration["UserUpdates:Reactions:Unsubscribe"];

            // Check if emote means anything
            if (!isSubscribing && !isUnsubscribing)
            {
                return;
            }

            var roleName = _configuration["UserUpdates:RoleName"];

            IRole role = guildChannel.Guild.Roles.FirstOrDefault(x => x.Name == roleName);

            role ??= await guildChannel.Guild.CreateRoleAsync(roleName, GuildPermissions.None, isMentionable : false);

            if (role != null)
            {
                var user = guildChannel.Guild.GetUser(reaction.UserId);

                if (user != null)
                {
                    if (isSubscribing)
                    {
                        await user.AddRoleAsync(role);
                    }
                    else
                    {
                        await user.RemoveRoleAsync(role);
                    }
                }
            }

            await message.RemoveReactionAsync(reaction.Emote, reaction.UserId);
        }
Esempio n. 9
0
        public async Task OnMessageEdit(Cacheable <IMessage, ulong> cmessage, SocketMessage smessage, ISocketMessageChannel ichannel)
        {
            var newMessage = await cmessage.DownloadAsync();

            if (!(ichannel is SocketGuildChannel channel))
            {
                return;
            }

            var guild       = channel.Guild;
            var guildConfig = _db.Guilds.FirstOrDefault(g => g.Id == guild.Id);

            if (guildConfig == null)
            {
                return;
            }

            var run = _db.Events.FirstOrDefault(sr => sr.MessageId3 == newMessage.Id);

            if (run == null || run.RunTime < DateTime.Now.ToBinary())
            {
                return;
            }

            Log.Information("Updating information for run from user {UserId}.", run.LeaderId);

            var splitIndex = newMessage.Content.IndexOf("|", StringComparison.Ordinal);

            if (splitIndex == -1) // If for some silly reason they remove the pipe, it'll just take everything after the command name.
            {
                splitIndex = "~schedule ".Length;
            }
            run.Description = newMessage.Content.Substring(splitIndex + 1).Trim();
            await _db.UpdateScheduledEvent(run);

            var embedChannel = guild.GetTextChannel(run.RunKindCastrum == RunDisplayTypeCastrum.None ? guildConfig.ScheduleOutputChannel : guildConfig.CastrumScheduleOutputChannel);

            if (!(await embedChannel.GetMessageAsync(run.EmbedMessageId) is IUserMessage message))
            {
                return;
            }

            var embed = message.Embeds.FirstOrDefault()?.ToEmbedBuilder()
                        .WithDescription("React to the :vibration_mode: on their message to be notified 30 minutes before it begins!\n\n" +
                                         $"**{guild.GetUser(run.LeaderId).Mention}'s full message: {newMessage.GetJumpUrl()}**\n\n" +
                                         $"{new string(run.Description.Take(1650).ToArray())}{(run.Description.Length > 1650 ? "..." : "")}\n\n" +
                                         $"**Schedule Overview: <{(run.RunKindCastrum == RunDisplayTypeCastrum.None ? guildConfig.BASpreadsheetLink : guildConfig.CastrumSpreadsheetLink)}>**")
                        .Build();

            Log.Information("Updated description for run {MessageId} to:\n{RunDescription}", run.MessageId3, new string(run.Description.Take(1800).ToArray()));

            if (embed == null)
            {
                return;
            }
            await message.ModifyAsync(properties => properties.Embed = embed);
        }
        public static async Task ClientOnReactionAdded(Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
        {
            // Get the message that was reacted to
            var msg = await arg1.DownloadAsync();

            // Ignore the reaction if the message wasn't posted by a bot
            if (msg.Source != MessageSource.Bot)
            {
                return;
            }

            // Verify permissions - must be in this role for reactions to be parsed
            if (!((SocketGuildUser)msg.Author).IsInRole("RoleBasedReactions"))
            {
                return;
            }

            // Do we recognise the emote/emoji?
            var translated = "";

            if (TranslateEmoji.ContainsKey(arg3.Emote.Name))
            {
                translated = TranslateEmoji[arg3.Emote.Name];
            }
            else
            {
                Console.WriteLine($"Unrecognised reaction: {arg3.Emote.Name}");
                return;
            }

            // Sanity check - make sure there is an embed in the message, that it has fields and found a match
            if (msg.Embeds.Count == 0 ||
                msg.Embeds.First().Fields.Length == 0 ||
                msg.Embeds.First().Fields.All(f => f.Name.Contains(translated) == false))
            {
                return;
            }


            var matchingField = msg.Embeds.First().Fields.FirstOrDefault(f => f.Name.Contains(translated));

            // Sanity check - make sure there's an @ in the field name, so that we can split on it.
            // This is added by the embed builder so it should be there, but check just in case someone borks something.
            if (!matchingField.Name.Contains("@"))
            {
                return;
            }

            var roleToAdd = matchingField.Name.Split("@")[1];
            var addResult = await RoleHelper.AddRole(roleToAdd, ((SocketTextChannel)msg.Channel).Guild,
                                                     (SocketGuildUser)arg3.User.Value);

            if (addResult.Success == false)
            {
                Console.WriteLine($"Failed to add role.. {addResult.Message}");
            }
        }
Esempio n. 11
0
        public async Task VerifyIdAsync(Cacheable <IUserMessage, ulong> message, ISocketMessageChannel channel,
                                        SocketReaction reaction)
        {
            if (!reaction.User.Value.IsAUser())
            {
                return;
            }

            if (reaction.Channel.Id == ulong.Parse(_config["ids:verificatielog"]))
            {
                Console.WriteLine("VerifyIdAsync");

                var guild           = _client.GetGuild(ulong.Parse(_config["ids:server"]));
                var studentRole     = guild.GetRole(ulong.Parse(_config["ids:studentrol"]));
                var notVerifiedRole = guild.GetRole(ulong.Parse(_config["ids:nietgeverifieerdrol"]));
                var embeds          = message.DownloadAsync().Result.Embeds.GetEnumerator();
                embeds.MoveNext();
                var isStudent = guild.GetUser(ulong.Parse(embeds.Current.Fields[0].Value)).Roles
                                .Contains(studentRole);
                if (!isStudent)
                {
                    if (reaction.Emote.ToString().Equals(Emojis.ACCEPTEER_EMOJI.ToString()) &&
                        !reaction.User.Value.IsBot)
                    {
                        var user = guild.GetUser(ulong.Parse(embeds.Current.Fields[0].Value));
                        await user.AddRoleAsync(studentRole);

                        await user.RemoveRoleAsync(notVerifiedRole);


                        var text = new StringBuilder();
                        text.Append("Jouw inzending werd zojuist goedgekeurd.");
                        text.AppendLine(
                            " Indien gewenst heb je nu de mogelijkheid om jouw verificatie-afbeelding te verwijderen.");
                        text.AppendLine(
                            "Naast deel te nemen van de server, heb je ook de mogelijkheid om deel te nemen aan de studentenvereniging van de richting! Neem eens een kijkje in onze #bovis-grafica kanaal voor meer informatie.");
                        text.Append(
                            " De volgende stap is het kiezen van jouw jaar  door te klikken op één (of meerdere) emoji onder dit bericht.");
                        text.Append(" Als je vakken moet meenemen, dan kan je ook het vorige jaar kiezen.");
                        text.Append(
                            " Als je geen kanalen meer wilt zien van een jaar, dan kan je gewoon opnieuw op de emoji ervan klikken.");
                        text.Append(
                            " Als je jaar niet verandert, dan is de sessie van deze chat verlopen en moet je de sessie terug activeren door `!jaar` te typen.");
                        var sent = await user.SendMessageAsync(text.ToString());

                        await sent.AddReactionsAsync(Emojis.emojiJaren);
                    }
                    else if (reaction.Emote.ToString().Equals(Emojis.WEIGER_EMOJI.ToString()) &&
                             !reaction.User.Value.IsBot)
                    {
                        await guild.GetUser(ulong.Parse(embeds.Current.Fields[0].Value))
                        .SendMessageAsync("Jouw inzending werd afgekeurd. Dien een nieuwe foto in.");
                    }
                }
            }
        }
Esempio n. 12
0
        public static async Task UpdateSettingMessage(Cacheable <IUserMessage, ulong> Data)
        {
            if (!_SettingMessageIds.Contains(Data.Id))
            {
                return;                                        // Not bothered about random reactions
            }
            var RelevantSetting = _AllSettings.Where(s => s.Message.Id == Data.Id).FirstOrDefault();

            RelevantSetting.Message = await Data.DownloadAsync(); // Update message
        }
        public static async Task ReactionAddedFor2048(Cacheable <IUserMessage, ulong> cash, ISocketMessageChannel channel,
                                                      SocketReaction reaction)
        {
            for (var i = 0; i < Global.OctopusGameMessIdList2048.Count; i++)
            {
                if (reaction.MessageId == Global.OctopusGameMessIdList2048[i].OctoGameMessIdToTrack2048 && reaction.UserId == Global.OctopusGameMessIdList2048[i].OctoGameUserIdToTrack2048 &&
                    reaction.UserId != 423593006436712458) //Id for bot
                {
                    switch (reaction.Emote.Name)
                    {
                    case "⬆":
                        NewGame.MakeMove(reaction.UserId, GameWork.MoveDirection.Up, Global.OctopusGameMessIdList2048[i].SocketMsg);
                        await Global.OctopusGameMessIdList2048[i].SocketMsg.RemoveReactionAsync(reaction.Emote, Global.OctopusGameMessIdList2048[i].Iuser, RequestOptions.Default);
                        break;

                    case "⬇":
                        NewGame.MakeMove(reaction.UserId, GameWork.MoveDirection.Down, Global.OctopusGameMessIdList2048[i].SocketMsg);
                        await Global.OctopusGameMessIdList2048[i].SocketMsg.RemoveReactionAsync(reaction.Emote, Global.OctopusGameMessIdList2048[i].Iuser, RequestOptions.Default);
                        break;

                    case "⬅":
                        NewGame.MakeMove(reaction.UserId, GameWork.MoveDirection.Left, Global.OctopusGameMessIdList2048[i].SocketMsg);
                        await Global.OctopusGameMessIdList2048[i].SocketMsg.RemoveReactionAsync(reaction.Emote, Global.OctopusGameMessIdList2048[i].Iuser, RequestOptions.Default);
                        break;

                    case "➡":
                        NewGame.MakeMove(reaction.UserId, GameWork.MoveDirection.Right, Global.OctopusGameMessIdList2048[i].SocketMsg);
                        await Global.OctopusGameMessIdList2048[i].SocketMsg.RemoveReactionAsync(reaction.Emote, Global.OctopusGameMessIdList2048[i].Iuser, RequestOptions.Default);
                        break;

                    case "❌":
                        NewGame.EndGame(reaction.UserId);
                        break;

                    case "🔃":
                        await cash.DownloadAsync().Result.RemoveAllReactionsAsync();

                        await cash.DownloadAsync().Result.AddReactionAsync(new Emoji("⬅"));

                        await cash.DownloadAsync().Result.AddReactionAsync(new Emoji("➡"));

                        await cash.DownloadAsync().Result.AddReactionAsync(new Emoji("⬆"));

                        await cash.DownloadAsync().Result.AddReactionAsync(new Emoji("⬇"));

                        await cash.DownloadAsync().Result.AddReactionAsync(new Emoji("🔃"));

                        await cash.DownloadAsync().Result.AddReactionAsync(new Emoji("❌"));

                        break;

                    default:
                        return;
                    }
                }
            }
            await Task.CompletedTask;
        }
Esempio n. 14
0
        private async Task OnReactionAdded(Cacheable<IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
        {
            if (arg3.UserId == _client.CurrentUser.Id) return;

            var message = await arg1.DownloadAsync();
            IUser user = await message.Channel.GetUserAsync(arg3.UserId).ConfigureAwait(false);


            await HandleExtraReactionMethodsAsync(arg1.Id, arg3, user, message).ConfigureAwait(false);
        }
Esempio n. 15
0
        private async Task ClientOnReactionAdded(Cacheable <IUserMessage, ulong> x, ISocketMessageChannel chanel,
                                                 SocketReaction reaction)
        {
            if (reaction.UserId == _client.CurrentUser.Id)
            {
                return;
            }
            var um = await x.DownloadAsync();

            if (reaction.Emote.Name == new Emoji("🌀").Name)
            {
                if (um.Author.Id == _client.CurrentUser.Id && um.Attachments.Count != 0)
                {
                    await um.RemoveAllReactionsAsync();

                    await um.AddReactionAsync(new Emoji("⬅️"));

                    await um.AddReactionAsync(new Emoji("⬆️"));

                    await um.AddReactionAsync(new Emoji("➡️"));

                    await um.AddReactionAsync(new Emoji("⬇️"));

                    await um.AddReactionAsync(new Emoji("↖️"));

                    await um.AddReactionAsync(new Emoji("↗️"));

                    await um.AddReactionAsync(new Emoji("↘️"));

                    await um.AddReactionAsync(new Emoji("↙️"));
                }
            }
            else
            {
                await um.RemoveReactionAsync(reaction.Emote, um.Author);

                var dict = new Dictionary <string, string>()
                {
                    { new Emoji("⬅️️").Name, "#move w" },
                    { new Emoji("⬆").Name, "#move n" },
                    { new Emoji("➡️").Name, "#move e" },
                    { new Emoji("⬇️").Name, "#move s" },

                    { new Emoji("↖️").Name, "#move nw" },
                    { new Emoji("↗️").Name, "#move ne" },
                    { new Emoji("↘️").Name, "#move se" },
                    { new Emoji("↙️").Name, "#move sw" },
                };

                RunCmd(dict[reaction.Emote.Name], reaction.User.Value, um);
            }
        }
        public async Task OnMessageUpdated(Cacheable <IMessage, ulong> _OldMsg, SocketMessage NewMsg, ISocketMessageChannel Channel)
        {
            var OldMsg = await _OldMsg.DownloadAsync();

            if (OldMsg == null || NewMsg == null)
            {
                return;
            }
            if (OldMsg.Source != MessageSource.User || NewMsg.Source != MessageSource.User)
            {
                return;
            }
            await MessageReceived(NewMsg);
        }
        private async Task ReactionChangedAsync(Cacheable <IUserMessage, ulong> cached, ISocketMessageChannel channel, SocketReaction reaction, bool added)
        {
            // If this reaction wasn't performed on a paginated message, quit.

            if (!paginatedMessages.ContainsKey(reaction.MessageId))
            {
                return;
            }

            // If the reaction was added by the bot, quit.

            if (reaction.UserId == client.CurrentUser.Id)
            {
                return;
            }

            // Get the paginated message.

            PaginatedMessageInfo messageInfo = paginatedMessages[reaction.MessageId];

            if (!messageInfo.Message.Enabled)
            {
                return;
            }

            // Ignore the reaction if it's not from the sender and we only accept reactions from the sender.

            if (messageInfo.Message.Restricted && reaction.UserId != messageInfo.Context.User.Id)
            {
                return;
            }

            string emoji = reaction.Emote.Name;

            Messaging.IMessage currentPage = messageInfo.Message.CurrentPage;

            await messageInfo.Message.HandleReactionAsync(new PaginatedMessageReactionArgs(messageInfo.Message, emoji, added));

            if (currentPage != messageInfo.Message.CurrentPage)
            {
                await cached.DownloadAsync().Result.ModifyAsync(msg => {
                    msg.Content = messageInfo.Message.CurrentPage.Text;
                    msg.Embed   = messageInfo.Message.CurrentPage.Embed.ToDiscordEmbed();
                });
            }

            // If the message was blocking, unblock it.

            messageInfo.Waiter?.Set();
        }
Esempio n. 18
0
        private async Task ReactionAddedAsync(Cacheable <IUserMessage, ulong> cachedMsg, ISocketMessageChannel channel, SocketReaction addedReaction)
        {
            var msg = await cachedMsg.DownloadAsync();

            if (msg == null)
            {
                return;
            }

            IChannelHandler handler = ChannelHandlers.ContainsKey(msg.Channel.Name) ? ChannelHandlers[msg.Channel.Name] : DefaultHandler;
            var             context = new ReactionContext(Context, msg);

            await handler.ReactionAdded(context, addedReaction);
        }
Esempio n. 19
0
        private async Task OnReactionRemoved(Cacheable<IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
        {
            if (arg3.UserId == _client.CurrentUser.Id) return;

            DBConfigSettings config = _db.ConfigSettings.Find("Channels", "Log");
            if (config != null)
            {
                ulong channelId = MakeNumeric(config.Value);
                var message = await arg1.DownloadAsync();

                CommandContext context = new CommandContext(_client, message);
                var channel = await context.Guild.GetTextChannelAsync(channelId);

                await channel.SendMessageAsync($"Reaction: {arg3.Emote} removed from message {message.Id} by <@!{arg3.UserId}>!\r\nLink: https://discordapp.com/channels/{context.Guild.Id}/{message.Channel.Id}/{message.Id}");
            }
        }
Esempio n. 20
0
        private async Task ReactionRemoved(Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
        {
            var msg = await arg1.DownloadAsync();

            if (Message == null || msg.Id != Message.Id)
            {
                return;
            }

            if (arg3.User.Value.Id != msg.Author.Id)
            {
                if (ButtonPressed != null)
                {
                    await ButtonPressed(this, new ButtonPressEventArgs(arg3.User.Value, arg3.Emote.Name));
                }
            }
        }
Esempio n. 21
0
        private static async Task OnReactionAdded(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction reaction)
        {
            if (reaction.User.Value.IsBot)
            {
                return;
            }
            IUserMessage msg = await cache.DownloadAsync();

            foreach (IReactionAction action in AddReactionActions)
            {
                if (action.ActionApplies(msg, channel, reaction))
                {
                    await action.Execute(msg, channel, reaction);

                    break;
                }
            }
        }
Esempio n. 22
0
        private async Task ReactionRemoved(
            Cacheable <IUserMessage, ulong> message,
            ISocketMessageChannel channel,
            SocketReaction reaction)
        {
            if (this.ActionFromBot(reaction.UserId))
            {
                return;
            }

            if (this.messageTracker.TryGetGroup(message.Id, out var groupState))
            {
                await groupState.ReactionRemoved(message, channel, reaction);
            }
            var fullMessage = await message.DownloadAsync();

            await fullMessage.ModifyAsync(x => x.Content = this.BuildInProgressMessage(groupState));
        }
        public async Task OnMessageUpdated(Cacheable <IMessage, ulong> _OldMsg, SocketMessage NewMsg, ISocketMessageChannel Channel)
        {
            var OldMsg = await _OldMsg.DownloadAsync();

            if (OldMsg.Source != MessageSource.User)
            {
                return;
            }


            if (_cache.TryGetValue(NewMsg.Id, out var CacheMsg))
            {
                var reply = await Channel.GetMessageAsync(CacheMsg.First());

                await reply.DeleteAsync();
            }
            await MessageReceived(NewMsg);
        }
Esempio n. 24
0
        private async Task _client_ReactionAdded(
            Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3
            )
        {
            var curratedReactions = new string[] { check.Name, cross.Name };

            if (!_messages.Select(m => m.MessageID).Contains(arg1.Id))
            {
                return;
            }

            if (arg3.User.Value.IsBot || !curratedReactions.Contains(arg3.Emote.Name))
            {
                return;
            }

            HandleMessage(arg1.DownloadAsync().Result, arg3.Emote);
        }
Esempio n. 25
0
        private async Task ClientOnReactionAdded(Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
        {
            try
            {
                if (arg3.UserId != _client.CurrentUser.Id && arg3.Channel.Id == _triggersChannelId &&
                    arg3.Emote.Name == subscribeEmoji.Name)
                {
                    var msg = await arg1.DownloadAsync();

                    IRole role = _guild.Roles.FirstOrDefault(r => r.Name == msg.Content);
                    await _guild.GetUser(arg3.UserId).AddRoleAsync(role);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Esempio n. 26
0
        private async Task ReactionAdded(Cacheable <IUserMessage, ulong> message, ISocketMessageChannel channel, SocketReaction reaction)
        {
            try
            {
                // Try get reaction role
                ReactionRole reactionRole = await this.GetReactionRoleIfValid(message, channel, reaction);

                // Reaction Role not found or no Reactions - skip
                if (reactionRole == null || !reactionRole.Reactions.Any())
                {
                    return;
                }

                // If Item matching added Reaction doesn't exist for reaction role - skip
                ReactionRoleItem item = reactionRole.Reactions.FirstOrDefault(x => x.ReactionEmote.Name == reaction.Emote.Name && x.Role != null);
                if (item == null)
                {
                    return;
                }

                // Need to fetch message and guild to get user and role
                IUserMessage userMessage = await message.DownloadAsync();

                IGuild     guild = userMessage.GetGuild();
                IGuildUser user  = await guild.GetUserAsync(reaction.UserId);

                IRole role = guild.GetRole(item.Role.GetValueOrDefault());
                if (role != null)
                {
                    if (!user.RoleIds.Contains(role.Id))
                    {
                        await user.AddRoleAsync(role);
                    }
                }
            }
            catch (Exception ex)
            {
                await Utils.Logger.LogExceptionToDiscordChannel(
                    ex,
                    $"Role Reaction Added - MessageId: {message.Id}",
                    (channel as IGuildChannel)?.GuildId.ToString(),
                    (reaction.User.GetValueOrDefault() as IGuildUser)?.GetName());
            }
        }
Esempio n. 27
0
        async Task OnProposalVoteReceivedAsync(Cacheable <IUserMessage, ulong> cacheable, ISocketMessageChannel channel, SocketReaction reaction)
        {
            var message = await cacheable.DownloadAsync();

            if (!message.Author.IsPhotoUser())
            {
                return;
            }

            var socketChannel = SocketGuild.GetTextChannel(channel.Id);

            if (socketChannel.Category.Id != Config.PhotoCategoryId)
            {
                return;
            }

            var proposal = Config.Proposals.Find(element => element.UserId == message.Author.Id);

            if (proposal == null)
            {
                return;
            }

            if (reaction.Emote.IsUpvote())
            {
                proposal.Upvotes += 1;
            }
            if (reaction.Emote.IsDownvote())
            {
                proposal.Downvotes += 1;
            }

            if (reaction.Emote.IsCancel())
            {
                if (reaction.User.Value.Id == message.Author.Id)
                {
                    var socketUser = SocketGuild.GetUser(reaction.User.Value.Id);
                    await DeleteProposalAsync(socketUser);
                }
            }

            await PhotoConfig.SaveAsync();
        }
Esempio n. 28
0
        private async Task OnReactionAddedAsync(Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
        {
            var msg = await arg1.DownloadAsync().ConfigureAwait(false);

            var user  = arg3.User.Value;
            var emote = arg3.Emote;

            if (EnigmaReactions.ViewMessage.Equals(emote) && !user.IsBot)
            {
                if (msg.Author.Id == Client.CurrentUser.Id && msg.Embeds.Any())
                {
                    IEmbed encipheredEmbed = msg.Embeds.First();
                    if (encipheredEmbed.Title == EncipheredTitle)
                    {
                        EmbedField field     = encipheredEmbed.Fields.FirstOrDefault();
                        RotorKeys  rotorKeys = this.rotorKeys;
                        if (encipheredEmbed.Fields.Any() && field.Name == RotorKeysTitle)
                        {
                            rotorKeys = ParseRotorKeys(field.Value);
                        }
                        Machine machine = new Machine(new SetupArgs {
                            LetterSet  = letterSet,
                            Steckering = steckering,
                            RotorKeys  = rotorKeys,
                        });
                        string enciphered = Desanitize(encipheredEmbed.Description);
                        string deciphered = machine.Decipher(enciphered);

                        var          author = encipheredEmbed.Author.Value;
                        EmbedBuilder embed  = new EmbedBuilder {
                            Title       = DecipheredTitle,
                            Color       = configParser.EmbedColor,
                            Timestamp   = encipheredEmbed.Timestamp.Value,
                            Description = deciphered,
                        };
                        embed.WithAuthor(author.Name, author.IconUrl, author.Url);
                        var dm = await arg3.User.Value.GetOrCreateDMChannelAsync().ConfigureAwait(false);

                        await dm.SendMessageAsync(embed : embed.Build()).ConfigureAwait(false);
                    }
                }
            }
        }
        internal static async Task Sc_ReactionRemoved(Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
        {
            try
            {
                IUserMessage msg = arg1.Value ?? await arg1.DownloadAsync();

                if (arg3.Emote.Name.Equals("⭐", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (msg.Author.Id != arg3.User.Value.Id)
                    {
                        await Starboard.UpdateStarGivenAsync(new StarboardContext(StarboardContextType.REACTION_REMOVED, msg), arg3.User.Value, false);
                    }
                }
            }
            catch (Exception ex)
            {
                Program.Log($"Exception in Sc_ReactionRemoved {ex.GetType().FullName}: {ex.Message}\n{ex.StackTrace}", LogSeverity.Error);
            }
        }
        private async Task OnMessageUpdate(Cacheable <IMessage, ulong> original, SocketMessage edit, ISocketMessageChannel channel)
        {
            if (edit == null)
            {
                return;
            }
            var msg = await original.DownloadAsync() as SocketUserMessage;

            var msg2   = edit as SocketUserMessage;
            int argPos = 0;

            if (msg2.HasStringPrefix(_config["prefix"], ref argPos))
            {
                var messages = await channel.GetMessagesAsync(msg, Direction.After, 2, CacheMode.AllowDownload).FlattenAsync();

                var lastreply = messages.Where(x => x.Author.Id == _discord.CurrentUser.Id).FirstOrDefault();
                await lastreply.DeleteAsync();
                await MessageReceived(edit);
            }
        }