Exemple #1
0
        private async Task MessageReceivedHandler(IMessage msg)
        {
            var usrMsg = msg as IUserMessage;

            if (usrMsg == null)
            {
                return;
            }

            if (usrMsg.Author.IsBot || !NadekoBot.Ready) //no bots
            {
                return;
            }

            var guild = (msg.Channel as ITextChannel)?.Guild;

            if (guild != null && guild.OwnerId != usrMsg.Author.Id)
            {
                if (Permissions.FilterCommands.InviteFilteringChannels.Contains(usrMsg.Channel.Id) ||
                    Permissions.FilterCommands.InviteFilteringServers.Contains(guild.Id))
                {
                    if (usrMsg.Content.IsDiscordInvite())
                    {
                        try
                        {
                            await usrMsg.DeleteAsync().ConfigureAwait(false);

                            return;
                        }
                        catch (HttpException ex)
                        {
                            _log.Warn("I do not have permission to filter invites in channel with id " + usrMsg.Channel.Id, ex);
                        }
                    }
                }

                var filteredWords  = Permissions.FilterCommands.FilteredWordsForChannel(usrMsg.Channel.Id, guild.Id).Concat(Permissions.FilterCommands.FilteredWordsForServer(guild.Id));
                var wordsInMessage = usrMsg.Content.ToLowerInvariant().Split(' ');
                if (filteredWords.Any(w => wordsInMessage.Contains(w)))
                {
                    try
                    {
                        await usrMsg.DeleteAsync().ConfigureAwait(false);

                        return;
                    }
                    catch (HttpException ex)
                    {
                        _log.Warn("I do not have permission to filter words in channel with id " + usrMsg.Channel.Id, ex);
                    }
                }
            }

            BlacklistItem blacklistedItem;

            if ((blacklistedItem = Permissions.BlacklistCommands.BlacklistedItems.FirstOrDefault(bi =>
                                                                                                 (bi.Type == BlacklistItem.BlacklistType.Server && bi.ItemId == guild?.Id) ||
                                                                                                 (bi.Type == BlacklistItem.BlacklistType.Channel && bi.ItemId == msg.Channel.Id) ||
                                                                                                 (bi.Type == BlacklistItem.BlacklistType.User && bi.ItemId == usrMsg.Author.Id))) != null)
            {
                return;
            }

            try
            {
                // maybe this message is a custom reaction
                var crExecuted = await CustomReactions.TryExecuteCustomReaction(usrMsg).ConfigureAwait(false);

                //if it was, don't execute the command
                if (crExecuted)
                {
                    return;
                }
            }
            catch { }

            var throwaway = Task.Run(async() =>
            {
                var sw = new Stopwatch();
                sw.Start();

                try
                {
                    var t         = await ExecuteCommand(usrMsg, usrMsg.Content, guild, usrMsg.Author, MultiMatchHandling.Best);
                    var command   = t.Item1;
                    var permCache = t.Item2;
                    var result    = t.Item3;
                    sw.Stop();
                    var channel = (usrMsg.Channel as ITextChannel);
                    if (result.IsSuccess)
                    {
                        CommandExecuted(this, new CommandExecutedEventArgs(usrMsg, command));
                        _log.Info("Command Executed after {4}s\n\t" +
                                  "User: {0}\n\t" +
                                  "Server: {1}\n\t" +
                                  "Channel: {2}\n\t" +
                                  "Message: {3}",
                                  usrMsg.Author + " [" + usrMsg.Author.Id + "]",                                      // {0}
                                  (channel == null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]"), // {1}
                                  (channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"),             // {2}
                                  usrMsg.Content,                                                                     // {3}
                                  sw.Elapsed.TotalSeconds                                                             // {4}
                                  );
                    }
                    else if (!result.IsSuccess && result.Error != CommandError.UnknownCommand)
                    {
                        _log.Warn("Command Errored after {5}s\n\t" +
                                  "User: {0}\n\t" +
                                  "Server: {1}\n\t" +
                                  "Channel: {2}\n\t" +
                                  "Message: {3}\n\t" +
                                  "Error: {4}",
                                  usrMsg.Author + " [" + usrMsg.Author.Id + "]",                                      // {0}
                                  (channel == null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]"), // {1}
                                  (channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"),             // {2}
                                  usrMsg.Content,                                                                     // {3}
                                  result.ErrorReason,                                                                 // {4}
                                  sw.Elapsed.TotalSeconds                                                             // {5}
                                  );
                        if (guild != null && command != null && result.Error == CommandError.Exception)
                        {
                            if (permCache != null && permCache.Verbose)
                            {
                                try { await msg.Channel.SendMessageAsync(":warning: " + result.ErrorReason).ConfigureAwait(false); } catch { }
                            }
                        }
                    }
                    else
                    {
                        if (msg.Channel is IPrivateChannel)
                        {
                            //rofl, gotta do this to prevent this message from occuring on polls
                            int vote;
                            if (int.TryParse(msg.Content, out vote))
                            {
                                return;
                            }

                            await msg.Channel.SendMessageAsync(Help.DMHelpString).ConfigureAwait(false);

                            await DMForwardCommands.HandleDMForwarding(msg, ownerChannels);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _log.Warn(ex, "Error in CommandHandler");
                    if (ex.InnerException != null)
                    {
                        _log.Warn(ex.InnerException, "Inner Exception of the error in CommandHandler");
                    }
                }
            });

            return;
        }
Exemple #2
0
        private async Task MessageReceivedHandler(SocketMessage msg)
        {
            try
            {
                if (msg.Author.IsBot || !NadekoBot.Ready) //no bots, wait until bot connected and initialized
                {
                    return;
                }

                var execTime = Environment.TickCount;

                var usrMsg = msg as SocketUserMessage;
                if (usrMsg == null) //has to be an user message, not system/other messages.
                {
                    return;
                }

                // track how many messagges each user is sending
                UserMessagesSent.AddOrUpdate(usrMsg.Author.Id, 1, (key, old) => ++ old);

                var channel = msg.Channel as SocketTextChannel;
                var guild   = channel?.Guild;

                if (guild != null && guild.OwnerId != msg.Author.Id)
                {
                    if (await InviteFiltered(guild, usrMsg).ConfigureAwait(false))
                    {
                        return;
                    }

                    if (await WordFiltered(guild, usrMsg).ConfigureAwait(false))
                    {
                        return;
                    }
                }

                if (IsBlacklisted(guild, usrMsg))
                {
                    return;
                }

                var cleverBotRan = await Task.Run(() => TryRunCleverbot(usrMsg, guild)).ConfigureAwait(false);

                if (cleverBotRan)
                {
                    return;
                }

                // maybe this message is a custom reaction
                var crExecuted = await Task.Run(() => CustomReactions.TryExecuteCustomReaction(usrMsg)).ConfigureAwait(false);

                if (crExecuted) //if it was, don't execute the command
                {
                    return;
                }

                string messageContent = usrMsg.Content;

                // execute the command and measure the time it took
                var exec = await Task.Run(() => ExecuteCommand(new CommandContext(_client, usrMsg), messageContent, DependencyMap.Empty, MultiMatchHandling.Best)).ConfigureAwait(false);

                execTime = Environment.TickCount - execTime;

                if (exec.Result.IsSuccess)
                {
                    await LogSuccessfulExecution(usrMsg, exec, channel, execTime).ConfigureAwait(false);
                }
                else if (!exec.Result.IsSuccess && exec.Result.Error != CommandError.UnknownCommand)
                {
                    LogErroredExecution(usrMsg, exec, channel, execTime);
                    if (guild != null && exec.CommandInfo != null && exec.Result.Error == CommandError.Exception)
                    {
                        if (exec.PermissionCache != null && exec.PermissionCache.Verbose)
                        {
                            try { await msg.Channel.SendMessageAsync("⚠️ " + exec.Result.ErrorReason).ConfigureAwait(false); } catch { }
                        }
                    }
                }
                else
                {
                    if (msg.Channel is IPrivateChannel)
                    {
                        // rofl, gotta do this to prevent dm help message being sent to
                        // users who are voting on private polls (sending a number in a DM)
                        int vote;
                        if (int.TryParse(msg.Content, out vote))
                        {
                            return;
                        }

                        await msg.Channel.SendMessageAsync(Help.DMHelpString).ConfigureAwait(false);

                        await DMForwardCommands.HandleDMForwarding(msg, ownerChannels).ConfigureAwait(false);
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Warn("Error in CommandHandler");
                _log.Warn(ex);
                if (ex.InnerException != null)
                {
                    _log.Warn("Inner Exception of the error in CommandHandler");
                    _log.Warn(ex.InnerException);
                }
            }
        }
        private async void MessageReceivedHandler(SocketMessage msg)
        {
            try
            {
                var usrMsg = msg as SocketUserMessage;
                if (usrMsg == null)
                {
                    return;
                }

                if (!usrMsg.IsAuthor())
                {
                    UserMessagesSent.AddOrUpdate(usrMsg.Author.Id, 1, (key, old) => ++ old);
                }

                if (msg.Author.IsBot || !NadekoBot.Ready) //no bots
                {
                    return;
                }

                var guild = (msg.Channel as SocketTextChannel)?.Guild;

                if (guild != null && guild.OwnerId != msg.Author.Id)
                {
                    //todo split checks into their own modules
                    if (Permissions.FilterCommands.InviteFilteringChannels.Contains(msg.Channel.Id) ||
                        Permissions.FilterCommands.InviteFilteringServers.Contains(guild.Id))
                    {
                        if (usrMsg.Content.IsDiscordInvite())
                        {
                            try
                            {
                                await usrMsg.DeleteAsync().ConfigureAwait(false);

                                return;
                            }
                            catch (HttpException ex)
                            {
                                _log.Warn("I do not have permission to filter invites in channel with id " + msg.Channel.Id, ex);
                            }
                        }
                    }

                    var filteredWords  = Permissions.FilterCommands.FilteredWordsForChannel(msg.Channel.Id, guild.Id).Concat(Permissions.FilterCommands.FilteredWordsForServer(guild.Id));
                    var wordsInMessage = usrMsg.Content.ToLowerInvariant().Split(' ');
                    if (filteredWords.Any(w => wordsInMessage.Contains(w)))
                    {
                        try
                        {
                            await usrMsg.DeleteAsync().ConfigureAwait(false);

                            return;
                        }
                        catch (HttpException ex)
                        {
                            _log.Warn("I do not have permission to filter words in channel with id " + msg.Channel.Id, ex);
                        }
                    }
                }

                BlacklistItem blacklistedItem;
                if ((blacklistedItem = Permissions.BlacklistCommands.BlacklistedItems.FirstOrDefault(bi =>
                                                                                                     (bi.Type == BlacklistItem.BlacklistType.Server && bi.ItemId == guild?.Id) ||
                                                                                                     (bi.Type == BlacklistItem.BlacklistType.Channel && bi.ItemId == msg.Channel.Id) ||
                                                                                                     (bi.Type == BlacklistItem.BlacklistType.User && bi.ItemId == msg.Author.Id))) != null)
                {
                    return;
                }
#if !GLOBAL_NADEKO
                try
                {
                    var cleverbotExecuted = await Games.CleverBotCommands.TryAsk(usrMsg);

                    if (cleverbotExecuted)
                    {
                        return;
                    }
                }
                catch (Exception ex) { _log.Warn(ex, "Error in cleverbot"); }
#endif
                try
                {
                    // maybe this message is a custom reaction
                    var crExecuted = await CustomReactions.TryExecuteCustomReaction(usrMsg).ConfigureAwait(false);

                    //if it was, don't execute the command
                    if (crExecuted)
                    {
                        return;
                    }
                }
                catch { }

                string messageContent = usrMsg.Content;

                var sw = new Stopwatch();
                sw.Start();
                var exec = await ExecuteCommand(new CommandContext(_client.MainClient, usrMsg), messageContent, DependencyMap.Empty, MultiMatchHandling.Best);

                var command   = exec.CommandInfo;
                var permCache = exec.PermissionCache;
                var result    = exec.Result;
                sw.Stop();
                var channel = (msg.Channel as ITextChannel);
                if (result.IsSuccess)
                {
                    await CommandExecuted(usrMsg, command);

                    _log.Info("Command Executed after {4}s\n\t" +
                              "User: {0}\n\t" +
                              "Server: {1}\n\t" +
                              "Channel: {2}\n\t" +
                              "Message: {3}",
                              msg.Author + " [" + msg.Author.Id + "]",                                            // {0}
                              (channel == null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]"), // {1}
                              (channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"),             // {2}
                              usrMsg.Content,                                                                     // {3}
                              sw.Elapsed.TotalSeconds                                                             // {4}
                              );
                }
                else if (!result.IsSuccess && result.Error != CommandError.UnknownCommand)
                {
                    _log.Warn("Command Errored after {5}s\n\t" +
                              "User: {0}\n\t" +
                              "Server: {1}\n\t" +
                              "Channel: {2}\n\t" +
                              "Message: {3}\n\t" +
                              "Error: {4}",
                              msg.Author + " [" + msg.Author.Id + "]",                                            // {0}
                              (channel == null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]"), // {1}
                              (channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"),             // {2}
                              usrMsg.Content,                                                                     // {3}
                              result.ErrorReason,                                                                 // {4}
                              sw.Elapsed.TotalSeconds                                                             // {5}
                              );
                    if (guild != null && command != null && result.Error == CommandError.Exception)
                    {
                        if (permCache != null && permCache.Verbose)
                        {
                            try { await msg.Channel.SendMessageAsync("⚠️ " + result.ErrorReason).ConfigureAwait(false); } catch { }
                        }
                    }
                }
                else
                {
                    if (msg.Channel is IPrivateChannel)
                    {
                        //rofl, gotta do this to prevent this message from occuring on polls
                        int vote;
                        if (int.TryParse(msg.Content, out vote))
                        {
                            return;
                        }

                        await msg.Channel.SendMessageAsync(Help.DMHelpString).ConfigureAwait(false);

                        await DMForwardCommands.HandleDMForwarding(msg, ownerChannels);
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Warn(ex, "Error in CommandHandler");
                if (ex.InnerException != null)
                {
                    _log.Warn(ex.InnerException, "Inner Exception of the error in CommandHandler");
                }
            }

            return;
        }