Example #1
0
 private static async void SendIfSticker(MessageEventArgs e)
 {
     await botClient.SendStickerAsync(
         chatId : e.Message.Chat,
         sticker : e.Message.Sticker.FileId
         );
 }
Example #2
0
 public async Task <Session> ExecuteCommand(MessageEventArgs e, Session session)
 {
     try
     {
         await _botClient.SendStickerAsync(
             chatId : e.Message.Chat,
             sticker : "https://github.com/TelegramBots/book/raw/master/src/docs/sticker-fred.webp"
             );
     }
     catch (Exception exception)
     {
         throw  new Exception("Exception occured in StickerCommand: " + exception.Message);
     }
     return(null);
 }
Example #3
0
 private static async void ForwardMessage(Message message, UserModel recipient, ITelegramBotClient botClient)
 {
     _ = message.Type switch
     {
         MessageType.Unknown => await botClient.SendTextMessageAsync(recipient.TelegramId, "Bad message!"),
         MessageType.Text => await botClient.SendTextMessageAsync(recipient.TelegramId, message.Text),
         MessageType.Photo => await botClient.SendPhotoAsync(recipient.TelegramId, new InputOnlineFile(message.Photo[0].FileId)),
         MessageType.Audio => await botClient.SendAudioAsync(recipient.TelegramId, new InputOnlineFile(message.Audio.FileId)),
         MessageType.Video => await botClient.SendVideoAsync(recipient.TelegramId, new InputOnlineFile(message.Video.FileId)),
         MessageType.Voice => await botClient.SendVoiceAsync(recipient.TelegramId, new InputOnlineFile(message.Voice.FileId)),
         MessageType.Document => await botClient.SendDocumentAsync(recipient.TelegramId, new InputOnlineFile(message.Document.FileId)),
         MessageType.Sticker => await botClient.SendStickerAsync(recipient.TelegramId, new InputOnlineFile(message.Sticker.FileId)),
         MessageType.Contact => await botClient.SendContactAsync(recipient.TelegramId, message.Contact.PhoneNumber, message.Contact.FirstName, message.Contact.LastName),
         MessageType.VideoNote => await botClient.SendVideoNoteAsync(recipient.TelegramId, message.VideoNote.FileId),
     };
 }
Example #4
0
        static async void BotClient_OnMessage(object sender, MessageEventArgs e)
        {
            if (e.Message.Text != null)
            {
                string       answer      = null;
                IReplyMarkup replyMarkup = null;
                switch (e.Message.Text.ToLower())
                {
                case "/start":
                    replyMarkup = GetKeyboard();
                    break;

                case "варианты":
                    answer = GetGroupList();
                    break;

                case "расписание":
                    answer = GetSchedule(IsWeekEven());
                    break;

                case "на след. неделю":
                    answer = GetSchedule(!IsWeekEven());
                    break;

                default:
                    return;
                }

                if (answer != null)
                {
                    await botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : answer,
                        parseMode : Telegram.Bot.Types.Enums.ParseMode.Html
                        );
                }
                else
                {
                    var startSticker = new InputOnlineFile(startStickerId);
                    await botClient.SendStickerAsync(
                        chatId : e.Message.Chat,
                        sticker : startSticker,
                        replyMarkup : replyMarkup
                        );
                }
            }
        }
Example #5
0
        private async static void _botclient_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            if (e.Message.Text.ToLower().Contains("message"))
            {
                Console.WriteLine("opcion message");
                await _botclient.SendTextMessageAsync
                (
                    chatId : e.Message.Chat.Id,
                    text : $"jevi, le llegamos a tu cotorra: {e.Message.Text}"
                );
            }
            else if (e.Message.Text.ToLower().Contains("sticker"))
            {
                Console.WriteLine("opcion sticker");
                await _botclient.SendStickerAsync(
                    chatId : e.Message.Chat.Id,
                    sticker : "https://github.com/TelegramBots/book/raw/master/src/docs/sticker-dali.webp"
                    );
            }

            else if (e.Message.Text.ToLower().Contains("contact"))
            {
                Console.WriteLine("opcion contacto");
                await _botclient.SendContactAsync(
                    chatId : e.Message.Chat.Id,
                    phoneNumber : "123456789",
                    firstName : "Test",
                    lastName : "bot"

                    );
            }

            else if (e.Message.Text.ToLower().Contains("/repeat"))
            {
                await _botclient.SendTextMessageAsync
                (
                    chatId : e.Message.Chat.Id,
                    text : $"jevi, le llegamos a tu cotorra: {e.Message.Text}"
                );
            }
        }
Example #6
0
        private static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            var text = e?.Message?.Text;

            if (text == null)
            {
                return;
            }

            Console.WriteLine($"Recived text message '{text}' in chat '{e.Message.Chat.Id}'");

            await botClient.SendTextMessageAsync(
                chatId : e.Message.Chat,
                text : $"You said '{text}'"
                ).ConfigureAwait(false);

            await botClient.SendStickerAsync(
                chatId : e.Message.Chat,
                sticker : "https://github.com/TelegramBots/book/raw/master/src/docs/sticker-dali.webp"
                );
        }
Example #7
0
 /// <summary>
 /// 接收訊息事件
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private static void Bot_OnMessage(object sender, MessageEventArgs e)
 {
     if (e.Message.Text != null)
     {
         if (e.Message.Text.Equals("sticker"))
         {
             Console.WriteLine($"接收到貼圖,ID:{e.Message.Chat.Id}.");
             botClient.SendStickerAsync(chatId: e.Message.Chat, sticker: "https://github.com/TelegramBots/book/raw/master/src/docs/sticker-dali.webp");
         }
         else if (e.Message.Text.Equals("video"))
         {
             Console.WriteLine($"接收到影片,ID:{e.Message.Chat.Id}.");
             botClient.SendVideoAsync(chatId: e.Message.Chat, video: "https://github.com/TelegramBots/book/raw/master/src/docs/video-bulb.mp4");
         }
         else
         {
             Console.WriteLine($"接收到訊息,ID:{e.Message.Chat.Id}.");
             botClient.SendTextMessageAsync(chatId: e.Message.Chat, text: "你傳的消息:\n" + e.Message.Text);
             botClient.SendTextMessageAsync(chatId: _telegramChannelName, text: $"公告消息:{e.Message.Text}");
         }
     }
 }
Example #8
0
        private async static void _botClient_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            if (e.Message.Text != null)
            {
                System.Console.WriteLine($"Message Received");

                if (e.Message.Text.ToLower().Contains("hola"))
                {
                    await _botClient.SendTextMessageAsync(chatId : e.Message.Chat.Id, text : $"Coño tu otra vez?");

                    System.Console.WriteLine($"Message send");
                }
                else if (e.Message.Text.ToLower().Contains("contacto"))
                {
                    await _botClient.SendContactAsync(chatId : e.Message.Chat.Id, phoneNumber : "(+58) 424778906", firstName : "John", lastName : "Wick");
                }
            }
            else if (e.Message.Sticker != null)
            {
                System.Console.WriteLine($"StickerS Received");
                await _botClient.SendStickerAsync(chatId : e.Message.Chat.Id, sticker : "https://tlgrm.eu/_/stickers/ee1/7e3/ee17e34b-083f-3cae-b8de-24e96558758b/thumb-animated-128.mp4");
            }
        }
        public async Task Handle(BotListDescriptionsCommand notification, CancellationToken ct)
        {
            var message = notification.Message;

            if (message.ReplyToMessage?.Sticker is null)
            {
                throw new ValidationException("Must be a reply to a sticker");
            }

            var sticker = message.ReplyToMessage.Sticker;
            var fromId  = message.From.Id.ToString();

            await mediator.Send(new EnsureStickerIsRegisteredCommand(sticker.FileUniqueId, sticker.FileId), ct);

            await mediator.Send(new EnsureUserIsRegisteredCommand(fromId), ct);

            var descriptions = await mediator.Send(new GetStickerDescriptionsQuery(sticker.FileUniqueId), ct).ToList();

            if (descriptions.IsEmpty())
            {
                await botClient.SendTextMessageAsync(
                    chatId : message.Chat,
                    text : "<i>This sticker has no descriptions</i>",
                    parseMode : ParseMode.Html,
                    replyToMessageId : message.MessageId,
                    cancellationToken : ct);
            }
            else
            {
                await botClient.SendStickerAsync(
                    chatId : message.Chat,
                    sticker : message.ReplyToMessage.Sticker.FileId,
                    replyToMessageId : message.MessageId,
                    replyMarkup : StickerDescriptionButtonsBuilder.BuildDescriptionMarkup(descriptions),
                    cancellationToken : ct);
            }
        }
Example #10
0
        private void SendStickerPost(IPostModel post)
        {
            if (post.Attachments == null)
            {
                throw new ArgumentException("Images Post: post.attachments = null");
            }

            if (post.Attachments.Length == 0)
            {
                throw new ArgumentException("Images Post: post.attachments.length = 0");
            }

            if (post.Attachments[0] == null)
            {
                throw new ArgumentException("Images Post: post.attachments[0] = null");
            }

            var temp = bot.SendStickerAsync(
                ChannelID,
                new InputMedia(post.Attachments[0]));

            temp.Wait();
            Console.WriteLine(temp.Result.Text);
        }
Example #11
0
        public async Task EchoAsync(Update update)
        {
            var inputMsg = update.Message;
            var message  = string.Empty;

            if (update.Type == UpdateType.Message)
            {
                var lineId      = Regex.Match(inputMsg.Text, @"\d+").Value;
                var downloadUrl = string.Format(_config.LineStickerConfig.NormalStickerUrl, lineId);
                List <Telegram.Bot.Types.File> files = new List <Telegram.Bot.Types.File> ();
                using (var hc = new HttpClient()) {
                    Stream imgsZip = null;
                    try {
                        imgsZip = await hc.GetStreamAsync(downloadUrl);
                    } catch (Exception ex) {
                        _logger.Log(LogLevel.Error, $"{ex}");
                        return;
                    }
                    using (ZipArchive zipFile = new ZipArchive(imgsZip)) {
                        foreach (var entry in zipFile.Entries)
                        {
                            if (Regex.Match(entry.Name, @"^\[email protected]").Success)
                            {
                                using (Image image = Image.Load(entry.Open()))
                                    using (MemoryStream ms = new MemoryStream()) {
                                        image.Mutate(m => m.Resize(512, 512));
                                        image.SaveAsPng(ms);
                                        ms.Seek(0, SeekOrigin.Begin);
                                        try {
                                            var file = await _botService.UploadStickerFileAsync(
                                                userId : (int)inputMsg.Chat.Id,
                                                pngSticker : new Telegram.Bot.Types.InputFiles.InputFileStream(ms)
                                                );

                                            files.Add(file);
                                        } catch (Exception ex) {
                                            _logger.Log(LogLevel.Error, $"{ex}");
                                            return;
                                        }
                                    }
                            }
                        }
                        ;
                    }
                }

                string tempName = $"bot{Guid.NewGuid ().ToString ("N")}_by_{_config.BotConfig.BotName}";

                int firstEmojiUnicode = 0x1F601;
                var emojiString       = char.ConvertFromUtf32(firstEmojiUnicode);
                var stickerTitle      = "TransferBy@MartinBot";

                await _botService.CreateNewStickerSetAsync(
                    userId : (int)inputMsg.Chat.Id,
                    name : tempName,
                    title : stickerTitle,
                    pngSticker : files[0].FileId,
                    emojis : emojiString
                    );

                for (int i = 0; i < files.Count; i++)
                {
                    emojiString = char.ConvertFromUtf32(firstEmojiUnicode + i);
                    await _botService.AddStickerToSetAsync(
                        userId : (int)inputMsg.Chat.Id,
                        name : tempName,
                        pngSticker : files[i].FileId,
                        emojis : emojiString
                        );
                }

                var stickerSet = await _botService.GetStickerSetAsync(
                    name : tempName
                    );

                var sticker = stickerSet.Stickers[0];

                await _botService.SendStickerAsync(
                    chatId : new ChatId(inputMsg.Chat.Id),
                    sticker : new Telegram.Bot.Types.InputFiles.InputOnlineFile(sticker.FileId)
                    );
            }
            else
            {
                await _botService.SendTextMessageAsync(
                    chatId : inputMsg.Chat.Id,
                    text : $" Please, Send me a line sticker link "
                    );
            }
        }
Example #12
0
        private async void BotClient_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            if (e.Message.Text != null)
            {
                switch (e.Message.Text.ToLower())
                {
                case "hello":
                {
                    var keyboard = new InlineKeyboardMarkup(
                        new InlineKeyboardButton
                        {
                            Text         = "Quiz",
                            CallbackData = "quiz"
                        });

                    await botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : "Hello",
                        replyMarkup : keyboard);

                    break;
                }

                case "📊 start quiz":
                {
                    List <string> answers = new List <string>();
                    answers.Add("Nice");
                    answers.Add("Bad");
                    var id = await botClient.SendPollAsync(chatId : e.Message.Chat, question : "How are you ?", answers, isAnonymous : false);

                    Polls.Add(new Poll
                        {
                            ChatId = e.Message.Chat,
                            PollId = id.Poll.Id
                        });
                    break;
                }

                case "/start":
                {
                    var keyboard = new ReplyKeyboardMarkup
                    {
                        Keyboard = new KeyboardButton[][]
                        {
                            new KeyboardButton[]
                            {
                                new KeyboardButton("📊 Start quiz"),
                                new KeyboardButton("📊 Start quiz"),
                                new KeyboardButton("📊 Start quiz")
                            },
                            new KeyboardButton[]
                            {
                                new KeyboardButton("📊 Start quiz"),
                                new KeyboardButton("📊 Start quiz")
                            }
                        }
                    };
                    await botClient.SendStickerAsync(
                        chatId : e.Message.Chat,
                        sticker : "https://fs13.fex.net:443/download/2521380597",
                        replyMarkup : keyboard
                        );

                    break;
                }
                }
            }
        }
Example #13
0
        static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            if (e.Message.Text == "/hello")
            {
                Message textMessage = await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : "Hello, world!",
                    parseMode : ParseMode.Default,
                    disableNotification : false);
            }
            if (e.Message.Text == "/sendpic")
            {
                Message photoMessage = await botClient.SendPhotoAsync(
                    chatId : e.Message.Chat,
                    photo : "https://cdn5.zp.ru/job/attaches/2019/08/35/b8/35b8649f6773c52f3535793d96d84317.jpg",
                    caption : "<b>Логотип ИнПАД</b>. <i>Источник</i>: <a href=\"https://www.inpad.ru\">ИнПАД</a>",
                    parseMode : ParseMode.Html);
            }
            if (e.Message.Text == "/sendpoll")
            {
                Message pollMessage = await botClient.SendPollAsync(
                    chatId : e.Message.Chat,
                    isAnonymous : false,
                    question : "Ты работаешь в ИнПАДе?",
                    options : new[]
                {
                    "Да",
                    "Нет, в другом месте"
                });
            }
            if (e.Message.Text == "/sendfile")
            {
                Message fileMessage = await botClient.SendDocumentAsync(
                    chatId : e.Message.Chat,
                    document : "https://media.tenor.com/images/e9cc959f643d3aac2322295eb95d19ce/tenor.gif"
                    );
            }
            if (e.Message.Text == "/sendsticker")
            {
                Message stickerMessage = await botClient.SendStickerAsync(
                    chatId : e.Message.Chat,
                    sticker : "https://raw.githubusercontent.com/zubanidze/telegramBot/master/TelegramTestBot/1146271698.webp");
            }
            if (e.Message.Text == "/sendlocation")
            {
                Message locationMessage = await botClient.SendVenueAsync(
                    chatId : e.Message.Chat.Id,
                    latitude : 56.8393f,
                    longitude : 60.5836f,
                    title : "ИНСТИТУТ ПРОЕКТИРОВАНИЯ, архитектуры и дизайна",
                    address : "ул. Шейнкмана, 10, Екатеринбург, Свердловская обл., 620014",
                    replyMarkup : new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl(
                                                               "Перейти на сайт организации",
                                                               "https://www.inpad.ru/")));
            }
            if (e.Message.Text == "/sendcontact")
            {
                Message contactMessage = await botClient.SendContactAsync(
                    chatId : e.Message.Chat.Id,
                    phoneNumber : "+73432875694",
                    firstName : "Виктор",
                    lastName : "Сальников");
            }
            if ((!e.Message.Text.Contains("/") && (!e.Message.Text.All(char.IsDigit))))
            {
                Message textMessage = await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : "Такой команды пока нет :(",
                    parseMode : ParseMode.Default,
                    replyMarkup : keyboard);
            }
            if (e.Message.Text == "custom")
            {
                var rkm  = new ReplyKeyboardMarkup();
                var rows = new List <KeyboardButton[]>();
                var cols = new List <KeyboardButton>();
                for (var Index = 1; Index < 17; Index++)
                {
                    cols.Add(new KeyboardButton("" + Index));
                    if (Index % 4 != 0)
                    {
                        continue;
                    }
                    rows.Add(cols.ToArray());
                    cols = new List <KeyboardButton>();
                }
                rkm.Keyboard = rows.ToArray();


                await botClient.SendTextMessageAsync(
                    e.Message.Chat,
                    "Choose",
                    replyMarkup : rkm);
            }
            if (e.Message.Text == "1")
            {
                Message textMessage = await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : "Hello, world!",
                    parseMode : ParseMode.Default,
                    disableNotification : false);
            }
            if (e.Message.Text == "2")
            {
                Message contactMessage = await botClient.SendContactAsync(
                    chatId : e.Message.Chat.Id,
                    phoneNumber : "+73432875694",
                    firstName : "Виктор",
                    lastName : "Сальников");
            }
            if (e.Message.Text == "3")
            {
                Message pollMessage = await botClient.SendPollAsync(
                    chatId : e.Message.Chat,
                    isAnonymous : false,
                    question : "Ты работаешь в ИнПАДе?",
                    options : new[]
                {
                    "Да",
                    "Нет, в другом месте"
                });
            }
        }
Example #14
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!"
                                   );
            }
        }
Example #15
0
        /// <summary>
        /// сообщения, которые присылает юзер
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            #region обработка неиспользуемых типов информации
            var    message = e.Message; //переменная, где хранится сообщение юзера
            string text;
            string nameOfUser = $"{message.From.FirstName} {message.From.LastName}";

            if (message.Type != MessageType.Text)
            {
                Console.WriteLine($"{nameOfUser} неопознанный объект");
                await bot.SendTextMessageAsync(message.From.Id, "Я пока маленький бот, который не умеет работать с этим типом данных :(");
            }
            #endregion

            Console.WriteLine($"{nameOfUser} сообщение: '{message.Text}'"); //вывод в консоль поведения юзера
            wsr_user_16Entities2 modelDB = new wsr_user_16Entities2();      //модель БД

            #region Обработка команд и введенного текста
            switch (message.Text)
            {
                #region Старт
            case "/start":
                await bot.SendPhotoAsync(message.From.Id, "http://katia.mitsisv.gr/wp-content/uploads/2018/11/frazi.png");

                text = $@"Рад приветствовать тебя, {nameOfUser}!

Представляю твоему вниманию всего навсего лучшее руководство по разработке на WPF!
Наш бот поможет тебе начать ориентировться в языке программирования C#, научит, как делать дизайн на платформе WPF, как подключать базы данных и многому другому.
Если тебе это интересно, то пиши команду /help, чтобы ознакомиться с тем, на что я способен 😉";
                //await bot.SendStickerAsync(message.From.Id, "file:///C:/Users/%D0%9D%D0%B8%D0%BA%D0%B8%D1%82%D0%B0/Desktop/sticker.webp");
                await bot.SendTextMessageAsync(message.From.Id, text);

                try
                {
                    modelDB.UserInfo.Add(new UserInfo()
                    {
                        UserName = e.Message.Chat.FirstName,
                        UserId   = e.Message.From.Id,
                        Message  = e.Message.Text
                    });
                    modelDB.SaveChanges();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Ошибка базы данных. \n {ex}");
                }

                break;
                #endregion

                #region Стоп
            case "/stop":
                text = "Очень жаль, конечно, что ты нас бросаешь, но я очень надеюсь, что тебе было интересно!";
                await bot.SendTextMessageAsync(message.From.Id, text);

                await bot.SendPhotoAsync(message.From.Id, "https://www.ivi.ru/titr/uploads/2016/09/02/da11cf8201ebe0d66e8178c4c5a34e4d.jpg/1400x0");

                try
                {
                    modelDB.UserInfo.Add(new UserInfo()
                    {
                        UserName = e.Message.Chat.FirstName,
                        UserId   = e.Message.From.Id,
                        Message  = e.Message.Text
                    });
                    modelDB.SaveChanges();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Ошибка базы данных. \n {ex}");
                }
                break;
                #endregion

                #region Топ на ютубе
            case "/youtube":
                var youtubeBlogers = new InlineKeyboardMarkup(new[]
                {
                    new[]
                    {
                        InlineKeyboardButton.WithCallbackData("SimpleCode")
                    },
                    new[]
                    {
                        InlineKeyboardButton.WithCallbackData("Гоша Дударь")
                    },
                    new[]
                    {
                        InlineKeyboardButton.WithCallbackData("BashkaMen Programming")
                    },
                    new[]
                    {
                        InlineKeyboardButton.WithCallbackData("Сергей Камянецкий")
                    }
                });
                await bot.SendPhotoAsync(message.From.Id, "https://i2.wp.com/lalupadesherlock.com/wp-content/uploads/2017/05/YouTube_logo-the-lab-media1.png?w=1920&ssl=1");

                await bot.SendTextMessageAsync(message.From.Id, "Держи список лучших русскоязычных блогеров-C#-программистов, которые научат тебя писать качественный код!", replyMarkup : youtubeBlogers);

                try
                {
                    modelDB.UserInfo.Add(new UserInfo()
                    {
                        UserName = e.Message.Chat.FirstName,
                        UserId   = e.Message.From.Id,
                        Message  = e.Message.Text
                    });
                    modelDB.SaveChanges();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Ошибка базы данных. \n {ex}");
                }
                break;
                #endregion

                #region Список тем
            case "/topic":
                var menuOfTopics = new InlineKeyboardMarkup(new[]
                {
                    new[]
                    {
                        InlineKeyboardButton.WithCallbackData("Введение в C#")
                    },
                    new[]
                    {
                        InlineKeyboardButton.WithCallbackData("Что нужно знать о платформе")
                    },
                    new[]
                    {
                        InlineKeyboardButton.WithCallbackData("Как установить Visual Studio"),
                        InlineKeyboardButton.WithCallbackData("Как устроена среда разработки")
                    },
                    new[]
                    {
                        InlineKeyboardButton.WithCallbackData("Hello World"),
                        InlineKeyboardButton.WithCallbackData("Переменные в C#")
                    },
                    new[]
                    {
                        InlineKeyboardButton.WithCallbackData("Переменные"),
                        InlineKeyboardButton.WithCallbackData("Массивы")
                    },
                    new[]
                    {
                        InlineKeyboardButton.WithCallbackData("Методы"),
                        InlineKeyboardButton.WithCallbackData("Классы")
                    },
                    //new[]
                    //{
                    //      InlineKeyboardButton.WithCallbackData("Наследование"),
                    //      InlineKeyboardButton.WithCallbackData("Полиморфизм")
                    //},
                    new[]
                    {
                        InlineKeyboardButton.WithCallbackData("Вывод случайного числа"),
                        InlineKeyboardButton.WithCallbackData("Программа сортировки массива")
                    },
                    new[]
                    {
                        InlineKeyboardButton.WithCallbackData("Что такое WPF, и с чем его едят")
                    },
                    new[]
                    {
                        InlineKeyboardButton.WithCallbackData("Как создать приложение WPF"),
                        InlineKeyboardButton.WithCallbackData("Как работает дизайн")
                    }
                }
                                                            );

                await bot.SendTextMessageAsync(message.From.Id, "Надеюсь, ниже ты найдешь что-то, что будет для тебя полезно!", replyMarkup : menuOfTopics);

                await bot.SendTextMessageAsync(message.From.Id, "Данные для статей были взяты с ресурса metanit.com.");

                try
                {
                    modelDB.UserInfo.Add(new UserInfo()
                    {
                        UserName = e.Message.Chat.FirstName,
                        UserId   = e.Message.From.Id,
                        Message  = e.Message.Text
                    });
                    modelDB.SaveChanges();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Ошибка базы данных. \n {ex}");
                }
                break;
                #endregion

                #region О нас
            case "/about":
                text = $@"Этот бот родился, как проект для Колледжа Предпринимательства №11 🏛
Над созданием данного продукта информационнай деятельности работали: Мазус Никита, Похиленко Александр, Хлыстова Дарья и Мовила Лидия. Рыды познакомиться с тобой, {nameOfUser}!
По любым вопросом и предложениям пиши, буду рад: @Mazus_nikita";
                await bot.SendTextMessageAsync(message.From.Id, text);

                await bot.SendStickerAsync(message.From.Id, "https://kickerock.github.io/let-s-Talk/img/avatr2.png");

                try
                {
                    modelDB.UserInfo.Add(new UserInfo()
                    {
                        UserName = e.Message.Chat.FirstName,
                        UserId   = e.Message.From.Id,
                        Message  = e.Message.Text
                    });
                    modelDB.SaveChanges();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Ошибка базы данных. \n {ex}");
                }
                break;
                #endregion

                #region Список книг
            case "/book":
                text = "Если ты хочешь изучить C# и WPF по книгам, что вот, у меня есть немного :)";
                var listOfBooks = new InlineKeyboardMarkup(new[]
                {
                    new[]
                    {
                        InlineKeyboardButton.WithCallbackData("Изучение C#")
                    },

                    new[]
                    {
                        InlineKeyboardButton.WithCallbackData("Изучение WPF")
                    },
                    new[]
                    {
                        InlineKeyboardButton.WithCallbackData("Изучение EntityFramework")
                    },
                    new[]
                    {
                        InlineKeyboardButton.WithCallbackData("Настольная книга C# разработчика")
                    }
                }
                                                           );
                await bot.SendTextMessageAsync(message.From.Id, $"{text} \n Надеюсь, ниже ты найдешь что-то, что будет для тебя полезно!", replyMarkup : listOfBooks);

                try
                {
                    modelDB.UserInfo.Add(new UserInfo()
                    {
                        UserName = e.Message.Chat.FirstName,
                        UserId   = e.Message.From.Id,
                        Message  = e.Message.Text
                    });
                    modelDB.SaveChanges();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Ошибка базы данных. \n {ex}");
                }
                break;
                #endregion

                #region Помощь
            case "/help":
                text = @"Для того, чтобы взаимодействовать с ботом, ты можешь использовать следующие команды:
/start - для вызова первого сообщения;
/stop - если я тебе надоел и ты хочешь прекратить общаться со мной;
/topic - тут ты можешь посмотреть все темы которые я знаю по WPF и изучить их вместе со мной!;
/about - если ты захотел узнать о нас, тыкай;
/youtube - каналы, которые помогут в изучении C#;
/book - литература, которая поможет глубже изучить программирование;
/help - полный список команд";
                await bot.SendPhotoAsync(message.From.Id, "https://upload.wikimedia.org/wikipedia/ru/thumb/1/11/Chip%27n_Dale_Rescue_Rangers_logo.jpg/250px-Chip%27n_Dale_Rescue_Rangers_logo.jpg");

                await bot.SendTextMessageAsync(message.From.Id, text);

                try
                {
                    modelDB.UserInfo.Add(new UserInfo()
                    {
                        UserName = e.Message.Chat.FirstName,
                        UserId   = e.Message.From.Id,
                        Message  = e.Message.Text
                    });
                    modelDB.SaveChanges();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Ошибка базы данных. \n {ex}");
                }
                break;
                #endregion

                #region Все остальное
            default:
                text = "Прости, я еще молодой бот и мало, чего умею, но я учусь, будь уверен 🤓";
                await bot.SendTextMessageAsync(message.From.Id, text);

                #region Добавление всех сообщений в базу данных
                try
                {
                    modelDB.UserInfo.Add(new UserInfo()
                    {
                        UserName = e.Message.Chat.FirstName,
                        UserId   = e.Message.From.Id,
                        Message  = e.Message.Text
                    });
                    modelDB.SaveChanges();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Ошибка базы данных. \n {ex}");
                }
                #endregion

                break;
                #endregion
            }
            #endregion
        }
Example #16
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"
                        );
                }
            }
        }
 public async override void Action(ITelegramBotClient client, Chat chat, int messageId)
 {
     await client.SendStickerAsync(chatId : chat, sticker : stickerUrl);
 }
Example #18
0
        private static async void OnMessage(object sender, MessageEventArgs messageEventArgs)
        {
            Message message     = messageEventArgs.Message;
            Chat    chatInfo    = message.Chat;
            string  messageText = message.Text.ToLower();

            if (messageText != null)
            {
                ITelegramBotClient client = TelegramBot.Instance.Client;
                Console.WriteLine($"{chatInfo.FirstName}: envío {message.Text}");

                switch (messageText)
                {
                case "/commands":
                case "/comandos":
                    StringBuilder commandsStringBuilder = new StringBuilder("Lista de Comandos:\n")
                                                          .Append("/commands\n")
                                                          .Append("/comandos\n")
                                                          .Append("/hola\n")
                                                          .Append("/hello\n")
                                                          .Append("/hi\n")
                                                          .Append("/foto\n")
                                                          .Append("/photo\n")
                                                          .Append("/sticker\n")
                                                          .Append("/link\n")
                                                          .Append("/voice\n")
                                                          .Append("/audio\n");


                    await client.SendTextMessageAsync(
                        chatId : chatInfo.Id,
                        text : commandsStringBuilder.ToString());

                    break;

                case "/hola":
                case "/hello":
                case "/hi":
                    await client.SendTextMessageAsync(
                        chatId : chatInfo.Id,
                        text : $"Hola, ¿cómo estás {chatInfo.FirstName}? 👋😀");

                    break;

                case "/foto":
                case "/photo":
                    using (Stream stream = System.IO.File.OpenRead("../../Assets/kotlin.jpg"))
                    {
                        await client.SendPhotoAsync(
                            chatId : chatInfo.Id,
                            photo : stream,
                            caption : "<b>Kotlin</b>. <i>Source</i>: <a href=\"https://www.meme-arsenal.com/en/create/meme/497325\">Meme Arsenal</a>",
                            parseMode : ParseMode.Html);
                    }
                    break;

                case "/sticker":
                    using (Stream stream = System.IO.File.OpenRead("../../Assets/csharp.webp"))
                    {
                        await client.SendStickerAsync(
                            chatId : chatInfo.Id,
                            sticker : stream);
                    }

                    break;

                case "/link":
                    using (Stream stream = System.IO.File.OpenRead("../../Assets/ACDC_Back_In_Black.ogg"))
                    {
                        await client.SendTextMessageAsync(
                            chatId : chatInfo.Id,
                            text : "https://www.youtube.com/watch?v=A6ZqNQdJPjc");
                    }

                    break;

                case "/voice":
                    using (Stream stream = System.IO.File.OpenRead("../../Assets/ACDC_Back_In_Black.ogg"))
                    {
                        await client.SendVoiceAsync(
                            chatId : chatInfo.Id,
                            voice : stream,

                            duration : 25);
                    }

                    break;

                case "/audio":
                    using (Stream stream = System.IO.File.OpenRead("../../Assets/darthVader.mp3"))
                    {
                        await client.SendAudioAsync(
                            chatId : chatInfo.Id,
                            title : "I'm your father",
                            performer : "Darth Vader",
                            thumb : "https://acib.es/wp-content/uploads/2015/11/arton427.jpg",
                            audio : stream,
                            duration : 3);
                    }

                    break;

                default:
                    await client.SendTextMessageAsync(
                        chatId : chatInfo.Id,
                        text : $"{chatInfo.FirstName}, no comprendo lo que dices 😕"
                        );

                    break;
                }
            }
        }