Ejemplo n.º 1
0
        public static async Task <PhotoHandler> FromMessage(IUpdateContext context, Message message)
        {
            long chatId = message?.Chat?.Id ?? -1;
            ITelegramBotClient botClient = context?.Bot?.Client;

            if (message == null || botClient == null || chatId < 0)
            {
                return(null);
            }

            PhotoSize photoSize = message.Photo.OrderByDescending(p => p.FileSize).First();

            Telegram.Bot.Types.File file = await botClient.GetFileAsync(photoSize.FileId);

            if (file != null)
            {
                string downloadedFilePath = await DownloadFile(botClient, file, chatId);

                if (!string.IsNullOrWhiteSpace(downloadedFilePath))
                {
                    return(new PhotoHandler(downloadedFilePath));
                }
            }

            return(null);
        }
Ejemplo n.º 2
0
        public async Task Should_Get_File_Info()
        {
            const int fileSize = 253736;

            #region Send Document

            Message documentMessage;
            using (Stream stream = System.IO.File.OpenRead(Constants.PathToFile.Documents.Hamlet))
            {
                documentMessage = await BotClient.SendDocumentAsync(
                    chatId : _fixture.SupergroupChat,
                    document : stream
                    );
            }

            string fileId = documentMessage.Document.FileId;

            #endregion

            File file = await BotClient.GetFileAsync(documentMessage.Document.FileId);

            Assert.Equal(fileId, file.FileId);
            Assert.InRange(file.FileSize, fileSize - 3500, fileSize + 3500);
            Assert.NotEmpty(file.FilePath);

            _classFixture.File = file;
        }
        async Task TelegramHandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
        {
            using var Trace = new Trace();  //This c# 8.0 using feature will auto dispose when the function is done.

            try
            {
                // Only process Message updates: https://core.telegram.org/bots/api#message
                if (update.Type != UpdateType.Message)
                {
                    Log($"Debug: Telegram: Received an unsupported update.type '{update.Type}'");
                    return;
                }

                // Only process text messages
                if (update.Message!.Type != Telegram.Bot.Types.Enums.MessageType.Text && update.Message!.Type != Telegram.Bot.Types.Enums.MessageType.Voice)
                {
                    Log($"Debug: Telegram: Received an unsupported update.Message.type '{update.Message!.Type}'");
                    return;
                }


                var chatId = update.Message.Chat.Id;
                var messageText = update.Message.Text.IsNotEmpty() ? update.Message.Text : "";

                Log($"Debug: Telegram: Received a '{update.Type}' with content '{messageText}' in chat {chatId}.");

                if (update.Message.Type == Telegram.Bot.Types.Enums.MessageType.Voice)
                {
                    var filePath = Path.Combine(Global.GetTempFolder(), update.Message.Voice.FileId + ".ogg");
                    Log($"Debug: Telegram: Downloading a {update.Message.Voice.FileSize} byte Voice recording to {filePath}...");

                    Stopwatch sw = Stopwatch.StartNew();
                    using (FileStream fileStream = System.IO.File.OpenWrite(filePath))
                    {
                        Telegram.Bot.Types.File file = await this.telegramBot.GetInfoAndDownloadFileAsync(fileId: update.Message.Voice.FileId, destination: fileStream);
                    }
                    Log($"Debug: ...Done in {sw.ElapsedMilliseconds}ms");
                    Global.TelegramControlMessage($"play:{filePath}");
                }
                else
                {
                    Global.TelegramControlMessage(messageText);
                }


                // Echo received message text
                //Telegram.Bot.Types.Message sentMessage = await botClient.SendTextMessageAsync(
                //    chatId: chatId,
                //    text: "You said:\n" + messageText,
                //    cancellationToken: cancellationToken);
            }
            catch (Exception ex)
            {
                Log($"Error: {ex.Msg()}");
            }
        }
Ejemplo n.º 4
0
        public static void _Check_Insert_Value_Photo(Options_Handler user_option, PhotoSize photo)
        {
            string name = "";

            if (!string.IsNullOrEmpty(photo.FileId))
            {
                name = _Get_New_Image_Name() + ".jpg";
                string localFilePath = AppDomain.CurrentDomain.BaseDirectory + "Temp\\" + name;
                try
                {
                    using (var fileStream = System.IO.File.OpenWrite(localFilePath))
                    {
                        Telegram.Bot.Types.File fileInfo = bot.GetInfoAndDownloadFileAsync(
                            fileId: photo.FileId,
                            destination: fileStream
                            ).Result;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error downloading: " + ex.Message);
                }
            }
            if (string.IsNullOrEmpty(user_option.Property_Photo))
            {
                user_option.Property_Photo = name + ",";
            }
            else
            {
                //extract names
                List <string> photos = user_option.Property_Photo.Split(',').ToList();
                if (photos.Count < 4)
                {
                    photos.Add(name);
                    string ptemp = "";
                    foreach (var item in photos)
                    {
                        ptemp += item + ",";
                    }
                    user_option.Property_Photo = ptemp;
                }
                else
                {
                    foreach (var item in photos)
                    {
                        if (item != name)
                        {
                            user_option.Property_Photo = user_option.Property_Photo.Replace(item, name);
                            break;
                        }
                    }
                }
            }
        }
Ejemplo n.º 5
0
        private static async Task CacheFile(MessageEventArgs e, FileBase file)
        {
            Console.WriteLine("CacheFile");
            TG_File tg_file = await botClient.GetFileAsync(file.FileId);

            files.Add(new Message
            {
                Caption  = e.Message.Caption,
                FileId   = tg_file.FileId,
                Type     = e.Message.Type,
                FilePath = tg_file.FilePath.Split('/').LastOrDefault()
            });
        }
Ejemplo n.º 6
0
        public static async void DownloadFile(Message message)
        {
            Telegram.Bot.Types.File file = new Telegram.Bot.Types.File();
            if (message.Type == Telegram.Bot.Types.Enums.MessageType.Document)
            {
                file = await bot.GetFileAsync(message.Document.FileId);
            }
            else if (message.Type == Telegram.Bot.Types.Enums.MessageType.Photo)
            {
                file = await bot.GetFileAsync(message.Photo.LastOrDefault().FileId);
            }

            var file_ext       = file.FilePath.Split('.').Last();
            var fileNameAndExt = file.FilePath.Split(Path.DirectorySeparatorChar).Last();

            string          fileLocalName = @"D:\Hadi\Files\" + fileNameAndExt;
            Uri             fileUrl       = new Uri(@"https://api.telegram.org/file/bot519136861:AAERMYATxZxEke91a6yvpjLwEOxJ2YaCWGc/" + file.FilePath);
            HttpWebResponse response      = null;
            WebClient       wbClnt        = null;
            var             request       = (HttpWebRequest)WebRequest.Create(fileUrl);

            request.Method = "HEAD";
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                wbClnt   = new WebClient();
                wbClnt.DownloadFileAsync(fileUrl, fileLocalName);
            }
            catch (WebException ex)
            {
                /* A WebException will be thrown if the status of the response is not `200 OK` */
            }
            finally
            {
                // Don't forget to close your response.
                if (response != null)
                {
                    response.Close();
                }
                if (wbClnt != null)
                {
                    wbClnt = null;
                }
            }
            //Stream strm = new FileStream(filePath, FileMode.Open);
            //https://api.telegram.org/file/bot<token>/<file_path>

            //await bot.DownloadFileAsync(fileName, strm);
            //cancellationToken:new System.Threading.CancellationToken(false) );
            //bot.DownloadFileAsync();
        }
Ejemplo n.º 7
0
        private async Task <Book> DownloadOriginalBookAsync(Document document)
        {
            string fileName         = document.FileName;
            string originalBookPath = Path.Combine(this.fileStorage,
                                                   $"{Guid.NewGuid().ToString()}{Path.GetExtension(fileName)}");

            await using Stream input = System.IO.File.OpenWrite(originalBookPath);
            File documentFile = await this.bot.GetFileAsync(document.FileId);

            await this.bot.DownloadFileAsync(documentFile.FilePath, input);

            return(new Book(Path.GetFileNameWithoutExtension(fileName),
                            BookFormat.FromExtension(Path.GetExtension(fileName)), originalBookPath));
        }
Ejemplo n.º 8
0
 internal static bool checkFileSize(Telegram.Bot.Types.File file, Update update, BotUser curUser)
 {
     try
     {
         //return true if file bigger 20 MB
         if (file.FileSize > (1024 * 1024 * 20))
         {
             return(true);
         }
     }
     catch
     {
         return(true);
     }
     return(false);
 }
Ejemplo n.º 9
0
        public async Task Should_Download_Write_Using_FileId()
        {
            int fileSize = _classFixture.File.FileSize;

            string destinationFilePath = $"{Path.GetTempFileName()}.{Fixture.FileType}";

            _output.WriteLine($@"Writing file to ""{destinationFilePath}""");

            using FileStream fileStream = System.IO.File.OpenWrite(destinationFilePath);
            File file = await BotClient.GetInfoAndDownloadFileAsync(
                fileId : _classFixture.File.FileId,
                destination : fileStream
                );

            Assert.InRange(fileStream.Length, fileSize - 100, fileSize + 100);
            Assert.True(JToken.DeepEquals(
                            JToken.FromObject(_classFixture.File), JToken.FromObject(file)
                            ));
        }
Ejemplo n.º 10
0
        public async Task <Image> GetProfileImageAsync(int userId)
        {
            Image profileImage;

            try {
                UserProfilePhotos profilePhotos = await TelegramBot.GetUserProfilePhotosAsync(userId);

                PhotoSize photoSize = profilePhotos.Photos[0][1];
                Telegram.Bot.Types.File profileFile = await TelegramBot.GetFileAsync(photoSize.FileId);

                Stream imageStream = new MemoryStream();
                Telegram.Bot.Types.File getFile = await TelegramBot.GetInfoAndDownloadFileAsync(profileFile.FileId, imageStream);

                profileImage = Image.FromStream(imageStream);
                //profileImage.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            } catch (Exception ex) {
                ErrorHandler.SetError(source: "GetProfileImageAsync", error: ex.Message);
                profileImage = Image.FromFile("unkown.png");
            }

            return(profileImage);
        }
Ejemplo n.º 11
0
        public async Task <Message> DownloadAttachments(Message M)
        {
            for (int i = 0; i < M.Attachments.Count; i++)
            {
                Telegram.Bot.Types.File TgFile = await Api.GetFileAsync(M.Attachments[i].RepresentationTg);

                string FileDir  = "";
                string FilePath = "";

                if (M.Attachments[i].Type == AttachmentsType.Sticker)
                {
                    FileDir = "CachedStickers";
                }
                else
                {
                    FileDir = "CachedData";
                }

                System.IO.Directory.CreateDirectory(FileDir);

                FilePath = TgFile.FileId + "_" + TgFile.FilePath;

                try
                {
                    FileStream File = new FileStream(FileDir + "/" + FilePath, FileMode.CreateNew);

                    TgFile.FileStream.CopyTo(File);
                    File.Close();

                    await Api.SendTextMessageAsync(M.ChatId, "Successfully loaded");
                } catch
                {
                    await Api.SendTextMessageAsync(M.ChatId, "Successfully not loaded, because cached");
                };
                //M.Attachments[i].FileName = FileDir + "/" + FilePath;
            }

            return(M);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Сохранение в файл.
        /// </summary>
        /// <param name="message">Мередать сообщение полученное ботом</param>
        /// <param name="bot">передать самого бота</param>
        internal static async void SaveToFile(tlgtype.Message message, TelegramBotClient bot)
        {
            string FileName = String.Empty;  //Временная переменная где храним название файла.

            tlgtype.File file = null;        //Временный обьек для сохранения файла.


            if (!System.IO.Directory.Exists(path + message.Type))     //Проверяем что папка существует. Если нет , то создаем ее.
            {
                Directory.CreateDirectory(path + message.Type);
            }



            switch (message.Type)                                                                                                        //Проверяем тип сообщения.
            {
            case MessageType.Photo:                                                                                                      //Если фото.
                tlgtype.PhotoSize[] photos = message.Photo;                                                                              //Получаем массив фото.
                FileStream          fsPoto;
                for (int iter = 0; iter <= photos.Length - 1; iter++)                                                                    //Проходимся по массиву.
                {
                    FileName = String.Format("{0}_{2}.{1}", DateTime.Now.ToString("MM_dd_yyyy_HH_mm_ss_fffff"), "jpg", iter.ToString()); //Формируем имя файла для сохранения.
                    file     = await bot.GetFileAsync(message.Photo[iter].FileId);                                                       //Получает файл во временную переменную.

                    #region т.к. надо несколко файлов сохранять с разными именами. То решил что самое простое будет сразу сохранять все.
                    fsPoto = new FileStream(path + message.Type + "\\" + FileName, FileMode.OpenOrCreate); //Создаем файловый поток.
                    await bot.DownloadFileAsync(file.FilePath, fsPoto);                                    //Скачиваем файл.

                    bot.SendTextMessageAsync(message.Chat.Id, String.Format(@"Файл сохранен по пути: {0}
Тип файла:{1}", fsPoto.Name, message.Type));                                                               //выводим сообщение пользователю.

                    fsPoto.Close();
                    fsPoto.Dispose();
                    Thread.Sleep(100);                 //Делаем задержку. На тесте телега лагать начала.
                    #endregion
                }
                return;

            case MessageType.Document:                                      //Если документ.
                FileName = message.Document.FileName;                       //Формируем имя файла для сохранения.
                file     = await bot.GetFileAsync(message.Document.FileId); //Получает файл во временную переменную.

                break;

            case MessageType.Video:                                                                       //Если видео
                FileName = String.Format("{0}.{1}", DateTime.Now.ToString("MM_dd_yyyy_HH_mm_ss"), "mp4"); //Формируем имя файла для сохранения.
                file     = await bot.GetFileAsync(message.Video.FileId);                                  //Получает файл во временную переменную.

                break;

            case MessageType.Audio:                                                                           //Если Аудио.
                FileName = String.Format("{0}-{2}.{1}", message.Audio.Performer, "mp3", message.Audio.Title); //Формируем имя файла для сохранения.
                file     = await bot.GetFileAsync(message.Audio.FileId);                                      //Получает файл во временную переменную.

                break;

            default:                                                                  //Ну и на крайний случай если не один из выше перечисленных.
                bot.SendTextMessageAsync(message.Chat.Id, "Тип файла не распознан."); //Сообщаем что бот не знает о такой типе файла.
                return;                                                               //выходим из метода сохранения
            }



            if (FileName == String.Empty)       //На крайний случай. Если имя файла не сформировано то выходим из метода сохранения
            {
                return;
            }


            var fs = new FileStream(path + message.Type + "\\" + FileName, FileMode.OpenOrCreate); //Создаем файловый поток.

            await bot.DownloadFileAsync(file.FilePath, fs);                                        //Скачиваем файлы.

            bot.SendTextMessageAsync(message.Chat.Id, String.Format(@"Файл сохранен по пути: {0}
Тип файла:{1}", fs.Name, message.Type));                                                           //выводим сообщение пользователю.
            fs.Close();                                                                            //Закрываем файловый поток
            fs.Dispose();                                                                          //Помечаем утилизируем файловый поток. Вроде как это не само удаление, а пометка для сборщика + можно финализирующую логику писать для Dispose()
            Thread.Sleep(100);                                                                     //Задержка что бы телега не лагала.
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Get file extension (File class)
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string GetFileExtension(this File file)
        {
            string path = file.FilePath;

            return(path.Substring(path.LastIndexOf('.')));
        }
Ejemplo n.º 14
0
        private async void OnMessageReceived(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            try
            {
                if (e.Message.Chat.Type != ChatType.Group)
                {
                    return;
                }

                long chatId = e.Message.Chat.Id;

                var settings = _cashlogSettingsService.ReadSettings();

                /*if (chatId.ToString() != settings.AdminChatToken)
                 * {
                 *  _logger.Info($"{GetType().Name}: Произведена попытка использования бота в группе `{e.Message.Chat.Title}` ({chatId})");
                 *  await _client.SendTextMessageAsync(chatId, "Чтобы бот мог работать в этой группе обратитесь к @vsoff");
                 *  return;
                 * }*/

                // Получаем группу этого чата.
                Group group = await _groupService.GetByChatTokenAsync(chatId.ToString());

                // Если группы для этого чата нету, то создаём её.
                if (group == null)
                {
                    var admins = await _client.GetChatAdministratorsAsync(chatId);

                    var creator = admins.FirstOrDefault(x => x.Status == ChatMemberStatus.Creator);

                    if (creator == null)
                    {
                        _logger.Warning($"В группе {chatId} не был найден создатель");
                        return;
                    }

                    group = await _groupService.AddAsync(e.Message.Chat.Id.ToString(), creator.User.Id.ToString(), e.Message.Chat.Title ?? "Default chat name");
                }

                Customer[] customers = await _customerService.GetListAsync(group.Id);

                // Собираем всю информацию о пользователе и сообщении.
                UserMessageInfo userMessageInfo = new UserMessageInfo
                {
                    Group       = group,
                    Customers   = customers,
                    UserName    = e.Message.From.Username,
                    UserToken   = e.Message.From.Id.ToString(),
                    MessageType = Core.Models.MessageType.Unknown,
                    Message     = new MessageInfo
                    {
                        //e.Message.ReplyToMessage.MessageId
                        Token       = e.Message.MessageId.ToString(),
                        ReceiptInfo = null,
                        Text        = e.Message.Text,
                    }
                };

                // Дописываем дополнительную инфу.
                switch (e.Message.Type)
                {
                case MessageType.Photo:
                {
                    PhotoSize photoSize = e.Message.Photo.OrderByDescending(x => x.Width).First();
                    _logger.Trace($"{GetType().Name}: Получено фото чека с разрешением W:{photoSize.Width} H:{photoSize.Height}");

                    File file = await _client.GetFileAsync(photoSize.FileId);

                    // Скачиваем изображение.
                    byte[] imageBytes;
                    try
                    {
                        await using MemoryStream clientStream = new MemoryStream();
                        await _client.DownloadFileAsync(file.FilePath, clientStream);

                        imageBytes = clientStream.ToArray();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Ошибка во время скачки изображения с чеком из telegram", ex);
                    }

                    _logger.Trace($"{GetType().Name}: Получено изображение из потока размером {imageBytes.Length} байт");

                    var data = _receiptHandleService.ParsePhoto(imageBytes);
                    _logger.Trace(data == null ? $"{GetType().Name}: Не удалось распознать QR код на чеке" : $"{GetType().Name}: Данные с QR кода чека {data.RawData}");

                    userMessageInfo.Message.ReceiptInfo = data;
                    userMessageInfo.MessageType         = Core.Models.MessageType.QrCode;

                    break;
                }

                case MessageType.Text:
                {
                    userMessageInfo.MessageType = Core.Models.MessageType.Text;
                    break;
                }
                }

                // Уведомляем подписчиков о новом сообщении.
                OnMessage?.Invoke(this, userMessageInfo);
            }
            catch (Exception ex)
            {
                _logger.Error($"{GetType().Name}: Во время обработки полученного сообщения произошла ошибка", ex);
            }
        }
Ejemplo n.º 15
0
        private static async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs)
        {
            var message  = messageEventArgs.Message;
            var userFrom = message.From;
            var loadUser = _userManager.CheckUserRegistration(userFrom.Id.ToString());

            if (message.Type == MessageType.Photo)
            {
                if (loadUser == null)
                {
                    await TelegramBotEndpoint.SendTextMessageAsync(
                        message.Chat.Id,
                        $"Type /start for your registration");

                    return;
                }

                Telegram.Bot.Types.File file = await TelegramBotEndpoint.GetFileAsync(message.Photo[message.Photo.Count() - 1].FileId);

                using (FileStream Filestream = System.IO.File.Create("img" + loadUser.ChatId + ".jpg"))
                {
                    await TelegramBotEndpoint.GetInfoAndDownloadFileAsync(file.FileId, Filestream);

                    byte[] byteData = GetImageAsByteArray(Filestream);
                    _userManager.AddPhoto(loadUser, "img" + loadUser.ChatId + ".jpg");
                    var faceData = await _faceApiManager.MakeAnalysisRequest(byteData);

                    if (faceData != null)
                    {
                        _userManager.AddGenderAge(loadUser, faceData);
                        await TelegramBotEndpoint.SendTextMessageAsync(
                            message.Chat.Id,
                            $"Your photo successfully uploaded");

                        return;
                    }
                    await TelegramBotEndpoint.SendTextMessageAsync(
                        message.Chat.Id,
                        $"FaceApi Service Temporary unavalible");
                }

                return;
            }



            if (message.Type == MessageType.Text)
            {
                switch (message.Text.Split(' ').First())
                {
                case "/start":

                    if (loadUser == null)
                    {
                        UserModel model = new UserModel()
                        {
                            ChatId   = userFrom.Id.ToString(),
                            UserName = userFrom.Username
                        };

                        var registeredUser = _userManager.SignUpApplicationUser(model);

                        await TelegramBotEndpoint.SendTextMessageAsync(
                            message.Chat.Id,
                            $"Hello {registeredUser.UserName}, you are signed up!,\n" +
                            $"Now you can upload your photo in jpg format");

                        break;
                    }
                    else
                    {
                        string backMessage;
                        if (loadUser.Photo != null)
                        {
                            backMessage = $"Hello {loadUser.UserName}, welcome back!\n";
                        }
                        else
                        {
                            backMessage = $"Hello {loadUser.UserName}, welcome back!\n" +
                                          $"Don't forget to upload your photo!";
                        }
                        await TelegramBotEndpoint.SendTextMessageAsync(
                            message.Chat.Id,
                            backMessage
                            );

                        break;
                    }

                case "/getpair":
                    if (loadUser == null)
                    {
                        await TelegramBotEndpoint.SendTextMessageAsync(
                            message.Chat.Id,
                            $"Type /start for your registration");

                        return;
                    }
                    if (loadUser.Photo == null)
                    {
                        await TelegramBotEndpoint.SendTextMessageAsync(
                            message.Chat.Id,
                            $"Try to upload your photo");

                        return;
                    }

                    var pair = _userManager.GetPair(loadUser);
                    if (pair == null)
                    {
                        await TelegramBotEndpoint.SendTextMessageAsync(
                            message.Chat.Id,
                            $"No pair for you. Try later");

                        return;
                    }
                    await TelegramBotEndpoint.SendTextMessageAsync(
                        message.Chat.Id,
                        $"User name: {pair.UserName}\n" +
                        $"Age: {pair.Age}");

                    using (FileStream stream = new FileStream(pair.Photo, FileMode.Open))
                    {
                        await TelegramBotEndpoint.SendPhotoAsync(message.Chat.Id, stream);
                    }
                    break;
                }
            }
        }
Ejemplo n.º 16
0
        public static void UpdateImagePoint(Message message, TelegramBotClient client, Telegram.Bot.Types.File file)
        {
            var link      = "https://api.telegram.org/file/bot" + $"{ConfigurationManager.AppSettings["KeyBot"]}/{file.FilePath}";
            var image     = Image.FromStream(new MemoryStream(new WebClient().DownloadData(link)));
            var userImage = ImageToByte(image, client, message);

            using (var connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString))
            {
                using (var context = new MainDbContext(connection, false))
                {
                    connection.Open();
                    var lastPoint  = context.AllPoints.Max(p => p.IdPoint);
                    var parameter1 = new MySqlParameter("@lastPoint", lastPoint);
                    var parameter2 = new MySqlParameter("@userImage", userImage)
                    {
                        MySqlDbType = MySqlDbType.Blob
                    };
                    context.Database.ExecuteSqlCommand("UPDATE locationpoints SET ImagePoint = @userImage WHERE IdPoint = @lastPoint", parameter1, parameter2);
                }
            }
        }
Ejemplo n.º 17
0
 public async void SendShigetsuScreen(Telegram.Bot.Types.File file, long chatId)
 {
     await client.SendPhotoAsync(ConfigSettings.supalapkaId, file.FileId, replyMarkup : ConfirmButtons(chatId), caption : chatId.ToString());
 }
Ejemplo n.º 18
0
        private async static void StartServer()
        {
            try
            {
                TelegramBotClient client = new TelegramBotClient("269007176:AAFGjCV3qxbzLw0h4rVREGznLzJWXEFJWa0");
                User user = await client.GetMeAsync();

                Log("Bot is online");

                int offset = 0;
                while (!m_Close)
                {
                    Update[] updates = client.GetUpdatesAsync(offset).Result;
                    foreach (Update update in updates)
                    {
                        int index = -1;
                        if (update.Message.Text != null && (index = update.Message.Text.ToLower().IndexOf("durchsage:")) != -1)
                        {
                            string message = update.Message.Text.Substring(index + 10).Trim();
                            Log(string.Format("New Announcement ({0}): {1}", update.Message.From.FirstName, message));

                            m_Synthesizer.Speak(string.Format("Achtung, eine Durchsage: {0}", message));
                        }
                        else if (update.Message.Type == Telegram.Bot.Types.Enums.MessageType.VoiceMessage)
                        {
                            string                  fileID = update.Message.Voice.FileId;
                            MemoryStream            buffer = new MemoryStream();
                            Telegram.Bot.Types.File file   = await client.GetFileAsync(fileID, buffer);

                            buffer.Position = 0;

                            // Debug: Write to File
                            if (System.IO.File.Exists("Test.ogg"))
                            {
                                System.IO.File.Delete("Test.ogg");
                            }
                            FileStream fileStream = new FileStream("Test.ogg", FileMode.CreateNew, FileAccess.Write);
                            fileStream.Write(buffer.GetBuffer(), 0, (Int32)buffer.Length);
                            fileStream.Flush();
                            fileStream.Close();

                            ATL.AudioReaders.IAudioDataReader audioReader = ATL.AudioReaders.AudioReaderFactory.GetInstance().GetDataReader("Test.ogg");
                            audioReader.ReadFromFile("Test.ogg");
                            Int32 duration = (Int32)audioReader.Duration;

                            ProcessStartInfo startInfo = new ProcessStartInfo();
                            startInfo.FileName  = "C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe";
                            startInfo.Arguments = "C:\\Users\\Roland\\OneDrive\\Projects\\AnnouncementBot\\AnnouncementBot\\bin\\Debug\\Test.ogg";
                            Process process = Process.Start(startInfo);
                            Thread.Sleep((duration + 5) * 1000);
                            process.Kill();
                        }


                        offset = update.Id + 1;
                    }
                }
            }
            catch (Exception ex)
            {
                Log("Exception caught: " + ex.Message);
            }
        }
Ejemplo n.º 19
0
        private async void _telegramBotClient_OnUpdateAsync(object sender, Telegram.Bot.Args.UpdateEventArgs e)
        {
            User _usuarioTel = new User();

            Telegram.Bot.Types.Message _message = new Telegram.Bot.Types.Message();

            try
            {
                // Obtenemos
                _usuarioTel = e.Update.CallbackQuery != null ? e.Update.CallbackQuery.From : e.Update.Message.From;
                _message    = e.Update.CallbackQuery != null ? e.Update.CallbackQuery.Message : e.Update.Message;
                string valor = e.Update.CallbackQuery != null ? e.Update.CallbackQuery.Data : e.Update.Message.Text;

                if (!Directory.Exists($"C:\\bot\\{_usuarioTel.Id}"))
                {
                    Directory.CreateDirectory($"C:\\bot\\{_usuarioTel.Id}");
                }

                string ext         = string.Empty;
                string downloadUrl = string.Empty;

                lblDescargados.Text = $"Procesados: {++procesados:n2}";

                switch (_message.Type)
                {
                case MessageType.Document:
                    var  document     = _message.Document;
                    File fileDocument = await _telegramBotClient.GetFileAsync(document.FileId);

                    ext         = Path.GetExtension(fileDocument.FilePath);
                    downloadUrl = $"https://api.telegram.org/file/bot{txtToken.Text}/{fileDocument.FilePath}";
                    string documentFileName = $"C:\\bot\\{_usuarioTel.Id}\\{Guid.NewGuid()}{ext}";
                    using (WebClient webClient = new WebClient())
                    {
                        webClient.DownloadFile(new Uri(downloadUrl), documentFileName);
                    }

                    try
                    {
                        using (Stream stream = System.IO.File.OpenRead(documentFileName))
                        {
                            await _telegramBotClient.SendPhotoAsync(13707657, stream);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }

                    break;

                case MessageType.Photo:
                    PhotoSize photoSize = _message.Photo.OrderByDescending(x => x.FileSize).FirstOrDefault() ?? new PhotoSize();
                    File      filePhoto = await _telegramBotClient.GetFileAsync(photoSize.FileId);

                    ext         = Path.GetExtension(filePhoto.FilePath);
                    downloadUrl = $"https://api.telegram.org/file/bot{txtToken.Text}/{filePhoto.FilePath}";
                    string photoFilename = $"C:\\bot\\{_usuarioTel.Id}\\{Guid.NewGuid()}{ext}";
                    using (WebClient webClient = new WebClient())
                    {
                        webClient.DownloadFile(new Uri(downloadUrl), photoFilename);
                    }

                    try
                    {
                        using (Stream stream = System.IO.File.OpenRead(photoFilename))
                        {
                            await _telegramBotClient.SendPhotoAsync(13707657, stream);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }

                    break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ha ocurrido un error; {ex.Message}");
            }
        }