Ejemplo n.º 1
0
        public async Task TryRunCommand(SocketGuild guild, ITextChannel channel, IUserMessage usrMsg)
        {
            var execTime = Environment.TickCount;

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

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

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

            var exec1 = Environment.TickCount - execTime;


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

            if (cleverBotRan)
            {
                return;
            }

            var exec2 = Environment.TickCount - execTime;

            // maybe this message is a custom reaction
            // todo log custom reaction executions. return struct with info
            var cr = await Task.Run(() => CustomReactions.TryGetCustomReaction(usrMsg)).ConfigureAwait(false);

            if (cr != null) //if it was, don't execute the command
            {
                try
                {
                    if (guild != null)
                    {
                        PermissionCache pc = Permissions.GetCache(guild.Id);

                        int index;
                        if (
                            !pc.Permissions.CheckPermissions(usrMsg, cr.Trigger, "ActualCustomReactions",
                                                             out index))
                        {
                            //todo print in guild actually
                            var returnMsg =
                                $"Permission number #{index + 1} **{pc.Permissions[index].GetCommand(guild)}** is preventing this action.";
                            _log.Info(returnMsg);
                            return;
                        }
                    }
                    await cr.Send(usrMsg).ConfigureAwait(false);

                    if (cr.AutoDeleteTrigger)
                    {
                        try { await usrMsg.DeleteAsync().ConfigureAwait(false); } catch { }
                    }
                }
                catch (Exception ex)
                {
                    _log.Warn("Sending CREmbed failed");
                    _log.Warn(ex);
                }
                return;
            }

            var exec3 = Environment.TickCount - execTime;

            string messageContent = usrMsg.Content;

            if (guild != null)
            {
                ConcurrentDictionary <string, string> maps;
                if (Modules.Utility.Utility.CommandMapCommands.AliasMaps.TryGetValue(guild.Id, out maps))
                {
                    var keys = maps.Keys
                               .OrderByDescending(x => x.Length);

                    var lowerMessageContent = messageContent.ToLowerInvariant();
                    foreach (var k in keys)
                    {
                        string newMessageContent;
                        if (lowerMessageContent.StartsWith(k + " "))
                        {
                            newMessageContent = maps[k] + messageContent.Substring(k.Length, messageContent.Length - k.Length);
                        }
                        else if (lowerMessageContent == k)
                        {
                            newMessageContent = maps[k];
                        }
                        else
                        {
                            continue;
                        }

                        _log.Info(@"--Mapping Command--
    GuildId: {0}
    Trigger: {1}
    Mapping: {2}", guild.Id, messageContent, newMessageContent);
                        var oldMessageContent = messageContent;
                        messageContent = newMessageContent;

                        try { await usrMsg.Channel.SendConfirmAsync($"{oldMessageContent} => {newMessageContent}").ConfigureAwait(false); } catch { }
                        break;
                    }
                }
            }


            // 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 CommandExecuted(usrMsg, exec.CommandInfo).ConfigureAwait(false);
                await LogSuccessfulExecution(usrMsg, exec, channel, exec1, exec2, exec3, execTime).ConfigureAwait(false);
            }
            else if (!exec.Result.IsSuccess && exec.Result.Error != CommandError.UnknownCommand)
            {
                LogErroredExecution(usrMsg, exec, channel, exec1, exec2, exec3, execTime);
                if (guild != null && exec.CommandInfo != null && exec.Result.Error == CommandError.Exception)
                {
                    if (exec.PermissionCache != null && exec.PermissionCache.Verbose)
                    {
                        try { await usrMsg.Channel.SendMessageAsync("⚠️ " + exec.Result.ErrorReason).ConfigureAwait(false); } catch { }
                    }
                }
            }
            else
            {
                if (usrMsg.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(usrMsg.Content, out vote))
                    {
                        return;
                    }

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

                    await SelfCommands.HandleDmForwarding(usrMsg, ownerChannels).ConfigureAwait(false);
                }
            }
        }
Ejemplo n.º 2
0
        private Task MessageReceivedHandler(SocketMessage msg)
        {
            var _ = Task.Run(async() =>
            {
                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;
                    }

                    if (usrMsg.Author.Id == 193022505026453504)
                    {
                        return;
                    }
#if !GLOBAL_NADEKO
                    // track how many messagges each user is sending
                    UserMessagesSent.AddOrUpdate(usrMsg.Author.Id, 1, (key, old) => ++ old);
#endif

                    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 exec1 = Environment.TickCount - execTime;

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

                    var exec2 = Environment.TickCount - execTime;

                    // maybe this message is a custom reaction
                    // todo log custom reaction executions. return struct with info
                    var cr = await Task.Run(() => CustomReactions.TryGetCustomReaction(usrMsg)).ConfigureAwait(false);
                    if (cr != null) //if it was, don't execute the command
                    {
                        try
                        {
                            if (guild != null)
                            {
                                PermissionCache pc;
                                if (!Permissions.Cache.TryGetValue(guild.Id, out pc))
                                {
                                    using (var uow = DbHandler.UnitOfWork())
                                    {
                                        var config = uow.GuildConfigs.For(guild.Id,
                                                                          set => set.Include(x => x.Permissions));
                                        Permissions.UpdateCache(config);
                                    }
                                    Permissions.Cache.TryGetValue(guild.Id, out pc);
                                    if (pc == null)
                                    {
                                        throw new Exception("Cache is null.");
                                    }
                                }
                                int index;
                                if (
                                    !pc.Permissions.CheckPermissions(usrMsg, cr.Trigger, "ActualCustomReactions",
                                                                     out index))
                                {
                                    //todo print in guild actually
                                    var returnMsg =
                                        $"Permission number #{index + 1} **{pc.Permissions[index].GetCommand(guild)}** is preventing this action.";
                                    _log.Info(returnMsg);
                                    return;
                                }
                            }
                            await cr.Send(usrMsg).ConfigureAwait(false);

                            if (cr.AutoDeleteTrigger)
                            {
                                try { await msg.DeleteAsync().ConfigureAwait(false); } catch { }
                            }
                        }
                        catch (Exception ex)
                        {
                            _log.Warn("Sending CREmbed failed");
                            _log.Warn(ex);
                        }
                        return;
                    }

                    var exec3 = Environment.TickCount - execTime;

                    string messageContent = usrMsg.Content;
                    if (guild != null)
                    {
                        ConcurrentDictionary <string, string> maps;
                        if (Modules.Utility.Utility.CommandMapCommands.AliasMaps.TryGetValue(guild.Id, out maps))
                        {
                            string newMessageContent;
                            if (maps.TryGetValue(messageContent.Trim().ToLowerInvariant(), out newMessageContent))
                            {
                                _log.Info(@"--Mapping Command--
    GuildId: {0}
    Trigger: {1}
    Mapping: {2}", guild.Id, messageContent, newMessageContent);
                                var oldMessageContent = messageContent;
                                messageContent        = newMessageContent;

                                try { await usrMsg.Channel.SendConfirmAsync($"{oldMessageContent} => {newMessageContent}").ConfigureAwait(false); } catch { }
                            }
                        }
                    }


                    // 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 CommandExecuted(usrMsg, exec.CommandInfo).ConfigureAwait(false);
                        await LogSuccessfulExecution(usrMsg, exec, channel, exec1, exec2, exec3, execTime).ConfigureAwait(false);
                    }
                    else if (!exec.Result.IsSuccess && exec.Result.Error != CommandError.UnknownCommand)
                    {
                        LogErroredExecution(usrMsg, exec, channel, exec1, exec2, exec3, 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 SelfCommands.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);
                    }
                }
            });

            return(Task.CompletedTask);
        }