/// <summary>
    /// Get of list Administrators in ChatId
    /// </summary>
    /// <param name="chatId"></param>
    /// <returns></returns>
    public async Task <ChatMember[]> GetChatAdministratorsAsync(long chatId)
    {
        var administrators = await _cacheService.GetOrSetAsync(
            cacheKey : "chat-admin_" + chatId.ReduceChatId(),
            action : async() =>
            await _botClient.GetChatAdministratorsAsync(chatId)
            );

        return(administrators);
    }
Beispiel #2
0
        private async void OnMessage(object sender, MessageEventArgs e)
        {
            if (!IsValidChatType(e.Message.Chat.Type))
            {
                await BotClient.SendTextMessageAsync(
                    e.Message.Chat.Id,
                    "Бот не работает вне груповых чатов.",
                    replyToMessageId : e.Message.MessageId);

                return;
            }

            if (string.IsNullOrEmpty(e.Message.Text) && e.Message.NewChatMembers == null)
            {
                return;
            }

            var chatAdmins = await BotClient.GetChatAdministratorsAsync(e.Message.Chat.Id);

            if (chatAdmins.All(admin => admin.User.Id != BotClient.BotId))
            {
                return;
            }

            foreach (var command in _commands.Where(command => command.Contains(e.Message)))
            {
                if (command is ForbiddenWordCommand)
                {
                    Log.Logger.Information($"{e.Message.From} нарушил правила чата: \"{e.Message.Text}\"");
                }
                else
                {
                    string commandIdentifier = command.Triggers != null
                        ? command.Triggers.First()
                        : command.GetType().Name;

                    Log.Logger.Information($"{e.Message.From} (@{e.Message.Chat.Username}) запросил команду {commandIdentifier}: {e.Message.Text}");
                }

                try
                {
                    await command.Execute(e.Message);
                }
                catch (Exception ex)
                {
                    string errorTemplate = $"Unpredictable error occured ({nameof(ex)}): {ex.Message}\n" +
                                           $"Stack Trace: {ex.StackTrace}";
                    Log.Error(ex, errorTemplate);
                }

                return;
            }
        }
Beispiel #3
0
        internal static List <GroupAdmin> GetChatAdmins(long chatid, bool forceCacheUpdate = false)
        {
            try
            {                                                                                     // Admins are cached for 1 hour
                string            itemIndex = $"{chatid}";
                List <GroupAdmin> admins    = Program.AdminCache[itemIndex] as List <GroupAdmin>; // Read admin list from cache
                if (admins == null || forceCacheUpdate)
                {
                    admins = Api.GetChatAdministratorsAsync(chatid).Result.Select(x =>
                                                                                  new GroupAdmin(x.User.Id, chatid, x.User.FirstName)).ToList();

                    CacheItemPolicy policy = new CacheItemPolicy()
                    {
                        AbsoluteExpiration = DateTime.Now.AddHours(1)
                    };
                    Program.AdminCache.Set(itemIndex, admins, policy); // Write admin list into cache
                }

                return(admins);
            }
            catch (Exception e)
            {
                e.LogError();
                return(null);
            }
        }
Beispiel #4
0
        public async void Handle(Message message)
        {
            Debug.Assert(message != null);

            if (message.From.Id == _botClient.BotId)
            {
                // Don't process messages sent by us.
                return;
            }

            if (message.Text != null)
            {
                _logger.Information($"{Utilities.UserToString(message.From)}: {message.Text}");
            }

            if (_spammerDetector.IsSpam(message))
            {
                // Don't ban admins.
                ChatMember[] admins = await _botClient.GetChatAdministratorsAsync(message.Chat.Id).ConfigureAwait(false);

                if (admins.Select(a => a.User.Id).Contains(message.From.Id))
                {
                    _logger.Information($"Ignoring spam from admin {message.From.Id}");
                    return;
                }

                await _botClient.DeleteMessageAsync(message.Chat.Id, message.MessageId).ConfigureAwait(false);

                await _botClient.KickChatMemberAsync(message.Chat.Id, message.From.Id).ConfigureAwait(false);

                await _botClient.SendTextMessageAsync(message.Chat.Id, $"Banned spammer {Utilities.UserToString(message.From)}.").ConfigureAwait(false);
            }
        }
Beispiel #5
0
        private static async Task <bool> IsAdministratorAsync(ITelegramBotClient botClient, Chat chat, User user)
        {
            var administrators = await botClient.GetChatAdministratorsAsync(chat.Id);

            if (administrators.Any(a => a.User.Id == user.Id))
            {
                return(true);
            }

            return(false);
        }
Beispiel #6
0
        public async IAsyncEnumerable <MessageResponse> HandleMessageAsync(Message message, NextHandler nextHandler)
        {
            var chat = message.Chat;

            if (chat.Type != ChatType.Private)
            {
                if (message.MigrateToChatId != 0)
                {
                    await _groupService.MigrateGroupAsync(chat.Id, message.MigrateToChatId);

                    yield break;
                }

                if (!await _groupService.IsGroupExistsAsync(chat.Id))
                {
                    var creator = (await _botClient.GetChatAdministratorsAsync(chat)).Single(r => r.Status == ChatMemberStatus.Creator);

                    await _groupService.EnsureGroupAsync(chat.Id, chat.Title, creator.User.Id);
                }

                if (message.MigrateFromChatId != 0)
                {
                    await _groupService.RemoveGroupAsync(message.MigrateFromChatId);

                    yield break;
                }

                if (message.LeftChatMember is User removedMember)
                {
                    await _groupService.RemoveMemberAsync(chat.Id, removedMember.Id);

                    yield break;
                }

                if (message.NewChatTitle is string title)
                {
                    await _groupService.UpdateTitleAsync(chat.Id, title);

                    yield break;
                }

                if (message.From.IsBot)
                {
                    yield break;
                }

                await _groupService.EnsureMemberAsync(chat.Id, message.From.Id);
            }

            await foreach (var _ in nextHandler(message))
            {
                ;
            }
        }
Beispiel #7
0
    public static async Task UpdateCacheAdminAsync(
        this ITelegramBotClient client,
        long chatId
        )
    {
        var keyCache = GetCacheKey(chatId);

        Log.Information("Updating list Admin Cache with key: {0}", keyCache);
        var admins = await client.GetChatAdministratorsAsync(chatId);

        admins.AddCache(keyCache);
    }
Beispiel #8
0
        public async Task <Chat?> GetChat(long chatId)
        {
            var chat = await _api.GetChatAsync(chatId).ConfigureAwait(false);

            var ownerId = chat.Type switch
            {
                TgChatType.Private => chat.Id,
                _ => (await _api.GetChatAdministratorsAsync(chatId).ConfigureAwait(false))
                .First(u => u.Status == ChatMemberStatus.Creator).User.Id
            };

            return(TgConverter.ToChat(chat, ownerId));
        }
Beispiel #9
0
        private async void OnMessage(object sender, MessageEventArgs e)
        {
            if (IsMessageEmpty(e.Message))
            {
                return;
            }

            if (IsGroupChat(e.Message.Chat))
            {
                var chatAdmins = await BotClient.GetChatAdministratorsAsync(e.Message.Chat.Id);

                if (chatAdmins.All(admin => admin.User.Id != BotClient.BotId))
                {
                    // Do nothing until bot is not admin in the group
                    return;
                }
            }

            foreach (var command in _commands.Where(command => command.Contains(e.Message)))
            {
                string commandIdentifier = command.Triggers != null
                    ? command.Triggers.First()
                    : command.GetType().Name;

                Log.Logger.Information($"{e.Message.From} triggered command {commandIdentifier}: {e.Message.Text}");

                try
                {
                    await command.Execute(e.Message);
                }
                catch (Exception ex)
                {
                    string errorTemplate = $"Unpredictable error occured ({nameof(ex)}): {ex.Message}\n" +
                                           $"Stack Trace: {ex.StackTrace}";
                    Log.Error(ex, errorTemplate);
                }

                return;
            }
        }
Beispiel #10
0
        public async ValueTask HandleUpdate(Update update)
        {
            if (update?.Message?.Text is null)
            {
                return;
            }

            var text = update.Message.Text;

            if (!text.StartsWith("/"))
            {
                return;
            }

            var commandText = text
                              .Substring(1)
                              .Replace($"@{_username}", "");

            if (!_commands.TryGetValue(commandText, out var cmd))
            {
                return;
            }

            if (_adminCommands.Contains(cmd))
            {
                var admins = await _botClient.GetChatAdministratorsAsync(update.Message.Chat);

                if (admins.Any(x => x.User.Id == update.Message.From.Id))
                {
                    await cmd.HandleCommand(_botClient, update.Message);
                }
            }
            else
            {
                await cmd.HandleCommand(_botClient, update.Message);
            }
        }
Beispiel #11
0
        public async Task <bool> Process(ITelegramBotClient botClient, Update update, NeededItems n)
        {
            ChatMember[] admins = await botClient.GetChatAdministratorsAsync(n.ChatId);

            if (admins.Any(x => x.User.Id == n.Sender.Id))
            {
                GroupServices c = new GroupServices();

                switch (n.Params[0])
                {
                case "/setwelcome":
                {
                    if (string.IsNullOrEmpty(update.Message.ReplyToMessage.Text))
                    {
                        return(true);
                    }

                    Models.BaseModels.Group chat = await c.GetByTlId(n.ChatId);

                    await c.UpdateWelcome(n.ChatId, update.Message.ReplyToMessage.Text);


                    try
                    {
                        await botClient.SendTextMessageAsync(n.ChatId, update.Message.ReplyToMessage.Text, ParseMode.Html);
                    }
                    catch (Exception ex)
                    {
                        await botClient.SendTextMessageAsync(n.ChatId, ex.Message, ParseMode.Html);
                    }
                    await botClient.SendTextMessageAsync(n.ChatId, "Done!");

                    return(true);
                }

                case "/setabout":
                {
                    if (string.IsNullOrEmpty(update.Message.ReplyToMessage.Text))
                    {
                        return(true);
                    }

                    Models.BaseModels.Group chat = await c.GetByTlId(n.ChatId);

                    await c.UpdateAbout(n.ChatId, update.Message.ReplyToMessage.Text);

                    try
                    {
                        await botClient.SendTextMessageAsync(n.ChatId, update.Message.ReplyToMessage.Text, ParseMode.Html);
                    }
                    catch (Exception ex)
                    {
                        await botClient.SendTextMessageAsync(n.ChatId, ex.Message, ParseMode.Html);
                    }
                    await botClient.SendTextMessageAsync(n.ChatId, "Done!");

                    return(true);
                }

                default:
                    break;
                }
            }
            else
            {
                await botClient.SendTextMessageAsync(n.ChatId, "Admin only");
            }

            return(true);
        }
Beispiel #12
0
        static async void Bot_OnMessageAsync(object sender, MessageEventArgs e)
        {
            userQuery = e.Message.Text;
            var currentUser = users.Find(u => u.Id == e.Message.From.Id);

            if (currentUser == null)
            {
                Wallet wall = new Wallet
                {
                    Id  = users.Count + 1,
                    Sum = 0
                };
                users.Add(new User(e.Message.From.Id, e.Message.From.FirstName + " " + e.Message.From.LastName, e.Message.From.Username, wall));
                currentUser = users.ElementAt(users.Count - 1);
            }

            if (currentUser.SetTransaction == true)
            {
                string[]    parsedTrans      = userQuery.Split('-');
                Transaction transactionToAdd = null;

                try
                {
                    if (currentUser.TransactionType == Transaction.Operation.Income)
                    {
                        transactionToAdd = new Transaction
                        {
                            Id          = currentUser.Wallet.History.Count + 1,
                            Type        = Transaction.Operation.Income,
                            Cost        = Convert.ToInt32(parsedTrans[0]),
                            CreatedDate = DateTime.Now,
                            Discription = parsedTrans[1],
                        };
                    }
                    else
                    {
                        transactionToAdd = new Transaction
                        {
                            Id          = currentUser.Wallet.History.Count + 1,
                            Type        = Transaction.Operation.Expenses,
                            Cost        = Convert.ToInt32(parsedTrans[0]),
                            CreatedDate = DateTime.Now,
                            Discription = parsedTrans[1],
                        };
                    }
                }
                catch (Exception)
                {
                    await botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : $"Проверьте веденные данные, запишите сумму и название транзакции через тире",
                        parseMode : ParseMode.Html);

                    currentUser.SetTransaction = false;
                }

                var res = currentUser.Wallet.AddTransaction(transactionToAdd);
                if (res.IsCompletedSuccessfully)
                {
                    await botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : $"Транзакция № {transactionToAdd.Id} добавлена",
                        parseMode : ParseMode.Html);

                    currentUser.SetTransaction = false;
                }
                else
                {
                    await botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : $"Проверьте формат введенных данных",
                        parseMode : ParseMode.Html);
                }
            }
            if (userQuery == "/start@cuutiesBot")
            {
                InlineKeyboardMarkup replyKeyboard = new InlineKeyboardMarkup(new[]
                {
                    InlineKeyboardButton.WithCallbackData("Добавить"),
                    InlineKeyboardButton.WithCallbackData("Удалить")
                });

                await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : "1. Доходы",
                    parseMode : ParseMode.Html,
                    replyMarkup : replyKeyboard);

                await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : "2. Расходы",
                    parseMode : ParseMode.Html,
                    replyMarkup : replyKeyboard);

                await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : "3. Статистика",
                    parseMode : ParseMode.Html,
                    replyMarkup : new InlineKeyboardMarkup(new InlineKeyboardButton().CallbackData = "Посмотреть"));
            }
            else if (userQuery == "/sharewallet@cuutiesBot")
            {
                var members = await botClient.GetChatAdministratorsAsync(e.Message.Chat);

                List <InlineKeyboardButton> replyKeyboardList = new List <InlineKeyboardButton>();

                string text = "Выберие участника, что бы поделиться кошельком: \n";
                currentUser.ShareWithUser = true;

                foreach (var member in members)
                {
                    text += $"@{member.User.Username}, {member.User.FirstName}\n";
                    replyKeyboardList.Add(InlineKeyboardButton.WithCallbackData(member.User.Username));
                }
                InlineKeyboardMarkup replyKeyboard = new InlineKeyboardMarkup(replyKeyboardList);
                await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : text,
                    parseMode : ParseMode.Html,
                    replyMarkup : replyKeyboard
                    );
            }
        }
        private async Task HandleCommand(Message message)
        {
            var text = message.Text;

            // TODO: Evaluate moving all this logic into a service, and do a refactor

            if (IsCommand(Commands.Start, text))
            {
                var chatConfig = await _chatConfigurationService.GetConfigurationByChatId(message.Chat.Id);

                var messageBuilder = new StringBuilder();

                if (chatConfig == null)
                {
                    messageBuilder.AppendLine("Hi, I'm GrammarNazi.");
                    messageBuilder.AppendLine("I'm currently working and correcting all spelling errors in this chat.");
                    messageBuilder.AppendLine($"Type {Commands.Help} to get useful commands.");

                    var chatConfiguration = new ChatConfiguration
                    {
                        ChatId           = message.Chat.Id,
                        GrammarAlgorithm = Defaults.DefaultAlgorithm,
                        SelectedLanguage = SupportedLanguages.Auto
                    };

                    await _chatConfigurationService.AddConfiguration(chatConfiguration);
                }
                else
                {
                    if (chatConfig.IsBotStopped)
                    {
                        if (!await IsUserAdmin())
                        {
                            messageBuilder.AppendLine("Only admins can use this command.");
                        }
                        else
                        {
                            chatConfig.IsBotStopped = false;
                            await _chatConfigurationService.Update(chatConfig);

                            messageBuilder.AppendLine("Bot started");
                        }
                    }
                    else
                    {
                        messageBuilder.AppendLine("Bot is already started");
                    }
                }

                await _client.SendTextMessageAsync(message.Chat.Id, messageBuilder.ToString());
            }
            else if (IsCommand(Commands.Help, text))
            {
                var messageBuilder = new StringBuilder();
                messageBuilder.AppendLine("Help").AppendLine();
                messageBuilder.AppendLine("Useful commands:");
                messageBuilder.AppendLine($"{Commands.Start} start/activate the Bot.");
                messageBuilder.AppendLine($"{Commands.Stop} stop/disable the Bot.");
                messageBuilder.AppendLine($"{Commands.Settings} get configured settings.");
                messageBuilder.AppendLine($"{Commands.SetAlgorithm} <algorithm_number> to set an algorithm.");
                messageBuilder.AppendLine($"{Commands.Language} <language_number> to set a language.");
                messageBuilder.AppendLine($"{Commands.ShowDetails} Show correction details");
                messageBuilder.AppendLine($"{Commands.HideDetails} Hide correction details");
                messageBuilder.AppendLine($"{Commands.Tolerant} Set strictness level to {CorrectionStrictnessLevels.Tolerant.GetDescription()}");
                messageBuilder.AppendLine($"{Commands.Intolerant} Set strictness level to {CorrectionStrictnessLevels.Intolerant.GetDescription()}");

                await _client.SendTextMessageAsync(message.Chat.Id, messageBuilder.ToString());
            }
            else if (IsCommand(Commands.Settings, text))
            {
                var chatConfig = await GetChatConfiguration(message.Chat.Id);

                var messageBuilder = new StringBuilder();
                messageBuilder.AppendLine(GetAvailableAlgorithms(chatConfig.GrammarAlgorithm));
                messageBuilder.AppendLine(GetSupportedLanguages(chatConfig.SelectedLanguage));

                var showCorrectionDetailsIcon = chatConfig.HideCorrectionDetails ? "❌" : "✅";
                messageBuilder.AppendLine($"Show correction details {showCorrectionDetailsIcon}").AppendLine();
                messageBuilder.AppendLine("Strictness level:").AppendLine($"{chatConfig.CorrectionStrictnessLevel.GetDescription()} ✅").AppendLine();

                if (chatConfig.IsBotStopped)
                {
                    messageBuilder.AppendLine($"The bot is currently stopped. Type {Commands.Start} to activate the Bot.");
                }

                await _client.SendTextMessageAsync(message.Chat.Id, messageBuilder.ToString());
            }
            else if (IsCommand(Commands.SetAlgorithm, text))
            {
                var messageBuilder = new StringBuilder();

                if (!await IsUserAdmin())
                {
                    messageBuilder.AppendLine("Only admins can use this command.");
                    await _client.SendTextMessageAsync(message.Chat.Id, messageBuilder.ToString(), replyToMessageId : message.MessageId);

                    return;
                }

                var parameters = text.Split(" ");
                if (parameters.Length == 1)
                {
                    var chatConfig = await GetChatConfiguration(message.Chat.Id);

                    messageBuilder.AppendLine($"Parameter not received. Type {Commands.SetAlgorithm} <algorithm_numer> to set an algorithm").AppendLine();
                    messageBuilder.AppendLine(GetAvailableAlgorithms(chatConfig.GrammarAlgorithm));
                    await _client.SendTextMessageAsync(message.Chat.Id, messageBuilder.ToString());
                }
                else
                {
                    bool parsedOk = int.TryParse(parameters[1], out int algorithm);

                    if (parsedOk)
                    {
                        var chatConfig = await GetChatConfiguration(message.Chat.Id);

                        chatConfig.GrammarAlgorithm = (GrammarAlgorithms)algorithm;

                        // Fire and forget
                        _ = _chatConfigurationService.Update(chatConfig);

                        await _client.SendTextMessageAsync(message.Chat.Id, "Algorithm updated.");
                    }
                    else
                    {
                        await _client.SendTextMessageAsync(message.Chat.Id, $"Invalid parameter. Type {Commands.SetAlgorithm} <algorithm_numer> to set an algorithm.");
                    }
                }
            }
            else if (IsCommand(Commands.Language, text))
            {
                var messageBuilder = new StringBuilder();

                if (!await IsUserAdmin())
                {
                    messageBuilder.AppendLine("Only admins can use this command.");
                    await _client.SendTextMessageAsync(message.Chat.Id, messageBuilder.ToString(), replyToMessageId : message.MessageId);

                    return;
                }

                var parameters = text.Split(" ");

                if (parameters.Length == 1)
                {
                    var chatConfig = await GetChatConfiguration(message.Chat.Id);

                    messageBuilder.AppendLine($"Parameter not received. Type {Commands.Language} <language_number> to set a language.").AppendLine();
                    messageBuilder.AppendLine(GetSupportedLanguages(chatConfig.SelectedLanguage));
                    await _client.SendTextMessageAsync(message.Chat.Id, messageBuilder.ToString());
                }
                else
                {
                    bool parsedOk = int.TryParse(parameters[1], out int language);

                    if (parsedOk)
                    {
                        var chatConfig = await GetChatConfiguration(message.Chat.Id);

                        chatConfig.SelectedLanguage = (SupportedLanguages)language;

                        // Fire and forget
                        _ = _chatConfigurationService.Update(chatConfig);

                        await _client.SendTextMessageAsync(message.Chat.Id, "Language updated.");
                    }
                    else
                    {
                        await _client.SendTextMessageAsync(message.Chat.Id, $"Invalid parameter. Type {Commands.Language} <language_number> to set a language.");
                    }
                }
            }
            else if (IsCommand(Commands.Stop, text))
            {
                if (!await IsUserAdmin())
                {
                    await _client.SendTextMessageAsync(message.Chat.Id, "Only admins can use this command.", replyToMessageId : message.MessageId);

                    return;
                }

                var chatConfig = await GetChatConfiguration(message.Chat.Id);

                chatConfig.IsBotStopped = true;

                // Fire and forget
                _ = _chatConfigurationService.Update(chatConfig);

                await _client.SendTextMessageAsync(message.Chat.Id, $"Bot stopped");
            }
            else if (IsCommand(Commands.HideDetails, text))
            {
                if (!await IsUserAdmin())
                {
                    await _client.SendTextMessageAsync(message.Chat.Id, "Only admins can use this command.", replyToMessageId : message.MessageId);

                    return;
                }

                var chatConfig = await GetChatConfiguration(message.Chat.Id);

                chatConfig.HideCorrectionDetails = true;

                // Fire and forget
                _ = _chatConfigurationService.Update(chatConfig);

                await _client.SendTextMessageAsync(message.Chat.Id, "Correction details hidden ✅");
            }
            else if (IsCommand(Commands.ShowDetails, text))
            {
                if (!await IsUserAdmin())
                {
                    await _client.SendTextMessageAsync(message.Chat.Id, "Only admins can use this command.", replyToMessageId : message.MessageId);

                    return;
                }

                var chatConfig = await GetChatConfiguration(message.Chat.Id);

                chatConfig.HideCorrectionDetails = false;

                // Fire and forget
                _ = _chatConfigurationService.Update(chatConfig);

                await _client.SendTextMessageAsync(message.Chat.Id, "Show correction details ✅");
            }
            else if (IsCommand(Commands.Tolerant, text))
            {
                if (!await IsUserAdmin())
                {
                    await _client.SendTextMessageAsync(message.Chat.Id, "Only admins can use this command.", replyToMessageId : message.MessageId);

                    return;
                }

                var chatConfig = await GetChatConfiguration(message.Chat.Id);

                chatConfig.CorrectionStrictnessLevel = CorrectionStrictnessLevels.Tolerant;

                // Fire and forget
                _ = _chatConfigurationService.Update(chatConfig);

                await _client.SendTextMessageAsync(message.Chat.Id, "Tolerant ✅");
            }
            else if (IsCommand(Commands.Intolerant, text))
            {
                if (!await IsUserAdmin())
                {
                    await _client.SendTextMessageAsync(message.Chat.Id, "Only admins can use this command.", replyToMessageId : message.MessageId);

                    return;
                }

                var chatConfig = await GetChatConfiguration(message.Chat.Id);

                chatConfig.CorrectionStrictnessLevel = CorrectionStrictnessLevels.Intolerant;

                // Fire and forget
                _ = _chatConfigurationService.Update(chatConfig);

                await _client.SendTextMessageAsync(message.Chat.Id, "Intolerant ✅");
            }

            bool IsCommand(string expected, string actual)
            {
                if (actual.Contains("@"))
                {
                    // TODO: Get bot name from config
                    return(_webHostEnvironment.IsDevelopment()
                        ? actual.StartsWith($"{expected}@grammarNaziTest_Bot")
                        : actual.StartsWith($"{expected}@grammarNz_Bot"));
                }

                return(actual.StartsWith(expected));
            }

            async Task <bool> IsUserAdmin()
            {
                if (message.Chat.Type == ChatType.Private)
                {
                    return(true);
                }

                var chatAdministrators = await _client.GetChatAdministratorsAsync(message.Chat.Id);

                var currentUserId = message.From.Id;

                return(chatAdministrators.Any(v => v.User.Id == currentUserId));
            }
        public async Task ProcessMessageAsync(ITelegramBotClient botClient, Message message)
        {
            switch (message.Type)
            {
            case MessageType.Text:
            {
                var chat = message.Chat;

                if (chat == null)
                {
                    return;
                }

                if (message.Entities == null)
                {
                    return;
                }

                if (message.Entities.Length >= 1)
                {
                    var firstEntity = message.Entities[0];

                    if (firstEntity.Type == MessageEntityType.BotCommand && firstEntity.Offset == 0)
                    {
                        var botCommand = message.EntityValues.First().ToLower();
                        var botParts   = botCommand.Split('@');
                        if (botParts.Length > 1)
                        {
                            if (botParts[1] != (await botClient.GetMeAsync()).Username.ToLower())
                            {
                                return;
                            }
                        }

                        botCommand = botParts[0];

                        var processor = this.commandProcessors.Where(p => p.Command == botCommand).FirstOrDefault();

                        if (processor == null)
                        {
                            await botClient.SendTextMessageAsync(message.Chat.Id, "Unknown command " + botCommand, replyToMessageId : message.MessageId);

                            return;
                        }

                        switch (processor.AccessLevel)
                        {
                        case AccessLevel.Public:
                            break;

                        case AccessLevel.Administrator:
                        {
                            var administrators = await botClient.GetChatAdministratorsAsync(message.Chat.Id);

                            if (!administrators.Any(a => a.User.Id == message.From.Id))
                            {
                                await botClient.SendTextMessageAsync(message.Chat.Id, "Sorry, only admins can run that command.", replyToMessageId : message.MessageId);

                                return;
                            }
                        }
                        break;

                        case AccessLevel.Owner:
                        {
                            var adminUserIds = Environment.GetEnvironmentVariable("BOT_ADMIN_USERIDS");
                            var adminIds     = adminUserIds.Split(';');

                            bool isAdmin = false;
                            foreach (var id in adminIds)
                            {
                                var idNumber = int.Parse(id);
                                if (message.From.Id == idNumber)
                                {
                                    isAdmin = true;
                                    break;
                                }
                            }

                            if (!isAdmin)
                            {
                                await botClient.SendTextMessageAsync(message.Chat.Id, "Sorry, only owners can run that command.", replyToMessageId : message.MessageId);

                                return;
                            }
                        }
                        break;
                        }

                        await processor.ExecuteAsync(botClient, message);
                    }
                }
            }
            break;
            }
        }
Beispiel #15
0
        static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            // UPDATE ADMINS
            ChatMember[] chatAdmins = await vozBot.GetChatAdministratorsAsync(e.Message.Chat);

            List <Admin> admins = new List <Admin>();

            for (int i = 0; i < chatAdmins.Length; i++)
            {
                admins.Add(new Admin {
                    UserId = chatAdmins[i].User.Id
                });
            }
            AccessAdmin.UpdateAdmin(admins);

            // WELCOME
            //-- Get welcome
            if (e.Message.NewChatMembers != null && e.Message.NewChatMembers.Length > 0)
            {
                Random rnd   = new Random();
                int    index = rnd.Next(AccessWelcome.GetWelcome().Count());
                await vozBot.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : MessageHelper.Unmasking(AccessWelcome.GetWelcome()[index].Message, e.Message.From.FirstName, e.Message.From.LastName, e.Message.From.Username, e.Message.Chat.Title)
                    );
            }
            //-- Set welcome
            if (e.Message.Text != null)
            {
                if (e.Message.Text.ToUpper().Contains("/WELCOME "))
                {
                    if (AccessAdmin.GetAdmin().Exists(x => x.UserId == e.Message.From.Id) && MessageHelper.Reform(e.Message.Text.Remove(0, 8)) != "")
                    {
                        AccessWelcome.AddWelcome(new Welcome()
                        {
                            Message = MessageHelper.Reform(e.Message.Text.Remove(0, 8))
                        });

                        await vozBot.SendTextMessageAsync(
                            chatId : e.Message.Chat,
                            text : "Xong!",
                            replyToMessageId : e.Message.MessageId
                            );
                    }
                    else
                    {
                        await vozBot.SendTextMessageAsync(
                            chatId : e.Message.Chat,
                            text : "Không được đâu bạn êy!",
                            replyToMessageId : e.Message.MessageId
                            );
                    }
                }
            }


            // NOTE



            // FILTER
            //-- Get filter
            if (e.Message.Text != null)
            {
                double max       = 0;
                Filter mostMatch = new Filter();
                foreach (var filter in AccessFilter.GetFilter())
                {
                    if (MessageHelper.MatchingRate(e.Message.Text, filter.Key) > max)
                    {
                        max       = MessageHelper.MatchingRate(e.Message.Text, filter.Key);
                        mostMatch = filter;
                    }
                }
                if (max > 0)
                {
                    await vozBot.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : MessageHelper.Unmasking(mostMatch.Message, e.Message.From.FirstName, e.Message.From.LastName, e.Message.From.Username, e.Message.Chat.Title),
                        replyToMessageId : e.Message.MessageId
                        );
                }
            }

            //-- Set filter
            if (e.Message.Text != null)
            {
                if (e.Message.Text.ToUpper().Contains("/FILTER "))
                {
                    if (AccessAdmin.GetAdmin().Exists(x => x.UserId == e.Message.From.Id) && MessageHelper.Reform(e.Message.Text.Remove(0, 7)) != "")
                    {
                        try
                        {
                            char          delim = '|';
                            List <string> keys  = MessageHelper.Reform(e.Message.Text.Remove(0, 7)).Split(delim, StringSplitOptions.RemoveEmptyEntries).ToList();
                            for (int i = 0; i < keys.Count; i++)
                            {
                                keys[i] = keys[i].Trim();
                            }
                            foreach (string key in keys)
                            {
                                if (key == "")
                                {
                                    keys.Remove(key);
                                }
                            }
                            Filter filter = new Filter {
                                Message = keys.Last()
                            };
                            keys.Remove(keys.Last());
                            filter.Key = keys;
                            AccessFilter.AddFilter(filter);

                            await vozBot.SendTextMessageAsync(
                                chatId : e.Message.Chat,
                                text : "Đã xong!",
                                replyToMessageId : e.Message.MessageId
                                );
                        }
                        catch (NullReferenceException)
                        {
                            await vozBot.SendTextMessageAsync(
                                chatId : e.Message.Chat,
                                text : "Lỗi rồi comrade ơi :(",
                                replyToMessageId : e.Message.MessageId
                                );
                        }
                    }
                }
            }


            // Bio
            //-- Get bio
            if (e.Message.Text != null)
            {
                if (e.Message.Text.ToUpper() == "/BIO")
                {
                    bool found = false;
                    if (e.Message.ReplyToMessage == null)
                    {
                        foreach (var bio in AccessBio.GetBio())
                        {
                            if (e.Message.From.Id == bio.UserId)
                            {
                                await vozBot.SendTextMessageAsync(
                                    chatId : e.Message.Chat,
                                    text : MessageHelper.Unmasking(bio.UserBio, e.Message.From.FirstName, e.Message.From.LastName, e.Message.From.Username, e.Message.Chat.Title),
                                    replyToMessageId : e.Message.MessageId
                                    );

                                found = true;
                            }
                        }
                        if (!found)
                        {
                            await vozBot.SendTextMessageAsync(
                                chatId : e.Message.Chat,
                                text : MessageHelper.Reform($"{e.Message.From.FirstName} {e.Message.From.LastName} chưa có cái bio nào cả. Comrade nào viết bio cho {e.Message.From.FirstName} {e.Message.From.LastName} đi mà..."),
                                replyToMessageId : e.Message.MessageId
                                );
                        }
                    }
                    else
                    {
                        foreach (var bio in AccessBio.GetBio())
                        {
                            if (e.Message.ReplyToMessage.From.Id == bio.UserId)
                            {
                                await vozBot.SendTextMessageAsync(
                                    chatId : e.Message.Chat,
                                    text : MessageHelper.Unmasking(bio.UserBio, e.Message.ReplyToMessage.From.FirstName, e.Message.ReplyToMessage.From.LastName, e.Message.ReplyToMessage.From.Username, e.Message.Chat.Title),
                                    replyToMessageId : e.Message.MessageId
                                    );

                                found = true;
                            }
                        }
                        if (!found)
                        {
                            await vozBot.SendTextMessageAsync(
                                chatId : e.Message.Chat,
                                text : MessageHelper.Reform($"{e.Message.ReplyToMessage.From.FirstName} {e.Message.ReplyToMessage.From.LastName} chưa có cái bio nào cả. Comrade nào viết bio cho {e.Message.ReplyToMessage.From.FirstName} {e.Message.ReplyToMessage.From.LastName} đi mà..."),
                                replyToMessageId : e.Message.MessageId
                                );
                        }
                    }
                }
            }

            //-- Set bio
            if (e.Message.Text != null)
            {
                if (e.Message.Text.ToUpper().Contains("/SETBIO "))
                {
                    if (e.Message.ReplyToMessage == null || e.Message.From.Id == e.Message.ReplyToMessage.From.Id)
                    {
                        await vozBot.SendTextMessageAsync(
                            chatId : e.Message.Chat,
                            text : "Tự trọng đê bạn êi!",
                            replyToMessageId : e.Message.MessageId
                            );
                    }
                    else if (AccessAdmin.GetAdmin().Exists(x => x.UserId == e.Message.From.Id) && MessageHelper.Reform(e.Message.Text.Remove(0, 7)) != "")
                    {
                        string biotext = MessageHelper.Reform($"{e.Message.ReplyToMessage.From.FirstName} {e.Message.ReplyToMessage.From.LastName}:\n") + MessageHelper.Reform(e.Message.Text.Remove(0, 7));
                        AccessBio.AddBio(new Bio()
                        {
                            UserId = e.Message.ReplyToMessage.From.Id, UserBio = biotext
                        });

                        await vozBot.SendTextMessageAsync(
                            chatId : e.Message.Chat,
                            text : MessageHelper.Reform($"Đã set bio cho {e.Message.ReplyToMessage.From.FirstName} {e.Message.ReplyToMessage.From.LastName}."),
                            replyToMessageId : e.Message.MessageId
                            );
                    }
                    else
                    {
                        await vozBot.SendTextMessageAsync(
                            chatId : e.Message.Chat,
                            text : "Không set được đâu bạn êy!",
                            replyToMessageId : e.Message.MessageId
                            );
                    }
                }
            }


            /// Private chat
        }
Beispiel #16
0
        private static void GetAdminsList()
        {
            var admins = BotClient.GetChatAdministratorsAsync(Vault.ChannelId).GetAwaiter().GetResult();

            adminIds = admins.Select(x => x.User.Id).ToList();
        }
 public Task <ChatMember[]> GetChatAdministratorsAsync(ChatId chatId, CancellationToken cancellationToken = default)
 {
     return(_client.GetChatAdministratorsAsync(chatId, cancellationToken));
 }