Exemplo n.º 1
0
        public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
                                               CancellationToken cancellationToken)
        {
            Message msg = context.Update.Message;

            _telegramService = new TelegramService(context);
            _settingsService = new SettingsService(msg);

            var id       = msg.From.Id;
            var sendText = "Under maintenance";

            await _telegramService.DeleteAsync(msg.MessageId)
            .ConfigureAwait(false);

            await _telegramService.SendTextAsync("🔄 Loading tags..")
            .ConfigureAwait(false);

            var tagsData = await _tagsService.GetTagsByGroupAsync("*", msg.Chat.Id)
                           .ConfigureAwait(false);

            var tagsStr = string.Empty;

            foreach (var tag in tagsData)
            {
                tagsStr += $"#{tag.Tag} ";
            }

            sendText = $"#️⃣<b> {tagsData.Count} Tags</b>\n" +
                       $"\n{tagsStr}";

            await _telegramService.EditAsync(sendText)
            .ConfigureAwait(false);

            //            var jsonSettings = TextHelper.ToJson(currentSetting);
            //            Log.Information($"CurrentSettings: {jsonSettings}");

            // var lastTagsMsgId = int.Parse(currentSetting.Rows[0]["last_tags_message_id"].ToString());

            var currentSetting = await _settingsService.GetSettingByGroup()
                                 .ConfigureAwait(false);

            var lastTagsMsgId = currentSetting.LastTagsMessageId;

            Log.Information($"LastTagsMsgId: {lastTagsMsgId}");

            if (lastTagsMsgId.ToInt() > 0)
            {
                await _telegramService.DeleteAsync(lastTagsMsgId.ToInt())
                .ConfigureAwait(false);
            }
            await _tagsService.UpdateCacheAsync(msg)
            .ConfigureAwait(false);

            await _settingsService.UpdateCell("last_tags_message_id", _telegramService.SentMessageId)
            .ConfigureAwait(false);


//            var json = TextHelper.ToJson(tagsData);
            //                Console.WriteLine(json);
        }
        public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
                                               CancellationToken cancellationToken)
        {
            _telegramService = new TelegramService(context);

            var isSudoer = _telegramService.IsSudoer();
            var isAdmin  = await _telegramService.IsAdminGroup()
                           .ConfigureAwait(false);

            if (isSudoer)
            {
                await _telegramService.DeleteAsync(_telegramService.Message.MessageId)
                .ConfigureAwait(false);

                await _telegramService.AppendTextAsync("Sedang mengsinkronkan Word Filter")
                .ConfigureAwait(false);

                await Sync.SyncWordToLocalAsync().ConfigureAwait(false);

                await _telegramService.AppendTextAsync("Selesai mengsinkronkan.")
                .ConfigureAwait(false);

                await _telegramService.DeleteAsync(delay : 3000)
                .ConfigureAwait(false);
            }
        }
Exemplo n.º 3
0
    public override async Task HandleAsync(
        IUpdateContext context,
        UpdateDelegate next,
        string[] args
        )
    {
        await _telegramService.AddUpdateContext(context);

        var msg    = _telegramService.Message;
        var chat   = _telegramService.Message.Chat;
        var chatId = _telegramService.ChatId;

        await _telegramService.DeleteSenderMessageAsync();

        if (!await _telegramService.CheckUserPermission())
        {
            Log.Warning("Settings command only for Admin group or Private chat");
            return;
        }

        Log.Information("Initializing reset Settings");
        await _telegramService.DeleteAsync(msg.MessageId);

        await _telegramService.SendTextMessageAsync("Sedang mengembalikan ke Pengaturan awal");

        var data = new Dictionary <string, object>()
        {
            ["chat_id"]                   = chat.Id,
            ["chat_title"]                = chat.Title,
            ["enable_afk_status"]         = 1,
            ["enable_anti_malfiles"]      = 1,
            ["enable_fed_cas_ban"]        = 1,
            ["enable_fed_es2_ban"]        = 1,
            ["enable_fed_spamwatch"]      = 1,
            ["enable_url_filtering"]      = 1,
            ["enable_human_verification"] = 1,
            ["enable_reply_notification"] = 1,
            ["enable_warn_username"]      = 1,
            ["enable_word_filter_group"]  = 1,
            ["enable_word_filter_global"] = 1,
            ["enable_welcome_message"]    = 1
        };

        var update = await _settingsService.SaveSettingsAsync(data);

        await _settingsService.UpdateCacheAsync(chatId);

        Log.Information("Result: {Update}", update);

        await _telegramService.EditMessageTextAsync("Pengaturan awal berhasil di kembalikan");

        await _telegramService.DeleteAsync(_telegramService.EditedMessageId, 2000);

        Log.Information("Settings has been reset");
    }
Exemplo n.º 4
0
        public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
                                               CancellationToken cancellationToken)
        {
            _telegramService = new TelegramService(context);
            _settingsService = new SettingsService(_telegramService.Message);
            var chat = _telegramService.Message.Chat;
            var msg  = _telegramService.Message;

            var adminOrPrivate = await _telegramService.IsAdminOrPrivateChat()
                                 .ConfigureAwait(false);

            if (adminOrPrivate)
            {
                Log.Information("Initializing reset Settings.");
                await _telegramService.DeleteAsync(msg.MessageId)
                .ConfigureAwait(false);

                await _telegramService.SendTextAsync("Sedang mengembalikan ke Pengaturan awal")
                .ConfigureAwait(false);

                var data = new Dictionary <string, object>()
                {
                    ["chat_id"]                       = chat.Id,
                    ["chat_title"]                    = chat.Title,
                    ["enable_afk_stats"]              = 1,
                    ["enable_anti_malfiles"]          = 1,
                    ["enable_fed_cas_ban"]            = 1,
                    ["enable_fed_es2"]                = 1,
                    ["enable_fed_spamwatch"]          = 1,
                    ["enable_url_filtering"]          = 1,
                    ["enable_human_verification"]     = 1,
                    ["enable_reply_notification"]     = 1,
                    ["enable_warn_username"]          = 1,
                    ["enable_word_filter_group_wide"] = 1,
                    ["enable_word_filter_per_group"]  = 1,
                    ["enable_welcome_message"]        = 1,
                };

                var update = await _settingsService.SaveSettingsAsync(data)
                             .ConfigureAwait(false);

                Log.Information($"Result: {update}");

                await _telegramService.EditAsync("Pengaturan awal berhasil di kembalikan")
                .ConfigureAwait(false);

                await _telegramService.DeleteAsync(_telegramService.EditedMessageId, 2000)
                .ConfigureAwait(false);

                Log.Information("Settings has been reset.");
            }
        }
        public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
                                               CancellationToken cancellationToken)
        {
            _telegramService = new TelegramService(context);
            _settingsService = new SettingsService(context.Update.Message);
            var message = _telegramService.Message;

            await _telegramService.DeleteAsync(message.MessageId)
            .ConfigureAwait(false);

            var adminOrPrivate = await _telegramService.IsAdminOrPrivateChat()
                                 .ConfigureAwait(false);

            if (adminOrPrivate)
            {
                await _telegramService.SendTextAsync("Sedang mengambil pengaturan..")
                .ConfigureAwait(false);

                var settings = await _settingsService.GetSettingButtonByGroup()
                               .ConfigureAwait(false);

                var btnMarkup = await settings.ToJson().JsonToButton(chunk: 2)
                                .ConfigureAwait(false);

                Log.Debug($"Settings: {settings.Count}");

                await _telegramService.EditAsync("Settings Toggles", btnMarkup)
                .ConfigureAwait(false);
            }
        }
Exemplo n.º 6
0
        private static async Task ScanMessageAsync(this TelegramService telegramService)
        {
            var message = telegramService.MessageOrEdited;
            var msgId   = message.MessageId;

            var text = message.Text ?? message.Caption;

            if (!text.IsNullOrEmpty())
            {
                var isMustDelete = await IsMustDelete(text)
                                   .ConfigureAwait(false);

                Log.Information($"Message {msgId} IsMustDelete: {isMustDelete}");

                if (isMustDelete)
                {
                    await telegramService.DeleteAsync(message.MessageId)
                    .ConfigureAwait(false);
                }
            }
            else
            {
                Log.Information("No message Text for scan.");
            }
        }
Exemplo n.º 7
0
    public override async Task HandleAsync(
        IUpdateContext context,
        UpdateDelegate next,
        string[] args
        )
    {
        await _telegramService.AddUpdateContext(context);

        var isSudoer = _telegramService.IsFromSudo;

        await _telegramService.DeleteSenderMessageAsync();

        if (!isSudoer)
        {
            Log.Debug("Only sudo can do Sync Kata!");
            return;
        }

        await _telegramService.AppendTextAsync("Sedang mengsinkronkan Word Filter");

        await _wordFilterService.UpdateWordListsCache();

        await _telegramService.AppendTextAsync("Selesai mengsinkronkan.");

        await _telegramService.DeleteAsync(delay : 3000);
    }
Exemplo n.º 8
0
        public static async Task<bool> CheckGlobalBanAsync(this TelegramService telegramService,
            User userTarget = null)
        {
            Log.Information("Starting check Global Ban");

            var message = telegramService.MessageOrEdited;
            var user = message.From;

            // var settingService = new SettingsService(message);
            var chatSettings = telegramService.CurrentSetting;
            if (!chatSettings.EnableFedEs2)
            {
                Log.Information("Fed ES2 Ban is disabled in this Group!");
                return false;
            }

            if (userTarget != null) user = userTarget;

            var messageId = message.MessageId;

            var isBan = await user.Id.CheckGBan()
                .ConfigureAwait(false);
            Log.Information($"IsBan: {isBan}");
            if (isBan)
            {
                await telegramService.DeleteAsync(messageId)
                    .ConfigureAwait(false);
                await telegramService.KickMemberAsync(user)
                    .ConfigureAwait(false);
                await telegramService.UnbanMemberAsync(user)
                    .ConfigureAwait(false);
            }

            return isBan;
        }
Exemplo n.º 9
0
        public async Task HandleAsync(IUpdateContext context, UpdateDelegate next, CancellationToken cancellationToken)
        {
            _telegramService = new TelegramService(context);
            var msg = context.Update.Message;

            Log.Information("Media received... ");
            var fileId        = msg.GetFileId();
            var reducedFileId = msg.GetReducedFileId();

            // var isBan = await _mediaFilterService.IsExistInCache("file_id", msg.GetReducedFileId());
            var isBan = await _mediaFilterService.IsExist("file_id", fileId)
                        .ConfigureAwait(false);

            if (isBan)
            {
                await _telegramService.DeleteAsync(msg.MessageId)
                .ConfigureAwait(false);
            }

            Log.Information($"Media isBan: {isBan}");

            if (BotSettings.HostingEnvironment.IsProduction())
            {
                await _mediaFilterService.UpdateCacheAsync()
                .ConfigureAwait(false);
            }
            else
            {
                Log.Information($"Update cache skipped because local Env");
            }

            Log.Information("Media Filter complete.");

            await next(context, cancellationToken).ConfigureAwait(false);
        }
Exemplo n.º 10
0
        private static async Task ScanPhotoAsync(this TelegramService telegramService)
        {
            var message = telegramService.MessageOrEdited;
            var chatId  = message.Chat.Id;
            var msgId   = message.MessageId;

            if (message.Photo != null)
            {
                Log.Information("");

                var fileName = $"{chatId}/ocr-{msgId}.jpg";
                Log.Information("Preparing photo");
                var savedFile = await telegramService.DownloadFileAsync(fileName)
                                .ConfigureAwait(false);

                // var ocr = await TesseractProvider.OcrSpace(savedFile)
                //     .ConfigureAwait(false);
                var ocr = GoogleVision.ScanText(savedFile);


                Log.Information("Scanning message..");
                var isMustDelete = await IsMustDelete(ocr)
                                   .ConfigureAwait(false);

                Log.Information($"Message {message.MessageId} IsMustDelete: {isMustDelete}");

                if (isMustDelete)
                {
                    await telegramService.DeleteAsync(message.MessageId)
                    .ConfigureAwait(false);
                }

                savedFile.GetDirectory().RemoveFiles("ocr");
            }
        }
    public static async Task DeleteMessageManyAsync(
        this TelegramService telegramService,
        long customUserId = -1
        )
    {
        var wTelegramService = telegramService.GetRequiredService <WTelegramApiService>();
        var chatId           = telegramService.ChatId;
        var userId           = customUserId == -1 ? telegramService.FromId : customUserId;
        var messageId        = telegramService.AnyMessage.MessageId;

        var messageIds = await wTelegramService.GetMessagesIdByUserId(
            chatId : chatId,
            userId : userId,
            lastMessageId : messageId
            );

        Log.Debug(
            "Deleting {MessageIdsCount} Messages for UserId {UserId}",
            messageIds.Count,
            userId
            );

        await messageIds.AsyncParallelForEach(
            maxDegreeOfParallelism : 8,
            body : async id => {
            await telegramService.DeleteAsync(id);
        }
            );
    }
Exemplo n.º 12
0
    public override async Task HandleAsync(
        IUpdateContext context,
        UpdateDelegate next,
        string[] args
        )
    {
        await _telegramService.AddUpdateContext(context);

        var chatId = _telegramService.ChatId;

        var checkUserPermission = await _telegramService.CheckUserPermission();

        if (!checkUserPermission)
        {
            Log.Warning("Delete RSS only for admin or private chat!");
            await _telegramService.DeleteAsync();

            return;
        }

        var urlFeed = _telegramService.Message.Text.GetTextWithoutCmd();

        await _telegramService.SendTextMessageAsync($"Sedang menghapus {urlFeed}");

        var delete = await _rssService.DeleteRssAsync(chatId, urlFeed);

        var success = delete.ToBool()
            ? "berhasil."
            : "gagal. Mungkin RSS tersebut sudah di hapus atau belum di tambahkan";

        await _telegramService.EditMessageTextAsync($"Hapus {urlFeed} {success}");

        await _rssFeedService.ReRegisterRssFeedByChatId(chatId);
    }
Exemplo n.º 13
0
    private async Task ExecuteBackupDb()
    {
        await _telegramService.SendTextMessageAsync("⬇ Sedang mencadangkan Database..", replyToMsgId : 0);

        var dataBackupInfo = await _databaseService.BackupMySqlDatabase();

        var fullNameZip = dataBackupInfo.FullNameZip;

        var sentMessage = await _telegramService.EditMessageTextAsync("⬆ Sedang mengunggah berkas..");

        var caption = $"File Size: {dataBackupInfo.FileSizeSql}";

        await _telegramService.SendMediaAsync(fullNameZip, MediaType.LocalDocument, caption);

        await _telegramService.DeleteAsync(sentMessage.MessageId);
    }
Exemplo n.º 14
0
    public override async Task HandleAsync(
        IUpdateContext context,
        UpdateDelegate next,
        string[] args
        )
    {
        await _telegramService.AddUpdateContext(context);

        var chatId       = _telegramService.ChatId;
        var messageTexts = _telegramService.MessageTextParts;
        var word         = messageTexts.ElementAtOrDefault(1);
        var isSudo       = _telegramService.IsFromSudo;

        if (!isSudo)
        {
            _logger.Warning("Delete Kata currently only for Sudo!");
            await _telegramService.DeleteAsync();

            return;
        }

        if (word.IsNullOrEmpty())
        {
            await _telegramService.SendTextMessageAsync("Kata apa yang mau di hapus?");
        }

        await _telegramService.SendTextMessageAsync("Sedang menghapus Kata..");

        var wordFilter = new WordFilter()
        {
            Word = word
        };

        var delete = await _wordFilterService.DeleteKata(wordFilter);

        var deleteResult = delete > 0 ? "Kata berhasil di hapus" : "Kata sudah dihapus";
        await _telegramService.EditMessageTextAsync(deleteResult);

        await _wordFilterService.UpdateWordListsCache();
    }
Exemplo n.º 15
0
    public static async Task <bool> OnCallbackDeleteAsync(this TelegramService telegramService)
    {
        var chatId        = telegramService.ChatId;
        var fromId        = telegramService.FromId;
        var messageTarget = telegramService.GetCallbackDataAt <string>(1);

        Log.Information(
            "Callback delete message at ChatId: {ChatId}. Target: {MessageTarget}",
            chatId,
            messageTarget
            );

        if (!await telegramService.CheckUserPermission())
        {
            Log.Information(
                "UserId: '{UserId}' at ChatId: '{ChatId}' has no permission to delete message",
                fromId,
                chatId
                );

            await telegramService.AnswerCallbackQueryAsync("Kamu tidak mempunyai akses melakukan tindakan ini!", true);

            return(true);
        }

        if (messageTarget == "current-message")
        {
            await telegramService.DeleteCurrentCallbackMessageAsync();
        }
        else
        {
            var messageId = telegramService.GetCallbackDataAt <int>(1);
            await telegramService.DeleteAsync(messageId);
        }

        return(true);
    }
Exemplo n.º 16
0
        public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
                                               CancellationToken cancellationToken)
        {
            _telegramService = new TelegramService(context);
            var client    = _telegramService.Client;
            var message   = _telegramService.Message;
            var partsText = message.Text.SplitText(" ").ToArray();
            var chatId    = message.Chat.Id;
            var listAlbum = new List <IAlbumInputMedia>();
            var catSource = "http://aws.random.cat/meow";
            var catNum    = 1;
            var param1    = partsText.ValueOfIndex(1);

            if (param1.IsNotNullOrEmpty())
            {
                if (!param1.IsNumeric())
                {
                    await _telegramService.SendTextAsync("Pastikan jumlah kochenk yang diminta berupa angka.")
                    .ConfigureAwait(false);

                    return;
                }

                catNum = param1.ToInt();

                if (catNum > 10)
                {
                    await _telegramService.SendTextAsync("Batas maksimal Kochenk yg di minta adalah 10")
                    .ConfigureAwait(false);

                    return;
                }
            }

            await _telegramService.SendTextAsync($"Sedang mempersiapkan {catNum} Kochenk")
            .ConfigureAwait(false);

            for (int i = 1; i <= catNum; i++)
            {
                Log.Information($"Loading cat {i} of {catNum} from {catSource}");
                // await _telegramService.EditAsync($"Sedang mengambil {i} of {catNum} Kochenk")
                //     .ConfigureAwait(false);

                var url = await catSource
                          .GetJsonAsync <CatMeow>(cancellationToken)
                          .ConfigureAwait(false);

                var urlFile = url.File.AbsoluteUri;

                Log.Information($"Adding kochenk {urlFile}");

                var fileName  = Path.GetFileName(urlFile);
                var timeStamp = DateTime.UtcNow.ToString("yyyy-MM-dd");
                var saveName  = Path.Combine(chatId.ToString(), $"kochenk_{timeStamp}_" + fileName);
                var savedPath = urlFile.SaveToCache(saveName);

                var fileStream = File.OpenRead(savedPath);
                // listAlbum.Add(new InputMediaPhoto()
                // {
                // Caption = $"Kochenk {i}",
                // Media = new InputMedia(fileStream, fileName),
                // ParseMode = ParseMode.Html
                // });

                var inputMediaPhoto = new InputMediaPhoto(new InputMedia(fileStream, fileName))
                {
                    Caption   = $"Kochenk {i}",
                    ParseMode = ParseMode.Html
                };
                listAlbum.Add(inputMediaPhoto);

                // listAlbum.Add(new InputMediaPhoto(new InputMedia()));
                await fileStream.DisposeAsync().ConfigureAwait(false);

                Thread.Sleep(100);
            }

            await _telegramService.DeleteAsync().ConfigureAwait(false);

            await client.SendMediaGroupAsync(listAlbum, chatId, cancellationToken : cancellationToken)
            .ConfigureAwait(false);
        }
Exemplo n.º 17
0
        public static async Task CheckUsernameAsync(this TelegramService telegramService)
        {
            try
            {
                Log.Information("Starting check Username");

                var warnLimit = 4;
                var message = telegramService.MessageOrEdited;
                var fromUser = message.From;
                var nameLink = fromUser.GetNameLink();

                // var settingService = new SettingsService(message);
                var chatSettings = telegramService.CurrentSetting;
                if (!chatSettings.EnableWarnUsername)
                {
                    Log.Information("Warn Username is disabled in this Group!");
                    return;
                }

                var noUsername = fromUser.IsNoUsername();
                Log.Information($"{fromUser} IsNoUsername: {noUsername}");

                if (noUsername)
                {
                    var updateResult = await UpdateWarnUsernameStat(message)
                        .ConfigureAwait(false);
                    var updatedStep = updateResult.StepCount;
                    var lastMessageId = updateResult.LastWarnMessageId;

                    await telegramService.DeleteAsync(lastMessageId)
                        .ConfigureAwait(false);

                    var sendText = $"Hai {nameLink}, kamu belum memasang username!" +
                                   $"\nPeringatan ke {updatedStep} dari {warnLimit}";

                    if (updatedStep == warnLimit) sendText += "\n\n<b>Ini peringatan terakhir!</b>";

                    if (updatedStep > warnLimit)
                    {
                        var sendWarn = $"Batas peringatan telah di lampaui." +
                                       $"\n{nameLink} di tendang sekarang!";
                        await telegramService.SendTextAsync(sendWarn)
                            .ConfigureAwait(false);

                        await telegramService.KickMemberAsync(fromUser)
                            .ConfigureAwait(false);
                        await telegramService.UnbanMemberAsync(fromUser)
                            .ConfigureAwait(false);
                        await ResetWarnUsernameStatAsync(message)
                            .ConfigureAwait(false);

                        return;
                    }

                    var urlStart = await telegramService.GetUrlStart("start=set-username")
                        .ConfigureAwait(false);
                    Log.Information($"UrlStart: {urlStart}");

                    var keyboard = new InlineKeyboardMarkup(
                        InlineKeyboardButton.WithUrl("Cara Pasang Username", urlStart)
                    );

                    await telegramService.SendTextAsync(sendText, keyboard)
                .ConfigureAwait(false);
                    await message.UpdateLastWarnUsernameMessageIdAsync(telegramService.SentMessageId)
                        .ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error check Username");
            }
        }
Exemplo n.º 18
0
        public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
                                               CancellationToken cancellationToken)
        {
            _telegramService = new TelegramService(context);

            var kickTargets = new List <User>();

            var     msg    = context.Update.Message;
            Message repMsg = null;
            var     fromId = msg.From.Id;

            // var idTargets = new List<int>();

            kickTargets.Add(msg.From);

            if (msg.ReplyToMessage != null)
            {
                repMsg = msg.ReplyToMessage;
                // idTarget = repMsg.From.id;
                kickTargets.Add(repMsg.From);

                if (repMsg.NewChatMembers != null)
                {
                    kickTargets.Clear();
                    var userTargets = repMsg.NewChatMembers;
                    kickTargets.AddRange(userTargets);

                    // foreach (var target in userTargets)
                    // {
                    //     idTargets.Add(target.Id);
                    // }
                }
            }

            await _telegramService.DeleteAsync(msg.MessageId)
            .ConfigureAwait(false);

            var isAdmin = await _telegramService.IsAdminGroup()
                          .ConfigureAwait(false);

            if (kickTargets[0].Id != msg.From.Id && isAdmin)
            {
                var isKicked = false;
                foreach (var target in kickTargets)
                {
                    var idTarget = target.Id;
                    var sendText = string.Empty;

                    // await _chatProcessor.AppendTextAsync($"Sedang menendang {idTarget}");
                    isKicked = await _telegramService.KickMemberAsync(target)
                               .ConfigureAwait(false);

                    await _telegramService.UnbanMemberAsync(target)
                    .ConfigureAwait(false);

                    if (isKicked)
                    {
                        sendText = $"{target} berhasil di tendank ";

                        sendText += idTarget == fromId ? $"oleh Self-kick" : $".";
                    }
                    else
                    {
                        sendText = $"Gagal menendang {idTarget}";
                    }

                    await _telegramService.AppendTextAsync(sendText)
                    .ConfigureAwait(false);
                }

                if (isKicked)
                {
                    await _telegramService.AppendTextAsync($"Sebanyak {kickTargets.Count} berhasil di tendang.")
                    .ConfigureAwait(false);
                }
                else
                {
                    await _telegramService.AppendTextAsync("Gagal menendang bbrp anggota")
                    .ConfigureAwait(false);
                }
            }
            else if (kickTargets[0].Id == fromId)
            {
                var idTarget = kickTargets[0];
                var isKicked = false;
                // await _chatProcessor.AppendTextAsync($"Sedang menendang {idTarget}");
                isKicked = await _telegramService.KickMemberAsync(idTarget)
                           .ConfigureAwait(false);

                if (isKicked)
                {
                    var sendText = $"{idTarget} berhasil di tendang ";
                    sendText += idTarget.Id == fromId ? $"oleh Self-kick" : $".";
                    await _telegramService.AppendTextAsync(sendText)
                    .ConfigureAwait(false);
                }
                else
                {
                    var sendTexts = $"Tendang {idTarget} gagal.";
                    await _telegramService.SendTextAsync(sendTexts)
                    .ConfigureAwait(false);
                }
            }
            else
            {
                await _telegramService.SendTextAsync("Hanya admin yang bisa mengeksekusi")
                .ConfigureAwait(false);
            }
        }
Exemplo n.º 19
0
    public override async Task HandleAsync(
        IUpdateContext context,
        UpdateDelegate next,
        string[] args
        )
    {
        await _telegramService.AddUpdateContext(context);

        var chatId = _telegramService.ChatId;
        var fromId = _telegramService.FromId;

        var messageTextParts = _telegramService.MessageTextParts;
        var word             = messageTextParts.ElementAtOrDefault(1) ?? string.Empty;
        var paramOption      = messageTextParts.ElementAtOrDefault(2) ?? string.Empty;

        var isGlobalBlock = false;

        var isSudoer = _telegramService.IsFromSudo;

        if (!isSudoer)
        {
            await _telegramService.DeleteSenderMessageAsync();

            Log.Information("Currently add Kata is limited only Sudo");
            return;
        }

        if (word.IsValidUrl())
        {
            word = word.ParseUrl().Path;
        }

        var where = new Dictionary <string, object>()
        {
            { "word", word }
        };

        if (paramOption.IsContains("-"))
        {
            if (paramOption.IsContains("g"))// Global
            {
                isGlobalBlock = true;
                await _telegramService.AppendTextAsync("Kata ini akan di blokir Global!");
            }
        }

        if (!paramOption.IsContains("g"))
        {
            @where.Add("chat_id", chatId);
        }

        if (!word.IsNotNullOrEmpty())
        {
            await _telegramService.SendTextMessageAsync("Apa kata yg mau di blok?");
        }
        else
        {
            var isExist = await _wordFilterService.IsExistAsync(@where);

            if (isExist)
            {
                await _telegramService.AppendTextAsync("Kata sudah di tambahkan");
            }
            else
            {
                await _telegramService.AppendTextAsync("Sedang menambahkan kata");

                await _wordFilterService.SaveWordAsync(new WordFilter()
                {
                    Word      = word,
                    ChatId    = chatId,
                    IsGlobal  = isGlobalBlock,
                    FromId    = fromId,
                    CreatedAt = DateTime.Now
                });

                await _telegramService.AppendTextAsync("Kata berhasil di tambahkan");

                await _wordFilterService.UpdateWordListsCache();
            }
        }

        await _telegramService.DeleteAsync(delay : 3000);
    }
Exemplo n.º 20
0
        public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
                                               CancellationToken cancellationToken)
        {
            _telegramService   = new TelegramService(context);
            _wordFilterService = new WordFilterService(context.Update.Message);

            var msg           = context.Update.Message;
            var cleanedMsg    = msg.Text.GetTextWithoutCmd();
            var partedMsg     = cleanedMsg.Split(" ");
            var paramOption   = partedMsg.ValueOfIndex(1) ?? "";
            var word          = partedMsg.ValueOfIndex(0);
            var isGlobalBlock = false;

            var isSudoer = _telegramService.IsSudoer();
            var isAdmin  = await _telegramService.IsAdminGroup()
                           .ConfigureAwait(false);

            if (!isSudoer && !isAdmin)
            {
                return;
            }

            if (word.IsValidUrl())
            {
                word = word.ParseUrl().Path;
            }

            var where = new Dictionary <string, object>()
            {
                { "word", word }
            };

            if (paramOption.IsContains("-"))
            {
                if (paramOption.IsContains("g") && isSudoer) // Global
                {
                    isGlobalBlock = true;
                    await _telegramService.AppendTextAsync("Kata ini akan di blokir Global!")
                    .ConfigureAwait(false);
                }

                if (paramOption.IsContains("d"))
                {
                }

                if (paramOption.IsContains("c"))
                {
                }
            }

            if (!paramOption.IsContains("g"))
            {
                @where.Add("chat_id", msg.Chat.Id);
            }

            if (!isSudoer)
            {
                await _telegramService.AppendTextAsync("Hanya Sudoer yang dapat memblokir Kata mode Group-wide!")
                .ConfigureAwait(false);
            }

            if (word.IsNotNullOrEmpty())
            {
                await _telegramService.AppendTextAsync("Sedang menambahkan kata")
                .ConfigureAwait(false);

                var isExist = await _wordFilterService.IsExistAsync(@where)
                              .ConfigureAwait(false);

                if (!isExist)
                {
                    var save = await _wordFilterService.SaveWordAsync(word, isGlobalBlock)
                               .ConfigureAwait(false);

                    await _telegramService.AppendTextAsync("Kata berhasil di tambahkan")
                    .ConfigureAwait(false);
                }
                else
                {
                    await _telegramService.AppendTextAsync("Kata sudah di tambahkan")
                    .ConfigureAwait(false);
                }
            }
            else
            {
                await _telegramService.SendTextAsync("Apa kata yg mau di blok?")
                .ConfigureAwait(false);
            }

            await _telegramService.DeleteAsync(delay : 3000)
            .ConfigureAwait(false);
        }
        public async Task HandleAsync(IUpdateContext context, UpdateDelegate next, CancellationToken cancellationToken)
        {
            var msg = context.Update.Message;

            _telegramService  = new TelegramService(context);
            _settingsService  = new SettingsService(msg);
            _globalBanService = new GlobalBanService(context.Update.Message);
            await _telegramService.DeleteAsync(msg.MessageId)
            .ConfigureAwait(false);

            Log.Information("New Chat Members...");

            var chatSettings = _telegramService.CurrentSetting;

            Settings = chatSettings;

            if (!chatSettings.EnableWelcomeMessage)
            {
                Log.Information("Welcome message is disabled!");
                return;
            }

            var newMembers  = msg.NewChatMembers;
            var isBootAdded = await newMembers.IsBotAdded().ConfigureAwait(false);

            if (isBootAdded)
            {
                var isRestricted = await _telegramService.EnsureChatRestrictionAsync()
                                   .ConfigureAwait(false);

                if (isRestricted)
                {
                    return;
                }

                var botName  = BotSettings.GlobalConfiguration["Engines:ProductName"];
                var sendText = $"Hai, perkenalkan saya {botName}" +
                               $"\nFYI saya di bangun ulang menggunakan .NET." +
                               $"\n\nAku adalah bot pendebug dan grup manajemen yang di lengkapi dengan alat keamanan. " +
                               $"Agar saya berfungsi penuh, jadikan saya admin dengan level standard. " +
                               $"\n\nAku akan menerapkan konfigurasi standard jika aku baru pertama kali masuk kesini. " +
                               $"\n\nUntuk melihat daftar perintah bisa ketikkan /help";

                await _telegramService.SendTextAsync(sendText).ConfigureAwait(false);

                await _settingsService.SaveSettingsAsync(new Dictionary <string, object>()
                {
                    { "chat_id", msg.Chat.Id },
                    { "chat_title", msg.Chat.Title }
                }).ConfigureAwait(false);

                if (newMembers.Length == 1)
                {
                    return;
                }
            }

            var parsedNewMember = await ParseMemberCategory(newMembers).ConfigureAwait(false);

            var allNewMember  = parsedNewMember.AllNewMember;
            var allNoUsername = parsedNewMember.AllNoUsername;
            var allNewBot     = parsedNewMember.AllNewBot;

            if (allNewMember.Length > 0)
            {
                var chatTitle   = msg.Chat.Title;
                var greet       = Time.GetTimeGreet();
                var memberCount = await _telegramService.GetMemberCount()
                                  .ConfigureAwait(false);

                var newMemberCount = newMembers.Length;

                Log.Information("Preparing send Welcome..");

                if (chatSettings.WelcomeMessage.IsNullOrEmpty())
                {
                    chatSettings.WelcomeMessage = $"Hai {allNewMember}" +
                                                  $"\nSelamat datang di kontrakan {chatTitle}" +
                                                  $"\nKamu adalah anggota ke-{memberCount}";
                }

                var sendText = chatSettings.WelcomeMessage.ResolveVariable(new
                {
                    allNewMember,
                    allNoUsername,
                    allNewBot,
                    chatTitle,
                    greet,
                    newMemberCount,
                    memberCount
                });

                InlineKeyboardMarkup keyboard = null;
                if (!chatSettings.WelcomeButton.IsNullOrEmpty())
                {
                    keyboard = chatSettings.WelcomeButton.ToReplyMarkup(2);
                }

                if (chatSettings.EnableHumanVerification)
                {
                    Log.Information("Human verification is enabled!");
                    Log.Information("Adding verify button..");

                    var userId       = newMembers[0].Id;
                    var verifyButton = $"Saya Manusia!|verify {userId}";

                    var withVerifyArr = new string[] { chatSettings.WelcomeButton, verifyButton };
                    var withVerify    = string.Join(",", withVerifyArr);

                    keyboard = withVerify.ToReplyMarkup(2);
                }

                var prevMsgId = chatSettings.LastWelcomeMessageId.ToInt();


                var sentMsgId = -1;

                if (chatSettings.WelcomeMediaType != MediaType.Unknown)
                {
                    var mediaType = (MediaType)chatSettings.WelcomeMediaType;
                    sentMsgId = (await _telegramService.SendMediaAsync(
                                     chatSettings.WelcomeMedia,
                                     mediaType,
                                     sendText,
                                     keyboard).ConfigureAwait(false)).MessageId;
                }
                else
                {
                    sentMsgId = (await _telegramService.SendTextAsync(sendText, keyboard)
                                 .ConfigureAwait(false)).MessageId;
                }

                if (!chatSettings.EnableHumanVerification)
                {
                    await _telegramService.DeleteAsync(prevMsgId).ConfigureAwait(false);
                }

                await _settingsService.SaveSettingsAsync(new Dictionary <string, object>()
                {
                    { "chat_id", msg.Chat.Id },
                    { "chat_title", msg.Chat.Title },
                    { "members_count", memberCount },
                    { "last_welcome_message_id", sentMsgId }
                }).ConfigureAwait(false);

                await _settingsService.UpdateCache().ConfigureAwait(false);
            }
            else
            {
                Log.Information("Welcome Message ignored because User is Global Banned.");
            }
        }
Exemplo n.º 22
0
    public static async Task SendRandomCatsAsync(this TelegramService telegramService)
    {
        var catSource = telegramService.CommonConfig.RandomCatSource;
        var message   = telegramService.Message;
        var partsText = message.Text.SplitText(" ").ToArray();
        var catNum    = 1;
        var param1    = partsText.ElementAtOrDefault(1);

        if (telegramService.IsCommand("/cats"))
        {
            catNum = NumberUtil.RandomInt(1, 10);
        }
        else
        {
            try
            {
                if (param1.IsNotNullOrEmpty())
                {
                    catNum = param1.ToInt();
                }
            }
            catch (Exception e)
            {
                await telegramService.SendTextMessageAsync("Pastikan jumlah kochenk yang diminta berupa angka.");

                return;
            }
        }

        if (catNum > 10)
        {
            await telegramService.SendTextMessageAsync("Berdasarkan Bot API, batas maksimal Kochenk yg dapat di minta adalah 10.");

            return;
        }

        try
        {
            await telegramService.SendTextMessageAsync($"Sedang mempersiapkan {catNum} Kochenk");

            var listAlbum = catSource switch
            {
                RandomCatSource.AwsRandomCat => await telegramService.AnimalsService.GetRandomCatsCatApi(catNum),
                RandomCatSource.TheCatApi => await telegramService.AnimalsService.GetRandomCatsCatApi(catNum),
                _ => throw new InvalidCatSourceException("Sumber kochenk tidak diketahui")
            };

            var sentMessage = await telegramService.EditMessageTextAsync($"Sedang mengirim {catNum} Kochenk");

            var sendMediaGroup = await telegramService.SendMediaGroupAsync(listAlbum);

            await telegramService.DeleteAsync(sentMessage.MessageId);

            if (sendMediaGroup.ErrorException != null)
            {
                var exception = sendMediaGroup.ErrorException;
                await telegramService.SendTextMessageAsync("Suatu kesalahan terjadi. Silakan dicoba kembali nanti.\n" + exception.Message);
            }
        }
        catch (Exception exception)
        {
            await telegramService.SendTextMessageAsync(
                sendText : "Suatu kesalahan terjadi. Silakan dicoba kembali nanti.\n" + exception.Message,
                scheduleDeleteAt : DateTime.UtcNow.AddMinutes(3)
                );
        }
    }
    public static async Task <bool> ScanMessageAsync(this TelegramService telegramService)
    {
        var chatId = telegramService.ChatId;

        try
        {
            if (telegramService.IsGlobalIgnored())
            {
                return(false);
            }

            var message           = telegramService.MessageOrEdited;
            var eventLogService   = telegramService.GetRequiredService <EventLogService>();
            var wordFilterService = telegramService.GetRequiredService <WordFilterService>();

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

            var messageId    = message.MessageId;
            var chatSettings = await telegramService.GetChatSetting();

            if (!chatSettings.EnableWordFilterGroupWide)
            {
                Log.Debug("Word Filter on {ChatId} is disabled!", chatId);
                return(false);
            }

            if (await telegramService.CheckFromAdminOrAnonymous())
            {
                Log.Debug("Scan Message disabled for Administrator. ChatId: {ChatId}", chatId);
                return(false);
            }

            var textToScan = telegramService.MessageOrEdited.CloneText(true);

            var scanMedia = await telegramService.ScanMediaAsync();

            textToScan += "\n\n" + scanMedia;

            if (telegramService.IsFromSudo &&
                (
                    textToScan.StartsWith("/dkata") ||
                    textToScan.StartsWith("/delkata") ||
                    textToScan.StartsWith("/kata")))
            {
                Log.Debug("Seem User will modify Kata!");
                return(false);
            }

            var result = await wordFilterService.IsMustDelete(textToScan);

            var isShouldDelete = result.IsSuccess;

            if (isShouldDelete)
            {
                Log.Information("Starting scan image if available..");
            }

            Log.Information(
                "Message {MsgId} IsMustDelete: {IsMustDelete}",
                messageId,
                isShouldDelete
                );

            if (!isShouldDelete)
            {
                return(false);
            }

            Log.Debug(
                "Scan Message at ChatId: {ChatId}. Result: {@V}",
                chatId,
                result
                );

            var note = "Pesan dihapus karena terdeteksi filter Kata." +
                       $"\n{result.Notes}";

            await eventLogService.SendEventLogAsync(
                chatId : chatId,
                message : message,
                text : note,
                messageFlag : MessageFlag.BadWord,
                forwardMessageId : messageId,
                deleteForwardedMessage : true
                );

            await telegramService.DeleteAsync(messageId);

            return(true);
        }
        catch (Exception exception)
        {
            Log.Error(
                exception,
                "Error occured when Scan Message at ChatId {ChatId}",
                chatId
                );

            return(false);
        }
    }