Example #1
0
        public static void Initialize(string apikey)
        {
            if (CacheData.FatalError)
            {
                return;
            }

            if (String.IsNullOrEmpty(apikey))
            {
                Data.Utils.Logging.AddLog(new Models.SystemLog()
                {
                    LoggerName = CacheData.LoggerName,
                    Date       = DateTime.Now,
                    Function   = "Unifiedban Terminal Startup",
                    Level      = Models.SystemLog.Levels.Fatal,
                    Message    = "API KEY must be set!",
                    UserId     = -1
                });
                CacheData.FatalError = true;
                return;
            }

            APIKEY          = apikey;
            instanceId      = Guid.NewGuid().ToString();
            currentHostname = System.Net.Dns.GetHostName();
            Commands.Initialize();

            BotClient = new TelegramBotClient(APIKEY);
            var me = BotClient.GetMeAsync().Result;

            Username = me.Username;
            MyId     = me.Id;
            Data.Utils.Logging.AddLog(new Models.SystemLog()
            {
                LoggerName = CacheData.LoggerName,
                Date       = DateTime.Now,
                Function   = "Unifiedban Terminal Startup",
                Level      = Models.SystemLog.Levels.Warn,
                Message    = $"Hello, World! I am user {me.Id} and my name is {me.FirstName}.",
                UserId     = -1
            });

            MessageQueueManager.AddChatIfNotPresent(CacheData.ControlChatId);

            BotClient.OnMessage       += BotClient_OnMessage;
            BotClient.OnCallbackQuery += BotClient_OnCallbackQuery;

            Console.Title = $"Unifiedban - Username: {me.Username} - Instance ID: {instanceId}";


            Data.Utils.Logging.AddLog(new Models.SystemLog()
            {
                LoggerName = CacheData.LoggerName,
                Date       = DateTime.Now,
                Function   = "Unifiedban Terminal Startup",
                Level      = Models.SystemLog.Levels.Info,
                Message    = "Bot Client initialized",
                UserId     = -2
            });
        }
Example #2
0
        public static bool RegisterGroup(Message message)
        {
            if (CacheData.Groups.ContainsKey(message.Chat.Id))
            {
                return(false);
            }

            BusinessLogic.Group.TelegramGroupLogic telegramGroupLogic =
                new BusinessLogic.Group.TelegramGroupLogic();
            TelegramGroup registered = telegramGroupLogic.Add(
                message.Chat.Id, message.Chat.Title, TelegramGroup.Status.Active,
                configuration: Newtonsoft.Json.JsonConvert.SerializeObject(CacheData.GroupDefaultConfigs),
                welcomeText: CacheData.GetTranslation("en", "message_welcome_default"),
                chatLanguage: "en",
                settingsLanguage: "en",
                reportChatId: CacheData.ControlChatId,
                rulesText: "No rules defined yet by the group admins. Just... be nice!",
                callerId: -2);

            if (registered == null)
            {
                return(false);
            }

            CacheData.Groups.Add(message.Chat.Id, registered);
            CacheData.GroupConfigs.Add(message.Chat.Id, CacheData.GroupDefaultConfigs);
            if (MessageQueueManager.AddGroupIfNotPresent(registered))
            {
                Manager.BotClient.SendTextMessageAsync(
                    chatId: message.Chat.Id,
                    parseMode: ParseMode.Markdown,
                    text: CacheData.GetTranslation("en", "message_group_first_join"),
                    disableWebPagePreview: true
                    );

                Manager.BotClient.SendTextMessageAsync(
                    chatId: CacheData.ControlChatId,
                    parseMode: ParseMode.Markdown,
                    text: String.Format(
                        "*[Log]*\n" +
                        "New group has chosen unified/ban 🥳\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(true);
        }
Example #3
0
        public static void MigrateToChatId(Message message)
        {
            if (!CacheData.Groups.ContainsKey(message.Chat.Id))
            {
                return;
            }

            BusinessLogic.Group.TelegramGroupLogic telegramGroupLogic =
                new BusinessLogic.Group.TelegramGroupLogic();

            TelegramGroup updated = telegramGroupLogic.UpdateChatId(message.Chat.Id, message.MigrateToChatId, -2); // TODO - log operation

            if (updated == null)
            {
                return;
            }

            CacheData.Groups.Add(updated.TelegramChatId, updated);
            MessageQueueManager.AddGroupIfNotPresent(updated);

            MessageQueueManager.RemoveGroupIfNotPresent(message.Chat.Id);
            CacheData.Groups.Remove(message.Chat.Id);
        }
Example #4
0
        public static void UserLeftAction(Message message)
        {
            if (Utils.BotTools.IsUserOperator(message.LeftChatMember.Id))
            {
                if (!CacheData.ActiveSupport
                    .Contains(message.Chat.Id))
                {
                    CacheData.ActiveSupport.Remove(message.Chat.Id);
                    CacheData.CurrentChatAdmins.Remove(message.Chat.Id);

                    Manager.BotClient.SendTextMessageAsync(
                        chatId: message.Chat.Id,
                        parseMode: ParseMode.Markdown,
                        text: String.Format(
                            "Support session *{0}* ended since operator left the chat.",
                            message.LeftChatMember.Username)
                        );
                    MessageQueueManager.EnqueueLog(new ChatMessage()
                    {
                        ParseMode = ParseMode.Markdown,
                        Text      = String.Format(
                            "*[Log]*" +
                            "Support session ended since operator *{0}* left the chat." +
                            "\nChatId: `{1}`" +
                            "\nChat: `{2}`" +
                            "\nUserId: `{3}`" +
                            "\n\n*hash_code:* #UB{4}-{5}",
                            message.LeftChatMember.Username,
                            message.Chat.Id,
                            message.Chat.Title,
                            message.LeftChatMember.Id,
                            message.Chat.Id.ToString().Replace("-", ""),
                            Guid.NewGuid())
                    });
                }
            }
        }
Example #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
                        });
                    }
                }
            }
        }
Example #6
0
        private static async void BotClient_OnMessage(object sender, MessageEventArgs e)
        {
            if (e == null)
            {
                return;
            }

            if (e.Message.Date < DateTime.Now.AddDays(-1))
            {
                return;
            }

            await Task.Run(() => CacheData.IncrementHandledMessages());

            if (CacheData.Groups.Keys.Contains(e.Message.Chat.Id))
            {
                if (CacheData.Groups[e.Message.Chat.Id].State !=
                    Models.Group.TelegramGroup.Status.Active &&
                    e.Message.Text != "/enable")
                {
                    return;
                }
            }

            Data.Utils.Logging.AddLog(new Models.SystemLog()
            {
                LoggerName = CacheData.LoggerName,
                Date       = DateTime.Now,
                Function   = "Unifiedban.Bot.Manager.BotClient_OnMessage",
                Level      = Models.SystemLog.Levels.Debug,
                Message    = "Message received",
                UserId     = -1
            });

            await Task.Run(() => Functions.CacheUsername(e.Message));

            if (e.Message.MigrateToChatId != 0)
            {
                Functions.MigrateToChatId(e.Message);
            }

            bool isPrivateChat = e.Message.Chat.Type == ChatType.Private ||
                                 e.Message.Chat.Type == ChatType.Channel;

            if (isPrivateChat)
            {
                MessageQueueManager.AddChatIfNotPresent(e.Message.Chat.Id);
            }

            bool justAdded = false;

            if (e.Message.NewChatMembers != null)
            {
                justAdded = e.Message.NewChatMembers.SingleOrDefault(x => x.Id == MyId) != null;
            }

            if (!justAdded && !isPrivateChat &&
                !CacheData.Groups.ContainsKey(e.Message.Chat.Id))
            {
                string logMessage = String.Format(
                    "*[Alert]*\n" +
                    "Group *{0}* left due to missing group record in database.\n" +
                    "⚠ do not open links you don't know ⚠\n" +
                    "\nChat: `{1}`" +
                    "\n\n*hash_code:* #UB{2}-{3}",
                    e.Message.Chat.Title,
                    e.Message.Chat.Id,
                    e.Message.Chat.Id.ToString().Replace("-", ""),
                    Guid.NewGuid());
                MessageQueueManager.EnqueueLog(new Models.ChatMessage()
                {
                    ParseMode = ParseMode.Markdown,
                    Text      = logMessage
                });

                await BotClient.SendTextMessageAsync(e.Message.Chat.Id,
                                                     "We're sorry but an error has occurred while retrieving this chat on our database.\n" +
                                                     "Please add again the bot if you want to continue to use it.\n" +
                                                     "For any doubt reach us in our support group @unifiedban_group");

                await BotClient.LeaveChatAsync(e.Message.Chat.Id);

                return;
            }

            if (!string.IsNullOrEmpty(e.Message.Text) &&
                !Utils.UserTools.KickIfInBlacklist(e.Message))
            {
                bool isCommand = false;
                if (e.Message.Text.StartsWith('/'))
                {
                    isCommand = Command.Parser.Parse(e.Message).Result;
                }

                if (e.Message.ReplyToMessage != null && !isCommand && !isPrivateChat)
                {
                    if (e.Message.ReplyToMessage.From.Id == MyId)
                    {
                        CommandQueueManager.ReplyMessage(e.Message);
                        return;
                    }
                }

                if (!Utils.ChatTools.HandleSupportSessionMsg(e.Message) && !isCommand &&
                    e.Message.From.Id != 777000 && !isPrivateChat)  // Telegram's official updateServiceNotification
                {
                    Controls.Manager.DoCheck(e.Message);
                }
            }
            if (e.Message.NewChatMembers != null)
            {
                Functions.UserJoinedAction(e.Message);
            }
            if (e.Message.LeftChatMember != null)
            {
                Functions.UserLeftAction(e.Message);
            }

            if (!String.IsNullOrEmpty(e.Message.MediaGroupId) ||
                e.Message.Photo != null ||
                e.Message.Document != null)
            {
                Controls.Manager.DoMediaCheck(e.Message);
            }

            if (!isPrivateChat && e.Message.NewChatTitle != null)
            {
                CacheData.Groups[e.Message.Chat.Id].Title = e.Message.NewChatTitle;
            }
        }