Example #1
1
 public static async void SendMessage(string txtMessage)
 {
     bot = new TelegramBotClient(Token);
     await bot.SendTextMessageAsync(Chat_ID, txtMessage);
 }
 public async Task Handle(object sender, AssetValueChangedEventArgs args)
 {
     await _telegramBotClient.SendTextMessageAsync(args.ChatId,
                                                   string.Format(NtFormat, args.Asset, args.Value));
 }
Example #3
0
 static async Task <Message> RemoveKeyboard(ITelegramBotClient botClient, Message message)
 {
     return(await botClient.SendTextMessageAsync(chatId : message.Chat.Id,
                                                 text : "Removing keyboard",
                                                 replyMarkup : new ReplyKeyboardRemove()));
 }
        public async Task ExecuteHandlerAsync(Message message)
        {
            var firewallId = _storageService.Get <string>(StorageKeys.FirewallId);

            if (string.IsNullOrEmpty(firewallId))
            {
                return;
            }

            var isNumber = int.TryParse(message.Text, out var id);

            if (isNumber)
            {
                if (id <= 0)
                {
                    await _telegramBotClient.SendTextMessageAsync(
                        chatId : message.Chat.Id,
                        text : CommonMessage.GetInvalidIndexMessage());

                    return;
                }

                var droplet = _storageService.Get <IEnumerable <DropletResponse> >(StorageKeys.Droplets)
                              .OrderBy(x => x.CreatedAt)
                              .ElementAt(id - 1);

                await _digitalOceanClient.Firewalls.RemoveDroplets(firewallId, new FirewallDroplets
                {
                    DropletIds = new List <long> {
                        droplet.Id
                    }
                });

                await _telegramBotClient.SendTextMessageAsync(
                    chatId : message.Chat.Id,
                    text : CommonMessage.GetDoneMessage());

                return;
            }


            var regExp = new Regex(RegExpPatterns.NumbersSeparatedByCommas);
            var result = regExp.Match(message.Text);

            if (result.Success)
            {
                var indexes    = message.Text.Split(",");
                var dropletIds = new List <long>();
                var droplets   = _storageService.Get <IEnumerable <DropletResponse> >(StorageKeys.Droplets)
                                 .OrderBy(x => x.CreatedAt);

                foreach (var index in indexes)
                {
                    if (int.Parse(index) <= 0)
                    {
                        continue;
                    }

                    var droplet = droplets.ElementAt(int.Parse(index) - 1);
                    dropletIds.Add(droplet.Id);
                }

                await _digitalOceanClient.Firewalls.RemoveDroplets(firewallId, new FirewallDroplets
                {
                    DropletIds = dropletIds
                });

                await _telegramBotClient.SendTextMessageAsync(
                    chatId : message.Chat.Id,
                    text : CommonMessage.GetDoneMessage());

                return;
            }

            regExp = new Regex(RegExpPatterns.NumbersSeparatedByDash);
            result = regExp.Match(message.Text);

            if (result.Success)
            {
                var indexes    = message.Text.Split("-");
                var firstIndex = int.Parse(indexes[0]);
                var lastIndex  = int.Parse(indexes[1]);

                if (firstIndex <= 0 || lastIndex <= 0)
                {
                    await _telegramBotClient.SendTextMessageAsync(
                        chatId : message.Chat.Id,
                        text : CommonMessage.GetInvalidIndexMessage());

                    return;
                }

                var dropletIds = new List <long>();
                var droplets   = _storageService.Get <IEnumerable <DropletResponse> >(StorageKeys.Droplets)
                                 .OrderBy(x => x.CreatedAt);

                for (var i = firstIndex - 1; i <= lastIndex - 1; i++)
                {
                    var droplet = droplets.ElementAt(i);
                    dropletIds.Add(droplet.Id);
                }

                await _digitalOceanClient.Firewalls.RemoveDroplets(firewallId, new FirewallDroplets
                {
                    DropletIds = dropletIds
                });

                await _telegramBotClient.SendTextMessageAsync(
                    chatId : message.Chat.Id,
                    text : CommonMessage.GetDoneMessage());
            }
        }
 public void Execute()
 {
     SessionHelper.GetSession(_callbackQueryEventArgs.CallbackQuery.From.Id).InstructionId = NextInstruction.AddRss;
     _telegramBotClient.SendTextMessageAsync(_callbackQueryEventArgs.CallbackQuery.From.Id, "enter rss url.").GetAwaiter();
 }
Example #6
0
        public async Task Instruction(Subscriber subscriber)
        {
            var text = $"I'm here to help you track your working time. " +
                       $"The following commands are available:{Environment.NewLine}" +
                       $"/standup - tasks of the previous work day{Environment.NewLine}" +
                       $"/active - show active tasks{Environment.NewLine}" +
                       $"/day - stats for today{Environment.NewLine}" +
                       $"/week - stats for the week{Environment.NewLine}" +
                       $"/month - stats for the month{Environment.NewLine}" +
                       $"/info - show account settings {Environment.NewLine}" +
                       $"/delete - delete account {Environment.NewLine}" +
                       $"/email - set email address {Environment.NewLine}" +
                       $"/healthcheck [threshold] - detailed report with a list of tasks where the difference between active and complete is bigger than a given threshold{Environment.NewLine}" +
                       "/help";

            await _bot.SendTextMessageAsync(subscriber.TelegramId, text);
        }
 public override async Task Execute(Message message, ITelegramBotClient botClient)
 {
     var chatId = message.Chat.Id;
     await botClient.SendTextMessageAsync(chatId, chatId.ToString(), parseMode : ParseMode.Markdown);
 }
Example #8
0
 async void Salutation(long chatId, string firstName)
 {
     await botClient.SendTextMessageAsync(chatId, $"Hello, I'm Pizza Bot! How can I help you {firstName}?");
 }
Example #9
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
        }
Example #10
0
        static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            if (e.Message.Text != null)
            {
                Console.WriteLine($"Received a text message in chat {e.Message.Chat.Id}, an user name is {e.Message.Chat.Username}.");

                switch (e.Message.Text)
                {
                case string message1 when message1[0] != '/':
                {
                    await botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : "Starting search"
                        );

                    List <InlineKeyboardButton> row_1_list = new List <InlineKeyboardButton>();
                    List <InlineKeyboardButton> row_2_list = new List <InlineKeyboardButton>();

                    LOLInfo info = new LOLInfo(e.Message.Text, true);

                    string message = $"{e.Message.Text} has been found in this regions:";

                    bool flagFound    = false;
                    int  foundRegions = 0;

                    for (int i = 0; i < 10; i++)
                    {
                        if (info.summonerInfos[i].name != "Unknown")
                        {
                            InlineKeyboardButton button = new InlineKeyboardButton()
                            {
                                CallbackData = $"{(Region)i}".ToLower(), Text = $"{(Region)i}"
                            };;
                            if (foundRegions < 5)
                            {
                                row_1_list.Add(button);
                            }
                            else
                            {
                                row_2_list.Add(button);
                            }


                            message  += (Region)i + " ";
                            flagFound = true;
                            foundRegions++;
                        }
                    }

                    List <InlineKeyboardButton[]> list = new List <InlineKeyboardButton[]>();

                    if (foundRegions < 8)
                    {
                        list.Add(row_1_list.ToArray());
                    }
                    else
                    {
                        list.Add(row_1_list.ToArray());
                        list.Add(row_2_list.ToArray());
                    }


                    message += "\n Please select region";

                    if (flagFound)
                    {
                        var inline = new InlineKeyboardMarkup(list);

                        await botClient.SendTextMessageAsync(
                            chatId : e.Message.Chat,
                            text : message,
                            replyMarkup : inline
                            );
                    }
                    else
                    {
                        Console.WriteLine("\nSummoner not found\n");
                        message = " Summoner not found";

                        await botClient.SendTextMessageAsync(chatId : e.Message.Chat.Id.ToString(),
                                                             text : message);
                    }

                    break;
                }


                case string message1 when message1 == "/start":
                {
                    await botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : "Hi!\nWrite summoner's name and I will give info :-)"
                        );

                    break;
                }

                default:
                    break;
                }
            }
        }
Example #11
0
        static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            try
            {
                Message         message = new Message();
                ParseMessage    pm      = new ParseMessage();
                PasteDotaThread pdt     = new PasteDotaThread();
                pm.ParseUserMessage(message.ReplyToMessage.Text);
                switch (pm.ExistBotCommands.Find(x => x.Equals(pm.BotCommand)))
                {
                case "/paste":
                    pdt.GetPasteFromNotepad(pm);
                    await botClient.SendTextMessageAsync(chatId : e.Message.Chat,
                                                         text : pdt.MessageText, replyToMessageId : e.Message.MessageId);

                    break;

                case "/d4":
                case "/d8":
                case "/d10":
                case "/d12":
                case "/d20":
                case "/d100":
                    var        cube = DndCaluclation.GetCube(pm.BotCommand);
                    DNDResults dndr = new DNDResults();
                    dndr.SomeResult(pm, cube);
                    await botClient.SendTextMessageAsync(chatId : e.Message.Chat, text : dndr.TextMessage,
                                                         replyToMessageId : e.Message.MessageId, parseMode : ParseMode.Markdown);

                    dndr.FinalResult(pm, cube);
                    await botClient.SendTextMessageAsync(chatId : e.Message.Chat, text : dndr.TextMessage,
                                                         replyToMessageId : e.Message.MessageId, parseMode : ParseMode.Markdown);

                    break;

                case "/otec":
                    pdt.GetPasteFromOtecNotepad(pm);
                    await botClient.SendTextMessageAsync(chatId : e.Message.Chat,
                                                         text : pdt.MessageText, replyToMessageId : e.Message.MessageId);

                    break;

                case "/help":
                    await botClient.SendTextMessageAsync(chatId : e.Message.Chat,
                                                         text : "Напиши вот этому человеку @shadowmorex", replyToMessageId : e.Message.MessageId);

                    break;

                case "/fresco":
                    Quotes quotes = new Quotes(pm);
                    await using (var file = File.OpenRead(quotes.PathToFile))
                    {
                        var iof = new InputOnlineFile(file, "quotes.bpm");
                        await botClient.SendPhotoAsync(e.Message.Chat, iof, "Все факты достоверны и тщательно проверены администрацией",
                                                       replyToMessageId : e.Message.MessageId);
                    }
                    break;

                case "/test":
                    await using (var file =
                                     File.OpenRead(@"D:\projects\Valentin_Core\Valentin_Core\resources\img\fresco.jpg"))
                    {
                        var iofa = new InputOnlineFile(file, "shit.png");
                        await botClient.SendPhotoAsync(e.Message.Chat, iofa, "иди нахуй",
                                                       replyToMessageId : e.Message.MessageId);
                    }

                    break;
                }
            }
            catch (Exception er)
            {
                await botClient.SendPhotoAsync(chatId : e.Message.Chat, photo :
                                               "http://reactionimage.org/img/gallery/3926393515.jpg",
                                               replyToMessageId : e.Message.MessageId,
                                               caption : "Какая-то хуйня, больше так не делай.\n" +
                                               "Если думаешь, что проблема в боте\n" +
                                               "то вызови автора командой */help*",
                                               parseMode : ParseMode.Markdown);
            }
        }
Example #12
0
        private async static void _botClient_OnMessage(object sender, MessageEventArgs e)
        {
            if (e.Message.Text != null)
            {
                if (e.Message.Text.ToLower().Contains($"hola"))
                {
                    await _botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat.Id,
                        text : $"Hola Bienvenido a ChatBot Inteligente" + Environment.NewLine +
                        $"" + Environment.NewLine +
                        $"¿Que deseas realizar? " + Environment.NewLine +
                        $"1. Página Web" + Environment.NewLine +
                        $"2. Desarrollo de aplicaciones Web" + Environment.NewLine +
                        $"3. Desarrollo de ChatBot" + Environment.NewLine +
                        $"4. Solicitud de cotización" + Environment.NewLine +
                        $"5. Salir"
                        );
                }
                else if (!e.Message.Text.ToLower().Contains($"hola") && !e.Message.Text.ToLower().Contains("1") &&
                         !e.Message.Text.ToLower().Contains("2") && !e.Message.Text.ToLower().Contains("3") &&
                         !e.Message.Text.ToLower().Contains("4") && !e.Message.Text.ToLower().Contains("5"))
                {
                    await _botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat.Id,
                        text : $"Disculpa no reconozco la opción ingresada: {e.Message.Text}, Si me saludas con un Hola aprendere");
                }

                if (e.Message.Text.ToLower().Contains("1"))
                {
                    await _botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat.Id,
                        text : $"Desarrollo de páginas web"
                        );
                }

                if (e.Message.Text.ToLower().Contains("2"))
                {
                    await _botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat.Id,
                        text : $"Dejanos tus datos de contacto en contados minutos nos comunicaremos contigo!!!" + Environment.NewLine +
                        $" Nombre Completa:" + Environment.NewLine +
                        $" Número de Contacto:  "
                        );
                }

                if (e.Message.Text.ToLower().Contains("3"))
                {
                    await _botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat.Id,
                        text : $"Creamos diferentes flujos que responderan a tus clientes"
                        );
                }

                if (e.Message.Text.ToLower().Contains("4"))
                {
                    await _botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat.Id,
                        text : $" Números de Contacto"
                        );
                }

                if (e.Message.Text.ToLower().Contains("5"))
                {
                    await _botClient.SendStickerAsync(
                        chatId : e.Message.Chat.Id,
                        sticker : "https://tlgrm.eu/_/stickers/8a1/9aa/8a19aab4-98c0-37cb-a3d4-491cb94d7e12/2.webp"
                        );
                }
            }
        }
Example #13
0
        static async void OnMessage(object sender, MessageEventArgs e)
        {
            StreamWriter logger = new StreamWriter($"/root/memeler/logs.txt", true);

            if (e.Message.Chat.Id == 502979049 || e.Message.Chat.Id == 513085689)
            {
                if (e.Message.Type == MessageType.Text)
                {
                    if (File.Exists($"{e.Message.Chat.Id}"))
                    {
                        string caption = e.Message.Text;
                        if (e.Message.Text.ToLower() == "/no")
                        {
                            await Bot.SendTextMessageAsync(e.Message.Chat, "Saving Picture Without Caption");

                            caption = null;
                        }

                        {
                            StreamReader reader = new StreamReader($"{e.Message.Chat.Id}");
                            while (reader.EndOfStream == false)
                            {
                                string imagename = await reader.ReadLineAsync();

                                string img = await reader.ReadLineAsync();

                                await logger.WriteLineAsync("Caption: " + caption);

                                DownloadFile(img, imagename, caption);
                                await Bot.SendTextMessageAsync(e.Message.Chat, "File Downloaded");

                                reader.Close();
                                File.Delete($"{e.Message.Chat.Id}");
                                return;
                            }
                        }
                    }

                    switch (e.Message.Text.Split(' ').First())
                    {
                    case "/count":
                        var files = Directory
                                    .EnumerateFiles("/root/memeler/images", "*.*", SearchOption.AllDirectories)
                                    .Where(s => s.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) ||
                                           s.EndsWith(".png", StringComparison.OrdinalIgnoreCase));
                        int count = 0;
                        foreach (var file in files)
                        {
                            count++;
                        }
                        await Bot.SendTextMessageAsync(e.Message.Chat, $"There Are {count} Memes Available Rn");

                        break;

                    case "/start":
                    case "/help":
                        string help = $"Hello {e.Message.Chat.FirstName}, " +
                                      "You Don't Need A Help Text.";
                        await Bot.SendTextMessageAsync(e.Message.Chat, help);

                        break;

                    default:
                        await logger.WriteLineAsync("Unknown Command " + e.Message.Text + " Sent.");

                        await Bot.SendTextMessageAsync(e.Message.Chat, $"I Don't Really Understand That Holmes.");

                        break;
                    }
                }

                if (e.Message.Type == MessageType.Photo)
                {
                    await logger.WriteLineAsync("Message Received From " + e.Message.Chat.FirstName + " With Chat ID " + e.Message.Chat.Id + ":");

                    string imagename = $"{PhotoName()}.jpg";

                    await logger.WriteLineAsync("Picture File Name: " + imagename);

                    if (!string.IsNullOrEmpty(e.Message.Caption))
                    {
                        await logger.WriteLineAsync("Caption: " + e.Message.Caption);

                        DownloadFile(e.Message.Photo.LastOrDefault()?.FileId, imagename, e.Message.Caption);
                        await Bot.SendTextMessageAsync(e.Message.Chat, "File Downloaded");

                        return;
                    }

                    await Bot.SendTextMessageAsync(e.Message.Chat, "Send A Caption Or /no For Empty Caption");

                    await File.Create($"{e.Message.Chat.Id}").DisposeAsync();

                    await using StreamWriter writer = new StreamWriter($"{e.Message.Chat.Id}");
                    await writer.WriteLineAsync(imagename);

                    await writer.WriteLineAsync(e.Message.Photo.LastOrDefault()?.FileId);

                    writer.Close();
                }
            }
            else
            {
                await Bot.SendTextMessageAsync(e.Message.Chat.Id, $"Hello {e.Message.Chat.FirstName}, You " +
                                               $"Are Not Authorized To Use This Bot");
            }
            await logger.WriteLineAsync("\n");

            logger.Close();
        }
Example #14
0
        public async Task <bool> WriteAsync(string message)
        {
            var sentMessage = await _botClient.SendTextMessageAsync(_chatId, message, Telegram.Bot.Types.Enums.ParseMode.Markdown);

            return(sentMessage != null);
        }
Example #15
0
        // async OnMessage event task for the bot
        // it has to be async so the bot can be always listening
        private async static void BotClient_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            // Normal text message. Checks wether the message does have text.
            // in case it does, the bot answers.
            #region Text Message
            if (e.Message.Text != null)
            {
                Console.WriteLine($"Received text message in chat {e.Message.Chat.Id}.");

                // the bot sends asynchronously a message to the chat
                await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat.Id,
                    text : "You said:\n" + e.Message.Text
                    );
            }
            #endregion

            // Normal text message, with all the properties
            // a text message can have.
            #region Text message with properties
            Message textMessage = await botClient.SendTextMessageAsync(
                chatId : e.Message.Chat, // or a chat id: 123456789
                text : "Trying *all the parameters* of `sendMessage` method",
                parseMode : ParseMode.Markdown,
                disableNotification : true,
                replyToMessageId : e.Message.MessageId,
                replyMarkup : new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl(
                                                           "Check sendMessage method",
                                                           "https://core.telegram.org/bots/api#sendmessage"
                                                           ))
                );

            #endregion

            // Almost all of the methods for sending messages return you
            // the message you just sent.
            #region Messages return you the message you sent (as an object)
            Console.WriteLine(
                $"{textMessage.From.FirstName} sent message {textMessage.MessageId} " +
                $"to chat {textMessage.Chat.Id} at {textMessage.Date.ToLocalTime()}. " + // if you don't use ToLocalTime(), the bot will show the UTC time.
                $"It is a reply to message {textMessage.ReplyToMessage.MessageId} " +
                $"and has {textMessage.Entities.Length} message entities."
                );
            #endregion

            // Photo message. It gets the image from a URL on the internet.
            // All images can have captions. You can use HTML or Markdown on them.
            #region Photo Message
            Message photoMessage = await botClient.SendPhotoAsync(
                chatId : e.Message.Chat,
                photo : "https://github.com/TelegramBots/book/raw/master/src/docs/photo-ara.jpg",
                caption : "<b>Ara bird</b>. <i>Source</i>: <a href=\"https://pixabay.com\">Pixabay</a>",
                parseMode : ParseMode.Html
                );

            #endregion

            // Sticker message. Sticker files should be in WebP format.
            // Sends two messages. The first one gets the sticker by passing HTTP URL
            // to WebP sticker file, and the second by reusing the file_id of the
            // first sticker (kinda like a cache?)
            #region Sticker Messages
            Message stickerMessage1 = await botClient.SendStickerAsync(
                chatId : e.Message.Chat,
                sticker : "https://github.com/TelegramBots/book/raw/master/src/docs/sticker-fred.webp"
                );

            Message stickerMessage2 = await botClient.SendStickerAsync(
                chatId : e.Message.Chat,
                sticker : stickerMessage1.Sticker.FileId
                );

            #endregion

            // Audio message. Opens it in Media Player. MP3 Format.
            // Telegram can read metadata from the MP3 file (that's why
            // there are commented properties; the bot gets the same
            // properties, but from the file metadata!)
            #region Audio Message
            Message audioMessage = await botClient.SendAudioAsync(
                e.Message.Chat,
                "https://github.com/TelegramBots/book/raw/master/src/docs/audio-guitar.mp3"

                /*,
                 * performer: "Joel Thomas Hunger",
                 * title: "Fun Guitar and Ukulele",
                 * duration: 91 // in seconds
                 */
                );

            #endregion

            // Voice message. Not opened in Media Player (played directly
            // on the chat). OGG Format.
            // In this case, the OGG file is on our disk!
            #region Voice Message
            Message voiceMessage;
            using (var stream = System.IO.File.OpenRead("C:/Users/Biel/source/repos/TelegramBot/voice-nfl_commentary.ogg"))
            {
                voiceMessage = await botClient.SendVoiceAsync(
                    chatId : e.Message.Chat,
                    voice : stream,
                    duration : 36
                    );
            }
            #endregion


            // You can send MP4 files as a regular video or as a video note.
            // Other video formats must be sent as a file.

            // Video message. They can have caption, reply, and reply markup
            // (like other multimedia messages)
            // You can optionally specify the duration and the resolution
            // of the video. In this case the video is streamed,
            // meaning the user can partly watch the video on stream, without
            // having to download it completely.
            #region Video Message
            Message videoMessage = await botClient.SendVideoAsync(
                chatId : e.Message.Chat,
                video : "https://raw.githubusercontent.com/TelegramBots/book/master/src/docs/video-countdown.mp4",
                thumb : "https://raw.githubusercontent.com/TelegramBots/book/master/src/2/docs/thumb-clock.jpg",
                supportsStreaming : true
                );

            #endregion

            // Video note message. They are shown in circles to the user.
            // They are usually short (1 minute or less).
            // You can send a video note only by the video file or
            // reusing the file_id of another video note.
            // (sending it by its HTTP URL is not supported currently)
            #region Video Note Message
            Message videoNoteMessage;
            using (var stream = System.IO.File.OpenRead("C:/Users/step/Source/Repos/TelegramBotExamples/video-waves.mp4"))
            {
                videoNoteMessage = await botClient.SendVideoNoteAsync(
                    chatId : e.Message.Chat,
                    videoNote : stream,
                    duration : 47,
                    length : 360    // value of width/height
                    );
            }
            #endregion

            // Poll message. They can be sent only to groups and channels.
            // You can optionally send a keyboard with a poll,
            // both inline and a regular one.
            #region Poll Message
            Message pollMessage = await botClient.SendPollAsync(
                chatId : "@group_or_channel_username",
                question : "Did you ever hear the tragedy of Darth Plagueis The Wise?",
                options : new []
            {
                "Yes for the hundredth time!",
                "No, who's that?"
            }
                );

            #endregion

            // To stop the poll, you need to know original chat and message ids
            // (you get them from the Poll object you get on SendPollAsync, the pollMessage)
            #region Closing a Poll
            Poll poll = await botClient.StopPollAsync(
                chatId : pollMessage.Chat.Id,
                messageId : pollMessage.MessageId
                );

            #endregion


            // Filtering messages for commands
            if (e.Message.Text == "/sayhello")
            {
                Message sayHello = await botClient.SendTextMessageAsync
                                   (
                    chatId : e.Message.Chat.Id,
                    text : "Hello! Glad to see you!"
                                   );
            }

            if (e.Message.Text == "/saygoodbye")
            {
                Message sayHello = await botClient.SendTextMessageAsync
                                   (
                    chatId : e.Message.Chat.Id,
                    text : "Bye! Have a nice day!"
                                   );
            }
        }
        //----------------------------------------------------------------//

        public async Task <OkResult> CreateDaily([FromQuery] Int32 chatId)
        {
            await _botClient.SendTextMessageAsync(chatId, CaseMessages.SELECT_TIME);

            return(Ok());
        }
        public async Task ExecuteAsync(Message message)
        {
            try
            {
                var    splitStr = message.Text.Split(' ');
                var    currency = splitStr[1].ToUpper();
                var    value    = splitStr[2].Replace(',', '.');
                string sign     = "";
                double valueParsed;
                if (value.Contains("+") || value.Contains("-"))
                {
                    valueParsed = double.Parse(value.Substring(1, value.Length - 2), CultureInfo.InvariantCulture);
                    sign       += value[0];
                }
                else if (value.Contains("%"))
                {
                    valueParsed = double.Parse(value.Substring(0, value.Length - 1), CultureInfo.InvariantCulture);
                }
                else
                {
                    valueParsed = double.Parse(value.Substring(0, value.Length), CultureInfo.InvariantCulture);
                }

                var alert = _alertRepository.GetItem(z => z.UserId == message.Chat.Id && currency == z.NameCurrency);

                if (value.Contains("%"))
                {
                    var lastCoinMarcet = CurrencyInfoStore.GetLastCoinMarket()
                                         .FirstOrDefault(z => z.FirstCurrency == currency);
                    if (lastCoinMarcet == null)
                    {
                        await _client.SendTextMessageAsync(message.Chat.Id, "Currency not found");

                        return;
                    }
                    if (alert == null)
                    {
                        _alertRepository.Create(new Alert
                        {
                            NameCurrency  = currency,
                            PercentNotify = sign + valueParsed.ToString(CultureInfo.InvariantCulture),
                            UserId        = message.Chat.Id,
                            Cost          = lastCoinMarcet.Last
                        });
                    }
                    else
                    {
                        alert.PercentNotify = sign + valueParsed.ToString(CultureInfo.InvariantCulture);
                        alert.Cost          = lastCoinMarcet.Last;
                        _alertRepository.Update(alert, z => z.UserId == message.Chat.Id && currency == z.NameCurrency);
                    }
                }
                else
                {
                    if (alert == null)
                    {
                        _alertRepository.Create(new Alert
                        {
                            NameCurrency = currency,
                            NotifyCost   = valueParsed,
                            UserId       = message.Chat.Id
                        });
                    }
                    else
                    {
                        alert.NotifyCost = valueParsed;
                        _alertRepository.Update(alert, z => z.UserId == message.Chat.Id && currency == z.NameCurrency);
                    }
                }
                await _client.SendTextMessageAsync(message.Chat.Id, "Success");
            }
            catch (Exception e)
            {
                await NotSuccess(message);

                _logger.LogError("Exeption in SetAlertCommand", e.Message);
            }
        }
Example #18
0
 public async Task Initialize(ITelegramBotClient client, Update update)
 {
     await client.SendTextMessageAsync(update.GetChatId(),
                                       "Enter your current local time to detect your timezone. Use 24-hour HHmm format.",
                                       replyMarkup : TelegramHelper.GetHomeButtonKeyboard());
 }
        protected async Task StartActionWithConfirm(Message message, string actionName, Func <IDigitalOceanClient, int, Task <DigitalOcean.API.Models.Responses.Action> > func)
        {
            try
            {
                if (message.Text == "Yes")
                {
                    var digitalOceanApi = _digitalOceanClientFactory.GetInstance(message.From.Id);
                    var session         = _sessionRepo.Get(message.From.Id);
                    var dropletId       = session.Data.CastObject <int>();
                    var action          = await func(digitalOceanApi, dropletId).ConfigureAwait(false);

                    await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, $"\U0001F4C0 {actionName}...");

                    _sessionRepo.Update(message.From.Id, session =>
                    {
                        session.State = SessionState.WaitAction;
                    });

                    var cancellationTokenSource = new CancellationTokenSource();
                    cancellationTokenSource.CancelAfter(TimeSpan.FromMinutes(10));
                    var resultStatus = await CheckActionStatus(dropletId, action.Id, digitalOceanApi, cancellationTokenSource.Token);

                    if (resultStatus)
                    {
                        await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, "Done \U00002705", replyMarkup : Keyboards.GetSelectedDropletsMenuKeyboard());
                    }
                    else
                    {
                        await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, "Error \U0000274C", replyMarkup : Keyboards.GetSelectedDropletsMenuKeyboard());
                    }

                    _sessionRepo.Update(message.From.Id, session =>
                    {
                        session.State = SessionState.SelectedDroplet;
                    });
                }
                else if (message.Text == "No")
                {
                    _sessionRepo.Update(message.From.Id, session =>
                    {
                        session.State = SessionState.SelectedDroplet;
                    });

                    await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, "Canceled \U0001F630", replyMarkup : Keyboards.GetSelectedDropletsMenuKeyboard());
                }
            }
            catch (ApiException ex)
            {
                _logger.LogError($"UserId={message.From.Id.ToString()}, Error={ex.Message}");
                await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, $"DigitalOcean API Error: {ex.Message}");
            }
            catch (OperationCanceledException)
            {
                _logger.LogError($"UserId={message.From.Id.ToString()}, ChatId={message.Chat.Id.ToString()}, Error=Operation CheckActionStatus was auto-canceled after 3 minutes");
                await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, "Sorry, check action status operation was auto-canceled after 10 minutes \U0001F628", replyMarkup : Keyboards.GetSelectedDropletsMenuKeyboard());
            }
            catch (Exception ex)
            {
                _logger.LogError($"UserId={message.From.Id.ToString()}, ChatId={message.Chat.Id.ToString()}, Error={ex.Message}, StackTrace={ex.StackTrace}");
                await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, "Sorry, аn error has occurred \U0001F628", replyMarkup : Keyboards.GetSelectedDropletsMenuKeyboard());
            }
        }
Example #20
0
        public async Task <int> SendTextMessage(long chatId, string text, ParseMode parseMode = _defaultParseMode, bool disableWebPagePreview = _disableWebPagePreview, int replyToMessageId = 0, IReplyMarkup replyMarkup = null)
        {
            var message = await _telegramBotClient.SendTextMessageAsync(chatId, text, parseMode, disableWebPagePreview, replyToMessageId : replyToMessageId, replyMarkup : replyMarkup);

            return(message.MessageId);
        }
Example #21
0
        private async void BotOnCallbackQueryReceived(object sender, CallbackQueryEventArgs e)
        {
            int askNumb = -1;

            if (st == States.Stop)
            {
                return;
            }

            CallbackQuery callbackQuery = e.CallbackQuery;

            string[] dataParts = callbackQuery.Data.Split(':');
            if (dataParts.Length == 2 && dataParts[1] == guid.ToString())
            {
                guid = Guid.NewGuid();
                if (dataParts[0].StartsWith(NumberCmd))
                {
                    askNumb      = int.Parse(dataParts[0].Substring(NumberCmd.Length));
                    dataParts[0] = NumberCmd;
                }
                switch (dataParts[0])
                {
                case AddCmd:
                    break;

                case EditCmd:
                    await botClient.SendTextMessageAsync(chat.Id, "Выберите вопрос", replyMarkup : question.CreateGetInlineKeyboard(guid));

                    break;

                case DeleteCmd:
                    break;

                case ListCmd:
                    await botClient.SendTextMessageAsync(chat.Id, "Выберите вопрос", replyMarkup : question.CreateListInlineKeyboard(guid));

                    break;

                case EnterNumbCmd:
                    await botClient.SendTextMessageAsync(chat.Id, "Введите номер вопроса");

                    break;

                case NumberCmd:
                    await botClient.SendTextMessageAsync(chat.Id, botLinq.GetAskByOrd(askNumb).AskTxt);

                    break;

                case BackCmd:
                    await botClient.SendTextMessageAsync(chat.Id, "Вы отказались от этого меню", replyMarkup : question.CreateEditInlineKeyboard(guid));

                    break;

                case ExitCmd:
                    st = States.Stop;
                    await botClient.SendTextMessageAsync(chat.Id, "Сеанс завершен");

                    break;

                default:
                    await botClient.SendTextMessageAsync(chat.Id, "Извините, ошибка в боте");

                    break;
                }
            }
        }
Example #22
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);
        }
Example #23
0
        private async Task ProcessItem(WorkItem workItem)
        {
            var files = new List <Stream>();

            try
            {
                foreach (var fileInfo in workItem.Files)
                {
                    var stream = new MemoryStream();

                    try
                    {
                        var file = await _telegramBotClient.GetFileAsync(fileInfo, stream);

                        _logger.LogInformation("Downloaded file with name {0} and id {1} - Size: {2} KB", file.FilePath,
                                               file.FileId, file.FileSize / 1024);

                        if (workItem.DocumentAction == DocumentAction.DocumentScan)
                        {
                            var result = _imageDocumentDetectionService.ProcessStream(stream);
                            stream.Dispose();

                            if (result == null)
                            {
                                await _telegramBotClient.SendTextMessageAsync(workItem.ChatId,
                                                                              "Oh snap, I'm not able to handle this picture :(");

                                return;
                            }

                            files.Add(result);
                        }
                        else
                        {
                            files.Add(stream);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogCritical(ex, "Unable to process a file :(");
                        stream.Dispose();

                        await _telegramBotClient.SendTextMessageAsync(workItem.ChatId,
                                                                      "Oh snap, I'm not able to complete your action :(");

                        return;
                    }
                }

                switch (workItem.ConversationType)
                {
                case ConversationType.Image:
                    foreach (var processedFile in files)
                    {
                        await _telegramBotClient.SendPhotoAsync(workItem.ChatId,
                                                                new FileToSend(Guid.NewGuid() + ".jpg", processedFile));
                    }
                    break;

                case ConversationType.Pdf:
                    using (var collection = new MagickImageCollection())
                    {
                        foreach (var processedFile in files)
                        {
                            collection.Add(new MagickImage(processedFile));
                        }

                        using (var pdfStream = new MemoryStream())
                        {
                            collection.Write(pdfStream, MagickFormat.Pdf);
                            pdfStream.Position = 0;

                            await _telegramBotClient.SendDocumentAsync(workItem.ChatId, new FileToSend(Guid.NewGuid() + ".pdf", pdfStream));
                        }
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, "Unable to process a file :(");

                await _telegramBotClient.SendTextMessageAsync(workItem.ChatId,
                                                              "Oh snap, I'm not able to complete your action :(");

                return;
            }
            finally
            {
            }
        }
Example #24
0
 private async Task SendMessageAsync(string message, ParseMode mode = ParseMode.Default)
 {
     await _botClient.SendTextMessageAsync(_settings.MetaCountingChatId, message, mode);
 }
Example #25
0
        static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            switch (e.Message.Text)
            {
            case  "Протченко":
            {
                Console.WriteLine($"Received a text message in chat {e.Message.Chat.Id} :: {e.Message.Text}.");
                Random r = new Random();
                await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text :  Protchenko[r.Next(0, Protchenko.Count)]
                    );

                break;
            }

            case "Батин":
            {
                Console.WriteLine($"Received a text message in chat {e.Message.Chat.Id} :: {e.Message.Text}.");
                Random r = new Random();
                await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text :  Butin[r.Next(0, Butin.Count)]
                    );

                break;
            }

            case "Стригалёв":
            {
                Console.WriteLine($"Received a text message in chat {e.Message.Chat.Id} :: {e.Message.Text}.");
                Random r = new Random();
                await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text :  Strigalev[r.Next(0, Strigalev.Count)]
                    );

                break;
            }

            case "/help":
            {
                Console.WriteLine($"Received a text message in chat {e.Message.Chat.Id} :: {e.Message.Text}.");
                await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text :   "Протченко, Батин, Стригалёв; БОНУС: мемас"
                    );

                break;
            }

            case "/start":
            {
                Console.WriteLine($"Received a text message in chat {e.Message.Chat.Id} :: {e.Message.Text}.");
                await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text :   "Привет, я храню цитаты преподов с АСОИ, введи /help, чтобы узнать, доступных преподов. "
                    );

                break;
            }

            case "мемас":
            {
                Console.WriteLine($"Received a text message in chat {e.Message.Chat.Id} :: {e.Message.Text}.");
                Random r = new Random();
                await botClient.SendPhotoAsync(
                    chatId : e.Message.Chat,
                    photo : Memas[r.Next(0, Memas.Count)]
                    );

                break;
            }

            default:
            {
                Console.WriteLine($"Received a text message in chat {e.Message.Chat.Id} :: {e.Message.Text}.");
                await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text :   "Это вряд ли фамилия препода"
                    );

                break;
            }
            }
        }
Example #26
0
 public async Task ExecuteAsync(ITelegramBotClient botClient, Message message)
 {
     await botClient.SendTextMessageAsync(message.Chat.Id, @"( ͡° ͜ʖ ͡°)");
 }
Example #27
0
        private async static void BotClient_OnCallbackQuery(object sender, Telegram.Bot.Args.CallbackQueryEventArgs e)
        {
            var    buttonText = e.CallbackQuery.Data;
            string name       = $"{e.CallbackQuery.From.FirstName}";

            Console.WriteLine($"{name} нажал на кнопку {buttonText} ПО времени {DateTime.Now}");
            MainWork mongoDB = new MainWork();

            switch (buttonText)
            {
            case "NORD":
                var words1 = mongoDB.GetInformCS("NORD").Result;
                if (words1.Count > 0)
                {
                    foreach (string word in words1)
                    {
                        await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, word);
                    }
                    await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, "Для покупки введите /buy и ID через ',' без пробелов");
                }
                else
                {
                    await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, "Аккаунтов в данной категории нет!");
                }
                break;

            case "IPVANISH":
                var words = mongoDB.GetInformCS("IPVANISH").Result;
                if (words.Count > 0)
                {
                    foreach (string word in words)
                    {
                        await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, word);
                    }
                    await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, "Для покупки введите /buy и ID через ',' без пробелов");
                }
                else
                {
                    await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, "Аккаунтов в данной категории нет!");
                }
                break;

            case "ZETMATE":
                var words2 = mongoDB.GetInformCS("ZETMATE").Result;
                if (words2.Count > 0)
                {
                    foreach (string word in words2)
                    {
                        await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, word);
                    }
                    await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, "Для покупки введите /buy и ID через ',' без пробелов");
                }
                else
                {
                    await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, "Аккаунтов в данной категории нет!");
                }
                break;

            case "HMAPRO":
                var words3 = mongoDB.GetInformCS("HMAPRO").Result;
                if (words3.Count > 0)
                {
                    foreach (string word in words3)
                    {
                        await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, word);
                    }
                    await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, "Для покупки введите /buy и ID через ',' без пробелов");
                }
                else
                {
                    await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, "Аккаунтов в данной категории нет!");
                }
                break;

            case "WINDSCRIBE":
                var words4 = mongoDB.GetInformCS("WINDSCRIBE").Result;
                if (words4.Count > 0)
                {
                    foreach (string word in words4)
                    {
                        await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, word);
                    }
                    await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, "Для покупки введите /buy и ID через ',' без пробелов");
                }
                else
                {
                    await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, "Аккаунтов в данной категории нет!");
                }
                break;

            case "TUNNELBEAR":
                var words5 = mongoDB.GetInformCS("TUNNELBEAR").Result;
                if (words5.Count > 0)
                {
                    foreach (string word in words5)
                    {
                        await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, word);
                    }
                    await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, "Для покупки введите /buy и ID через ',' без пробелов");
                }
                else
                {
                    await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, "Аккаунтов в данной категории нет!");
                }
                break;

            case "VYPRVPN":
                var words6 = mongoDB.GetInformCS("VYPRVPN").Result;
                if (words6.Count > 0)
                {
                    foreach (string word in words6)
                    {
                        await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, word);
                    }
                    await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, "Для покупки введите /buy и ID через ',' без пробелов");
                }
                else
                {
                    await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, "Аккаунтов в данной категории нет!");
                }
                break;
            }
            try
            {
                await botClient.AnswerCallbackQueryAsync(e.CallbackQuery.Id, $"Вы нажали кнопку {buttonText}");
            }
            catch
            {
                Console.WriteLine("Был возможный краш!");
            }
        }
Example #28
0
        public override async Task Execute(Message message, ITelegramBotClient client)
        {
            ReplyKeyboardMarkup replyKeyboardMarkup = await GetMenu(message.Text);

            await client.SendTextMessageAsync(message.Chat.Id, MessageConstant.CHOOSE_TEAM, ParseMode.Html, false, false, 0, replyKeyboardMarkup);
        }
Example #29
0
 /// <inheritdoc/>
 public async Task Execute(Message message, ITelegramBotClient client) =>
 await client.SendTextMessageAsync(
     message.Chat.Id,
     $"\U0001F389 {About.Message} \U0001F449 {About.ShortLink} \U0001F448");
Example #30
0
 public override void Execute(ITelegramBotClient client, Message message)
 {
     client.SendTextMessageAsync(message.Chat, "Що вам конректно портібно?");
 }