Пример #1
0
        private static void BanUserForPositiveFilter(Message message, Filters.FilterResult result)
        {
            int limitTime = 3;

            Models.Group.ConfigurationParameter configValue = CacheData.GroupConfigs[message.Chat.Id]
                                                              .Where(x => x.ConfigurationParameterId == "SpamActionLimitTime")
                                                              .SingleOrDefault();
            if (configValue != null)
            {
                int.TryParse(configValue.Value, out limitTime);
            }
            RemoveMessageForPositiveFilter(message, result);

            Bot.Manager.BotClient.KickChatMemberAsync(message.Chat.Id, message.From.Id,
                                                      DateTime.UtcNow.AddMinutes(-5));
            UserTools.AddPenalty(message.Chat.Id, message.From.Id,
                                 Models.TrustFactorLog.TrustFactorAction.ban, Bot.Manager.MyId);

            Bot.Manager.BotClient.KickChatMemberAsync(message.Chat.Id, message.From.Id,
                                                      DateTime.UtcNow.AddMinutes(-5));

            UserTools.AddPenalty(message.Chat.Id, message.From.Id,
                                 Models.TrustFactorLog.TrustFactorAction.ban, Bot.Manager.MyId);

            string author = message.From.Username == null
                ? message.From.FirstName + " " + message.From.LastName
                : "@" + message.From.Username;
            string logMessage = String.Format(
                "*[Report]*\n" +
                "User banned as per group _Spam Action_ preference.\n" +
                "⚠ do not open links you don't know ⚠\n" +
                "\nControl: `{0}`" +
                "\nChat: `{1}`" +
                "\nAuthor: `{2}`" +
                "\nUserId: `{3}`" +
                "\n\n*hash_code:* #UB{4}-{5}",
                result.CheckName,
                message.Chat.Title,
                author,
                message.From.Id,
                message.Chat.Id.ToString().Replace("-", ""),
                Guid.NewGuid());

            MessageQueueManager.EnqueueLog(new ChatMessage()
            {
                ParseMode = ParseMode.Markdown,
                Text      = logMessage
            });

            LogTools.AddActionLog(new ActionLog()
            {
                GroupId      = CacheData.Groups[message.Chat.Id].GroupId,
                UtcDate      = DateTime.UtcNow,
                ActionTypeId = "autoBan",
                Parameters   = logMessage,
            });
        }
Пример #2
0
        public static void DoCheck(Message message)
        {
            foreach (var plugin in CacheData.PreControlsPlugins)
            {
                if (!plugin.Execute(message, MessageQueueManager.EnqueueMessage, Bot.Manager.BotClient))
                {
                    return;
                }
            }

            foreach (IControl control in controls)
            {
                ControlResult result = control.DoCheck(message);
                if (result.Result == IControl.ControlResultType.positive)
                {
                    var actionToTake = CacheData.GroupConfigs[message.Chat.Id]
                                       .SingleOrDefault(x => x.ConfigurationParameterId == "SpamAction");
                    if (actionToTake == null)
                    {
                        RemoveMessageForPositiveControl(message, result);
                        return;
                    }

                    switch (actionToTake.Value)
                    {
                    case "delete":
                        RemoveMessageForPositiveControl(message, result);
                        break;

                    case "limit":
                        LimitUserForPositiveControl(message, result);
                        break;

                    case "ban":
                        BanUserForPositiveControl(message, result);
                        break;
                    }

                    return;
                }
            }

            foreach (var plugin in CacheData.PostControlsPlugins)
            {
                if (!plugin.Execute(message, MessageQueueManager.EnqueueMessage, Bot.Manager.BotClient))
                {
                    return;
                }
            }

            foreach (var plugin in CacheData.PreFiltersPlugins)
            {
                if (!plugin.Execute(message, MessageQueueManager.EnqueueMessage, Bot.Manager.BotClient))
                {
                    return;
                }
            }

            foreach (Filters.IFilter filter in filters)
            {
                Filters.FilterResult result = filter.DoCheck(message);
                if (result.Result == Filters.IFilter.FilterResultType.positive)
                {
                    var actionToTake = CacheData.GroupConfigs[message.Chat.Id]
                                       .SingleOrDefault(x => x.ConfigurationParameterId == "SpamAction");
                    if (actionToTake == null)
                    {
                        RemoveMessageForPositiveFilter(message, result);
                        return;
                    }

                    switch (actionToTake.Value)
                    {
                    case "delete":
                        RemoveMessageForPositiveFilter(message, result);
                        break;

                    case "limit":
                        LimitUserForPositiveFilter(message, result);
                        break;

                    case "ban":
                        BanUserForPositiveFilter(message, result);
                        break;
                    }
                    return;
                }
            }

            foreach (var plugin in CacheData.PostFiltersPlugins)
            {
                if (!plugin.Execute(message, MessageQueueManager.EnqueueMessage, Bot.Manager.BotClient))
                {
                    return;
                }
            }
        }
Пример #3
0
        private static void LimitUserForPositiveFilter(Message message, Filters.FilterResult result)
        {
            int limitTime = 3;

            Models.Group.ConfigurationParameter configValue = CacheData.GroupConfigs[message.Chat.Id]
                                                              .Where(x => x.ConfigurationParameterId == "SpamActionLimitTime")
                                                              .SingleOrDefault();
            if (configValue != null)
            {
                int.TryParse(configValue.Value, out limitTime);
            }
            RemoveMessageForPositiveFilter(message, result);
            Bot.Manager.BotClient.RestrictChatMemberAsync(
                message.Chat.Id,
                message.From.Id,
                new ChatPermissions()
            {
                CanSendMessages       = false,
                CanAddWebPagePreviews = false,
                CanChangeInfo         = false,
                CanInviteUsers        = false,
                CanPinMessages        = false,
                CanSendMediaMessages  = false,
                CanSendOtherMessages  = false,
                CanSendPolls          = false
            },
                DateTime.UtcNow.AddMinutes(limitTime));

            string author = message.From.Username == null
                ? message.From.FirstName + " " + message.From.LastName
                : "@" + message.From.Username;
            string logMessage = String.Format(
                "*[Report]*\n" +
                "User limited as per group _Spam Action_ preference.\n" +
                "⚠ do not open links you don't know ⚠\n" +
                "\nControl: `{0}`" +
                "\nChat: `{1}`" +
                "\nAuthor: `{2}`" +
                "\nUserId: `{3}`" +
                "\n\n*hash_code:* #UB{4}-{5}",
                result.CheckName,
                message.Chat.Title,
                author,
                message.From.Id,
                message.Chat.Id.ToString().Replace("-", ""),
                Guid.NewGuid());

            MessageQueueManager.EnqueueLog(new ChatMessage()
            {
                ParseMode = ParseMode.Markdown,
                Text      = logMessage
            });

            LogTools.AddActionLog(new ActionLog()
            {
                GroupId      = CacheData.Groups[message.Chat.Id].GroupId,
                UtcDate      = DateTime.UtcNow,
                ActionTypeId = "autoLimit",
                Parameters   = logMessage,
            });
        }
Пример #4
0
        private static void RemoveMessageForPositiveFilter(Message message, Filters.FilterResult result)
        {
            try
            {
                Bot.Manager.BotClient.DeleteMessageAsync(message.Chat.Id, message.MessageId);
                string author = message.From.Username == null
                    ? message.From.FirstName + " " + message.From.LastName
                    : "@" + message.From.Username;
                string logMessage = String.Format(
                    "*[Report]*\n" +
                    "Message deleted due to filter *{0}* provided positive result.\n" +
                    "⚠ do not open links you don't know ⚠\n" +
                    "\nChat: `{1}`" +
                    "\nAuthor: `{3}`" +
                    "\nUserId: `{4}`" +
                    "\nOriginal message:\n```{2}```" +
                    "\n\n*hash_code:* #UB{5}-{6}",
                    result.CheckName,
                    message.Chat.Title,
                    message.Text,
                    author,
                    message.From.Id,
                    message.Chat.Id.ToString().Replace("-", ""),
                    Guid.NewGuid());
                MessageQueueManager.EnqueueLog(new ChatMessage()
                {
                    ParseMode = ParseMode.Markdown,
                    Text      = logMessage
                });

                LogTools.AddActionLog(new ActionLog()
                {
                    GroupId      = CacheData.Groups[message.Chat.Id].GroupId,
                    UtcDate      = DateTime.UtcNow,
                    ActionTypeId = "autoDelete",
                    Parameters   = logMessage,
                });
            }
            catch (Exception ex)
            {
                Data.Utils.Logging.AddLog(new SystemLog()
                {
                    LoggerName = CacheData.LoggerName,
                    Date       = DateTime.Now,
                    Function   = "Unifiedban.Terminal.Controls.Manager.RemoveMessageForPositiveFilter",
                    Level      = SystemLog.Levels.Error,
                    Message    = ex.Message,
                    UserId     = -1
                });
                if (ex.InnerException != null)
                {
                    Data.Utils.Logging.AddLog(new SystemLog()
                    {
                        LoggerName = CacheData.LoggerName,
                        Date       = DateTime.Now,
                        Function   = "Unifiedban.Terminal.Controls.Manager.RemoveMessageForPositiveFilter",
                        Level      = SystemLog.Levels.Error,
                        Message    = ex.InnerException.Message,
                        UserId     = -1
                    });
                }
            }
        }
Пример #5
0
        public static void UserJoinedAction(Message message)
        {
            if (message.NewChatMembers.SingleOrDefault(x => x.Id == Manager.MyId) != null &&
                (message.Chat.Type == ChatType.Group ||
                 message.Chat.Type == ChatType.Supergroup))
            {
                Data.Utils.Logging.AddLog(new SystemLog()
                {
                    LoggerName = CacheData.LoggerName,
                    Date       = DateTime.Now,
                    Function   = "Unifiedban.Bot.Manager.BotClient_OnMessage",
                    Level      = SystemLog.Levels.Info,
                    Message    = $"I have been added to Group {message.Chat.Title} ID {message.Chat.Id}",
                    UserId     = -1
                });

#if DEBUG
                if (!CacheData.BetaAuthChats.Contains(message.Chat.Id))
                {
                    Manager.BotClient.SendTextMessageAsync(
                        chatId: message.Chat.Id,
                        text: "⚠️Error registering new group. Not authorized to Beta channel.\n" +
                        "Join our support group to verify if you could join it: @unifiedban_group"
                        );
                    Manager.BotClient.SendTextMessageAsync(
                        chatId: CacheData.ControlChatId,
                        parseMode: ParseMode.Markdown,
                        text: String.Format(
                            "*[Log]*\n" +
                            "⚠️Error registering new group. Not authorized to Beta channel.\n" +
                            "\nChat: {0}" +
                            "\nChatId: {1}" +
                            "\n\n*hash_code:* #UB{2}-{3}",
                            message.Chat.Title,
                            message.Chat.Id,
                            message.Chat.Id.ToString().Replace("-", ""),
                            Guid.NewGuid())
                        );
                    return;
                }
#endif

                if (!CacheData.Groups.ContainsKey(message.Chat.Id))
                {
                    bool registered = RegisterGroup(message);
                    if (!registered)
                    {
                        Manager.BotClient.SendTextMessageAsync(
                            chatId: CacheData.ControlChatId,
                            parseMode: ParseMode.Markdown,
                            text: String.Format(
                                "*[Log]*\n" +
                                "⚠️Error registering new group.\n" +
                                "\nChat: {0}" +
                                "\nChatId: {1}" +
                                "\n\n*hash_code:* #UB{2}-{3}",
                                message.Chat.Title,
                                message.Chat.Id,
                                message.Chat.Id.ToString().Replace("-", ""),
                                Guid.NewGuid())
                            );
                    }
                }
            }

            if (!CacheData.Groups.ContainsKey(message.Chat.Id))
            {
                return;
            }

            bool blacklistEnabled = false;
            ConfigurationParameter blacklistConfig = CacheData.GroupConfigs[message.Chat.Id]
                                                     .Where(x => x.ConfigurationParameterId == "Blacklist")
                                                     .FirstOrDefault();
            if (blacklistConfig != null)
            {
                if (blacklistConfig.Value.ToLower() == "true")
                {
                    blacklistEnabled = true;
                }
            }

            bool rtlNameCheckEnabled = false;
            ConfigurationParameter rtlNameCheckConfig = CacheData.GroupConfigs[message.Chat.Id]
                                                        .Where(x => x.ConfigurationParameterId == "RTLNameFilter")
                                                        .FirstOrDefault();
            if (rtlNameCheckConfig != null)
            {
                if (rtlNameCheckConfig.Value.ToLower() == "true")
                {
                    rtlNameCheckEnabled = true;
                }
            }

            bool captchaEnabled = false;
            ConfigurationParameter captchaConfig = CacheData.GroupConfigs[message.Chat.Id]
                                                   .Where(x => x.ConfigurationParameterId == "Captcha")
                                                   .FirstOrDefault();
            if (captchaConfig != null)
            {
                if (captchaConfig.Value.ToLower() == "true")
                {
                    captchaEnabled = true;
                }
            }

            bool welcomeMessageEnabled = false;
            ConfigurationParameter welcomeMessageConfig = CacheData.GroupConfigs[message.Chat.Id]
                                                          .Where(x => x.ConfigurationParameterId == "WelcomeMessage")
                                                          .FirstOrDefault();
            if (welcomeMessageConfig != null)
            {
                if (welcomeMessageConfig.Value.ToLower() == "true")
                {
                    welcomeMessageEnabled = true;
                }
            }

            foreach (User member in message.NewChatMembers)
            {
                if (member.Id == Manager.MyId ||
                    member.Id == 777000 || // Telegram's official updateServiceNotification
                    member.IsBot)
                {
                    continue;
                }

                if (blacklistEnabled)
                {
                    if (Utils.UserTools.KickIfIsInBlacklist(message, member))
                    {
                        continue;
                    }
                }

                if (rtlNameCheckEnabled)
                {
                    Filters.FilterResult rtlCheck = RTLNameFilter.DoCheck(message,
                                                                          member.FirstName + " " + member.LastName);
                    if (rtlCheck.Result == Filters.IFilter.FilterResultType.positive)
                    {
                        try
                        {
                            Manager.BotClient.RestrictChatMemberAsync(
                                message.Chat.Id,
                                member.Id,
                                new ChatPermissions()
                            {
                                CanSendMessages       = false,
                                CanAddWebPagePreviews = false,
                                CanChangeInfo         = false,
                                CanInviteUsers        = false,
                                CanPinMessages        = false,
                                CanSendMediaMessages  = false,
                                CanSendOtherMessages  = false,
                                CanSendPolls          = false
                            }
                                );
                        }
                        catch (Exception ex)
                        {
                            Data.Utils.Logging.AddLog(new SystemLog()
                            {
                                LoggerName = CacheData.LoggerName,
                                Date       = DateTime.Now,
                                Function   = "UserJoinedAction -> rtlNameCheckEnabled",
                                Level      = SystemLog.Levels.Error,
                                Message    = ex.Message,
                                UserId     = -1
                            });

                            if (ex.InnerException != null)
                            {
                                Data.Utils.Logging.AddLog(new SystemLog()
                                {
                                    LoggerName = CacheData.LoggerName,
                                    Date       = DateTime.Now,
                                    Function   = "UserJoinedAction -> rtlNameCheckEnabled",
                                    Level      = SystemLog.Levels.Error,
                                    Message    = ex.Message,
                                    UserId     = -1
                                });
                            }
                        }

                        continue;
                    }
                }

                try
                {
                    bool pluginCheckOk = true;
                    foreach (var plugin in CacheData.PreCaptchaAndWelcomePlugins)
                    {
                        if (!plugin.Execute(message, member, MessageQueueManager.EnqueueMessage))
                        {
                            pluginCheckOk = false;
                            Manager.BotClient.KickChatMemberAsync(message.Chat.Id, member.Id);
                            if (message.Chat.Type == ChatType.Supergroup)
                            {
                                Manager.BotClient.UnbanChatMemberAsync(message.Chat.Id, member.Id);
                            }
                            break;
                        }
                    }

                    if (!pluginCheckOk)
                    {
                        continue;
                    }

                    if (CacheData.TrustFactors.ContainsKey(member.Id))
                    {
                        int points = CacheData.TrustFactors[member.Id].Points;
                        if (points < 71)
                        {
                            Manager.BotClient.SendTextMessageAsync(
                                chatId: message.Chat,
                                parseMode: ParseMode.Markdown,
                                text: String.Format(
                                    "*[Alert]*\n" +
                                    "⚠️ Trust factor of user {0}:{1} is below security threshold\n" +
                                    "\n*Trust factor:* {2}/100",
                                    member.Id,
                                    member.Username,
                                    points)
                                );
                        }
                    }
                    if (captchaEnabled && CacheData.Operators
                        .SingleOrDefault(x => x.TelegramUserId == member.Id) == null)
                    {
                        Manager.BotClient.RestrictChatMemberAsync(
                            message.Chat.Id,
                            member.Id,
                            new ChatPermissions()
                        {
                            CanSendMessages       = false,
                            CanAddWebPagePreviews = false,
                            CanChangeInfo         = false,
                            CanInviteUsers        = false,
                            CanPinMessages        = false,
                            CanSendMediaMessages  = false,
                            CanSendOtherMessages  = false,
                            CanSendPolls          = false
                        }
                            ).Wait();

                        string name = member.Username != null ? "@" + member.Username : member.FirstName;
                        MessageQueueManager.EnqueueMessage(
                            new Models.ChatMessage()
                        {
                            Timestamp   = DateTime.UtcNow,
                            Chat        = message.Chat,
                            ParseMode   = ParseMode.Default,
                            Text        = $"Please {name} certify to be a human.\nIf you don't click this button you are not going to be unlocked.",
                            ReplyMarkup = new InlineKeyboardMarkup(
                                InlineKeyboardButton.WithCallbackData(
                                    CacheData.GetTranslation("en", "captcha_iamhuman", true),
                                    $"/Captcha " + member.Id
                                    )
                                )
                        });

                        continue;
                    }

                    if (welcomeMessageEnabled)
                    {
                        BusinessLogic.ButtonLogic           buttonLogic = new BusinessLogic.ButtonLogic();
                        List <List <InlineKeyboardButton> > buttons     = new List <List <InlineKeyboardButton> >();
                        int btnCount   = 0;
                        int depthLevel = 0;
                        buttons.Add(new List <InlineKeyboardButton>());

                        foreach (Button btn in buttonLogic
                                 .GetByChat(CacheData.Groups[message.Chat.Id]
                                            .GroupId))
                        {
                            if (btnCount == 2)
                            {
                                btnCount = 0;
                                buttons.Add(new List <InlineKeyboardButton>());
                                depthLevel++;
                            }
                            buttons[depthLevel].Add(InlineKeyboardButton.WithUrl(btn.Name, btn.Content));
                            btnCount++;
                        }

                        MessageQueueManager.EnqueueMessage(
                            new Models.ChatMessage()
                        {
                            Timestamp = DateTime.UtcNow,
                            Chat      = message.Chat,
                            ParseMode = ParseMode.Html,
                            Text      = Utils.Parsers.VariablesParser(
                                CacheData.Groups[message.Chat.Id].WelcomeText,
                                message, member),
                            ReplyMarkup = new InlineKeyboardMarkup(
                                buttons
                                )
                        });
                    }

                    foreach (var plugin in CacheData.PostCaptchaAndWelcomePlugins)
                    {
                        if (!plugin.Execute(message, member, MessageQueueManager.EnqueueMessage))
                        {
                            Manager.BotClient.KickChatMemberAsync(message.Chat.Id, member.Id);
                            if (message.Chat.Type == ChatType.Supergroup)
                            {
                                Manager.BotClient.UnbanChatMemberAsync(message.Chat.Id, member.Id);
                            }
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Data.Utils.Logging.AddLog(new SystemLog()
                    {
                        LoggerName = CacheData.LoggerName,
                        Date       = DateTime.Now,
                        Function   = "UserJoinedAction",
                        Level      = SystemLog.Levels.Error,
                        Message    = ex.Message,
                        UserId     = -1
                    });

                    if (ex.InnerException != null)
                    {
                        Data.Utils.Logging.AddLog(new SystemLog()
                        {
                            LoggerName = CacheData.LoggerName,
                            Date       = DateTime.Now,
                            Function   = "UserJoinedAction",
                            Level      = SystemLog.Levels.Error,
                            Message    = ex.Message,
                            UserId     = -1
                        });
                    }
                }
            }
        }
Пример #6
0
        public ControlResult DoCheck(Message message)
        {
            if (Utils.ChatTools.IsUserAdmin(message.Chat.Id, message.From.Id))
            {
                return(new ControlResult()
                {
                    CheckName = "Spam Names",
                    Result = IControl.ControlResultType.skipped
                });
            }

            Models.Group.ConfigurationParameter configValue = CacheData.GroupConfigs[message.Chat.Id]
                                                              .Where(x => x.ConfigurationParameterId == "SpamNameControl")
                                                              .SingleOrDefault();
            if (configValue != null)
            {
                if (configValue.Value == "false")
                {
                    return new ControlResult()
                           {
                               CheckName = "Spam Names",
                               Result    = IControl.ControlResultType.skipped
                           }
                }
            }
            ;

            Filters.BadWordFilter badWordFilter = new Filters.BadWordFilter();
            Filters.FilterResult  badName       = badWordFilter
                                                  .DoCheck(message, message.From.FirstName + " " + message.From.LastName);
            if (badName.Result == Filters.IFilter.FilterResultType.positive)
            {
                return new ControlResult()
                       {
                           CheckName = "Spam Names",
                           Result    = IControl.ControlResultType.positive
                       }
            }
            ;

            if (!String.IsNullOrEmpty(message.From.FirstName))
            {
                if (!isNameSafe.TryGetValue(message.From.FirstName, out bool nameIsValid))
                {
                    CheckIfNameIsValid(message.From.FirstName);
                }
            }

            if (!String.IsNullOrEmpty(message.From.LastName))
            {
                if (!isNameSafe.TryGetValue(message.From.LastName, out bool surnameIsValid))
                {
                    CheckIfNameIsValid(message.From.LastName);
                }
            }

            if (!String.IsNullOrEmpty(message.From.FirstName))
            {
                if (!isNameSafe[message.From.FirstName])
                {
                    return new ControlResult()
                           {
                               CheckName = "Spam Names",
                               Result    = IControl.ControlResultType.positive
                           }
                }
            }
            ;
            if (!String.IsNullOrEmpty(message.From.LastName))
            {
                if (!isNameSafe[message.From.LastName])
                {
                    return new ControlResult()
                           {
                               CheckName = "Spam Names",
                               Result    = IControl.ControlResultType.positive
                           }
                }
            }
            ;

            return(new ControlResult()
            {
                CheckName = "Spam Names",
                Result = IControl.ControlResultType.negative
            });
        }

        void CheckIfNameIsValid(string name)
        {
            string          regex        = @"((http|ftp|https):\/\/)?([\w_-]+\s?(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?";
            Regex           reg          = new Regex(regex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
            MatchCollection matchedWords = reg.Matches(name);

            if (matchedWords.Count == 0)
            {
                isNameSafe[name] = true;

                return;
            }
            using (WebClientWithTimeout client = new WebClientWithTimeout())
            {
                string siteUri = name;
                if (!name.Contains("http://") && !name.Contains("https://"))
                {
                    siteUri = "http://" + name;
                }

                string htmlCode = "";
                try
                {
                    htmlCode = client.DownloadString(siteUri);
                }
                catch { }

                if (htmlCode.Contains("tgme_page_extra"))
                {
                    isNameSafe[name] = false;
                }
                else
                {
                    isNameSafe[name] = true;
                }
            }
        }
    }