コード例 #1
0
        /// <summary>
        /// Force load of storage file from telegram.
        /// Carefully, you can loose your unsaved data.
        /// </summary>
        public async Task ForceLoad()
        {
            using (await _saveLock.LockAsync())
            {
                var chat = await _botClient.GetChatAsync(_saveResChatId);

                if (chat.PinnedMessage?.Caption?.Trim() != FileResName)
                {
                    //Can't find storage.
                    File.WriteAllText(_storageFilePath, "{}");
                }
                else
                {
                    var fileId = chat.PinnedMessage.Document.FileId;
                    if (File.Exists(_storageFilePath))
                    {
                        File.Delete(_storageFilePath);
                    }
                    using (var stream = File.OpenWrite(_storageFilePath))
                    {
                        await _botClient.GetInfoAndDownloadFileAsync(fileId, stream);
                    }
                }

                LoadStorageStateFromFile();
            }
        }
コード例 #2
0
        public async Task Download()
        {
            if (IsDownloaded)
            {
                return;
            }

            if (IsEncrypt)
            {
                throw new ArgumentException("An encrypted message cannot download");
            }

            ITelegramBotClient telegramBotClient = ModulesManager.GetModulesManager().GetTelegramBotClient();

            using (MemoryStream stream = new MemoryStream())
            {
                await telegramBotClient.GetInfoAndDownloadFileAsync(photoId, stream);

                byte[] imageBytes = stream.ToArray();
                content = Convert.ToBase64String(imageBytes);
            }

            photoId      = null;
            IsDownloaded = true;
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: vladbovin/VoiceToTextBot
        static async void TgBot_OnMessage(object sender, MessageEventArgs e)
        {
            if (e.Message.Voice != null)
            {
                var message = await _tgBotClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : "Распознаю речь..."
                    );

                var tgAudioFilePath = $"{Guid.NewGuid()}.ogg";
                var tgAudioStream   = new FileStream(tgAudioFilePath, FileMode.Create);
                await _tgBotClient.GetInfoAndDownloadFileAsync(e.Message.Voice.FileId, tgAudioStream);

                tgAudioStream.Close();

                var resultTextMessage = await RecognizeText(tgAudioFilePath);

                File.Delete(tgAudioFilePath);

                await _tgBotClient.EditMessageTextAsync(
                    chatId : message.Chat.Id,
                    messageId : message.MessageId,
                    text : resultTextMessage
                    );
            }
        }
コード例 #4
0
        public async Task <Stream> FetchFile(string fileId)
        {
            var ms = new MemoryStream();

            await _telegramBotClient.GetInfoAndDownloadFileAsync(fileId, ms);

            return(ms);
        }
コード例 #5
0
        public async Task Begin()
        {
            // Arrange
            var turnContext    = A.Fake <ITurnContext>();
            var imageHuntState = new ImageHuntState()
            {
                GameId = 15, TeamId = 16, CurrentLatitude = 15.2, CurrentLongitude = 56, Status = Status.Started
            };

            A.CallTo(() => turnContext.GetConversationState <ImageHuntState>()).Returns(imageHuntState);
            var photoSize1 = new PhotoSize()
            {
                FileSize = 15, FileId = "15"
            };
            var photoSize2 = new PhotoSize()
            {
                FileSize = 1195247, FileId = "AgADBAADOawxG-RQqVO-4ni8OVZOPOnykBkABDQFk1xY-YUAAR0SAgABAg"
            };
            var activity = new Activity()
            {
                ActivityType = ActivityType.Message,
                ChatId       = 15,
                Pictures     = new[]
                {
                    photoSize1,
                    photoSize2
                }
            };

            A.CallTo(() => turnContext.Activity).Returns(activity);

            // Act
            await _target.Begin(turnContext);

            // Assert
            A.CallTo(() => turnContext.GetConversationState <ImageHuntState>()).MustHaveHappened();
            A.CallTo(() => _telegramBotClient.GetInfoAndDownloadFileAsync(A <string> ._, A <Stream> ._, A <CancellationToken> ._)).MustHaveHappened();
            A.CallTo(() => _teamWebService.UploadImage(A <ImageHuntWebServiceClient.Request.UploadImageRequest> ._)).MustHaveHappened();
            A.CallTo(() => turnContext.ReplyActivity(A <Activity> ._)).MustHaveHappened();
            A.CallTo(() => turnContext.End()).MustHaveHappened();
            A.CallTo(() => _logger.Log(A <LogLevel> ._, A <EventId> ._, A <object> ._, A <Exception> ._,
                                       A <Func <object, Exception, string> > ._))
            .WithAnyArguments()
            .MustHaveHappened();
        }
コード例 #6
0
    private async Task HandleFileBaseAsync(Message receivedMessage, Message sentMessage, string inputFileName,
                                           string fileId, CancellationToken cancellationToken)
    {
        await using (var fileStream = File.Create(inputFileName))
        {
            await _bot.GetInfoAndDownloadFileAsync(fileId, fileStream, cancellationToken);
        }

        await SendMessageAsync(receivedMessage, sentMessage, inputFileName, cancellationToken);
    }
コード例 #7
0
        public async void SendPhoto(ITelegramBotClient botClient, MessageEventArgs photo, AppUser user)
        {
            Photo newPhoto = new Photo(Guid.NewGuid(), user.UserId);
            var   path     = Path.Combine(PATH_TO_SERVER_STORAGE, newPhoto.GetPhysicalName);

            using (MemoryStream mem = new MemoryStream())
            {
                var r1 = await botClient.GetInfoAndDownloadFileAsync(photo.Message.Photo[1].FileId, mem);

                _userPhotoRepository.AttachPhoto(mem.ToArray(), newPhoto);
            }
        }
コード例 #8
0
        public async override void Handle(MessageWrapper message, ITelegramBotClient client)
        {
            if (!(message.Document is null) && (message.Document?.FileName?.EndsWith("fb2") ?? false))
            {
                var    ctsource = new CancellationTokenSource(TimeSpan.FromMinutes(10));
                var    ru       = "йцукенгшщзхъфывапролджэячсмитьбю" + "йцукенгшщзхъфывапролджэячсмитьбю".ToUpper();
                var    en       = "icukengsszh-fyvaproldzeacsmin-bu" + "icukengsszh-fyvaproldzeacsmin-bu".ToUpper();
                string rfn      = message.Document.FileName;
                for (int i = 0; i < ru.Length; i++)
                {
                    rfn = rfn.Replace(ru[i], en[i]);
                }
                var bookFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, rfn);
                using (var fs = File.OpenWrite(bookFilePath))
                {
                    await client.GetInfoAndDownloadFileAsync(message.Document.FileId, fs, ctsource.Token);

                    fs.Flush();
                }
                var    a               = new Process();
                string outp            = "";
                string newbookFilePath = null;
                Regex  rr              = new Regex("failed: [1-9]+?");
                try
                {
                    a.StartInfo.FileName               = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"translator\fb2pdf.cmd");
                    a.StartInfo.Arguments              = $"\"{bookFilePath}\"";
                    a.StartInfo.WindowStyle            = ProcessWindowStyle.Normal;
                    a.StartInfo.RedirectStandardOutput = true;
                    a.Start();
                    outp = a.StandardOutput.ReadToEnd();
                    a.WaitForExit();
                    newbookFilePath = bookFilePath.Replace("fb2", "pdf");
                    using (var fs = File.OpenRead(newbookFilePath))
                    {
                        await client.SendDocumentAsync(message.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(fs, rfn.Replace("fb2", "pdf")));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                if (rr.IsMatch(outp))
                {
                    await client.SendTextMessageAsync(message.Chat.Id, "errors when converting");
                }
                File.Delete(bookFilePath);
                if (newbookFilePath != null)
                {
                    File.Delete(newbookFilePath);
                    File.Delete(bookFilePath + "pdf");
                }
            }
コード例 #9
0
        private async Task DownloadInternalAsync()
        {
            ITelegramBotClient telegramBotClient = ModulesManager.GetTelegramBotClient();

            using (MemoryStream stream = new MemoryStream())
            {
                await telegramBotClient.GetInfoAndDownloadFileAsync(photoId, stream);

                byte[] imageBytes = stream.ToArray();
                content = Convert.ToBase64String(imageBytes);
            }

            photoId      = null;
            IsDownloaded = true;
        }
コード例 #10
0
        public async Task Begin()
        {
            // Arrange
            var turnContext    = A.Fake <ITurnContext>();
            var imageHuntState = new ImageHuntState()
            {
                GameId = 15, TeamId = 16, CurrentLatitude = 15.2, CurrentLongitude = 56, Status = Status.Started
            };

            A.CallTo(() => turnContext.GetConversationState <ImageHuntState>()).Returns(imageHuntState);
            A.CallTo(() => _telegramBotClient.GetInfoAndDownloadFileAsync(A <string> ._, A <Stream> ._, A <CancellationToken> ._))
            .Invokes((string fileId, Stream stream, CancellationToken cancellationToken) => { stream.Write(new byte[10], 0, 10); });
            var document1 = new Document()
            {
                FileSize = 15, FileId = "15", MimeType = "image/jpeg"
            };

            var activity = new Activity()
            {
                ActivityType = ActivityType.Message,
                ChatId       = 15,
                Document     = document1
            };

            A.CallTo(() => turnContext.Activity).Returns(activity);

            // Act
            await _target.Begin(turnContext);

            // Assert
            A.CallTo(() => turnContext.GetConversationState <ImageHuntState>()).MustHaveHappened();
            A.CallTo(() => _telegramBotClient.GetInfoAndDownloadFileAsync(A <string> ._, A <Stream> ._, A <CancellationToken> ._)).MustHaveHappened();
            A.CallTo(() => _teamWebService.UploadImage(A <UploadImageRequest> ._)).MustHaveHappened();
            A.CallTo(() => turnContext.ReplyActivity(A <Activity> ._)).MustHaveHappened();
            A.CallTo(() => turnContext.End()).MustHaveHappened();
        }
コード例 #11
0
        private async Task <string> ProcessGpx(Message message, YasUser yasUser)
        {
            var fileId   = message.Document.FileId;
            var fileName = message.Document.FileName;

            await using var memoryStream = new MemoryStream();
            await _telegramBot.GetInfoAndDownloadFileAsync(fileId, memoryStream);

            memoryStream.Position = 0;
            XNamespace ns      = "http://www.topografix.com/GPX/1/1";
            var        root    = XElement.Load(memoryStream);
            var        orderId = 0;
            var        points  = root.Elements(ns + "rte").Elements(ns + "rtept")
                                 .Union(root.Elements(ns + "wpt"))
                                 .Select(w => new YasWaypoint()
            {
                Name      = w.Element(ns + "name")?.Value,
                Latitude  = Convert.ToDecimal(w.Attribute("lat")?.Value),
                Longitude = Convert.ToDecimal(w.Attribute("lon")?.Value),
                OrderId   = orderId++
            }).ToList();

            if (points.Count == 0)
            {
                return($"No route or way points were found in {fileName} ");
            }

            var route = new YasRoute
            {
                UserId     = yasUser.UserId,
                UploadTime = DateTime.UtcNow,
                RouteName  = root.Element(ns + "rte")?.Element(ns + "name")?.Value ?? Path.GetFileNameWithoutExtension(fileName)
            };

            await using var db = _dbFactory.Create();
            await db.BeginTransactionAsync();

            route.RouteId = await db.GetTable <YasRoute>().DataContext.InsertWithInt64IdentityAsync(route);

            foreach (var point in points)
            {
                point.RouteId = route.RouteId;
            }
            db.BulkCopy(points);
            await db.CommitTransactionAsync();

            return($"The route <b> {route.RouteId} </b> : {route.RouteName} ({points.Count} way points) has been uploaded \n userId:{yasUser.PublicId}");
        }
コード例 #12
0
        internal async Task <IpicUploadResult> UploadImageToIpicAsync(string fileId, CancellationToken cancellationToken)
        {
            _logger.LogInformation("Running upload for file_id {0}", fileId);

            await using var fileStream = new MemoryStream();
            var file = await _botClient.GetInfoAndDownloadFileAsync(fileId, fileStream, cancellationToken);

            fileStream.Position = 0;
            var fileName = Path.GetFileName(file.FilePath);

            _logger.LogInformation("File name of {0} is {1}", fileId, fileName);

            cancellationToken.ThrowIfCancellationRequested();

            using var formData = new MultipartFormDataContent();

            using var fileContent = new StreamContent(fileStream);
            using var tnsize      = new StringContent("150");
            using var name        = new StringContent(fileName);
            using var quality     = new StringContent("75");
            using var client      = new StringContent("ipic.su");
            using var action      = new StringContent("loadimg");
            using var link        = new StringContent("/");

            formData.Add(fileContent, "image", fileName);
            formData.Add(tnsize, "tnsize");
            formData.Add(name, "name");
            formData.Add(quality, "quality");
            formData.Add(client, "client");
            formData.Add(action, "action");
            formData.Add(link, "link");

            using var response = await _httpClient.PostAsync("/", formData, cancellationToken);

            await using var responseStream = await response.Content.ReadAsStreamAsync();

            _logger.LogDebug("Response status code is {0}", response.StatusCode);

            using var scope = _serviceProvider.CreateScope();
            var ipicParseService = scope.ServiceProvider.GetRequiredService <IpicParseService>();

            return(new IpicUploadResult
            {
                FileName = fileName,
                FileUrl = ipicParseService.ParseShortLinkToUploadedImage(responseStream)
            });
        }
コード例 #13
0
        /// <summary>
        /// Downloads an encrypted Passport file, decrypts it, and writes the content to
        /// <paramref name="destination"/> stream
        /// </summary>
        /// <param name="botClient">Instance of bot client</param>
        /// <param name="passportFile"></param>
        /// <param name="fileCredentials"></param>
        /// <param name="destination"></param>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <returns>File information of the encrypted Passport file on Telegram servers.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static async Task <File> DownloadAndDecryptPassportFileAsync(
            this ITelegramBotClient botClient,
            PassportFile passportFile,
            FileCredentials fileCredentials,
            System.IO.Stream destination,
            CancellationToken cancellationToken = default
            )
        {
            if (passportFile == null)
            {
                throw new ArgumentNullException(nameof(passportFile));
            }
            if (fileCredentials == null)
            {
                throw new ArgumentNullException(nameof(fileCredentials));
            }
            if (destination == null)
            {
                throw new ArgumentNullException(nameof(destination));
            }

            File fileInfo;

            var encryptedContentStream = passportFile.FileSize > 0
                ? new System.IO.MemoryStream(passportFile.FileSize)
                : new System.IO.MemoryStream();

            using (encryptedContentStream)
            {
                fileInfo = await botClient.GetInfoAndDownloadFileAsync(
                    passportFile.FileId,
                    encryptedContentStream,
                    cancellationToken
                    ).ConfigureAwait(false);

                encryptedContentStream.Position = 0;

                await new Decrypter().DecryptFileAsync(
                    encryptedContentStream,
                    fileCredentials,
                    destination,
                    cancellationToken
                    ).ConfigureAwait(false);
            }

            return(fileInfo);
        }
コード例 #14
0
        public static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            var dateCurrent = DateTime.Today;
            var listPeople  = Service.GetAll();
            var senderId    = e.Message.From.Id;

            UserInfos.TryGetValue(senderId, out var userInfo);

            if (userInfo == null)
            {
                userInfo = new UserInfo
                {
                    Emotion = new Emotion(),
                    Human   = new Human(),
                    Step    = 0,
                    Photo   = new Photo()
                };

                UserInfos.Add(senderId, userInfo);
                userInfo.Human.SenderId = senderId;
                userInfo.Human.Date     = dateCurrent;

                await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : "Привет, меня зовут Гриша-Голубь и я являюсь ботом, который распознает твои эмоции по фотографии, которую ты мне отправищь)"
                    );

                //var listPeople = Service.GetAll();
                foreach (var i in listPeople)
                {
                    if (userInfo.Human.SenderId == i.SenderId)
                    {
                        userInfo.Step = 4;
                        await botClient.SendTextMessageAsync(
                            chatId : e.Message.Chat,
                            text : "Вы уже записаны в базе.Рады вас снова видеть) "

                            );

                        return;
                    }
                    else
                    {
                        userInfo.Step = 0;
                        await botClient.SendTextMessageAsync(
                            chatId : e.Message.Chat,
                            text : "Рады с вами познакомится) Позвольте записать вас в базу"
                            );

                        return;
                    }
                }
            }

            if (userInfo.Step == 0)
            {
                userInfo.Step++;
                await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : "Начнем?"
                    );

                return;
            }

            if (userInfo.Step == 1)
            {
                if (e.Message.Text == "да" || e.Message.Text == "Да" || e.Message.Text == "Yes")

                {
                    userInfo.Step++;
                    await botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : "Отлично, как тебя зовут?"
                        );

                    return;
                }

                if (e.Message.Text == "нет" || e.Message.Text == "Нет" || e.Message.Text == "No")

                {
                    userInfo.Step++;
                    await botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : "Так, кто бы ты ни был, ты ОФИГЕЛ!!! Я тут значит работаю, твои эмоции пытаюсь просканировать, а ты со мной разговаривать значит не хочешь??? У тя просто ннет выбора) Как тебя зовут незнакомец?"
                        );

                    return;
                }

                else

                {
                    userInfo.Step++;
                    await botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : "Я не бэлмэс тебяя, но сочту твой ответ за Да) Как тебя зовут, незнакомец?"
                        );

                    return;
                }
            }

            if (userInfo.Step == 2)
            {
                var name = e.Message.Text;
                userInfo.Human.Name = name;

                userInfo.Step++;

                await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : "Отлично, а какая у вас фамилия, ну или ник???"
                    );

                return;
            }

            if (userInfo.Step == 3)
            {
                var lastName = e.Message.Text;
                userInfo.Human.LastName = lastName;

                Service.Save(userInfo.Human);
                await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : "Отлично, у меня есть необходимые данные, чтобы внести вас в базу"
                    );

                userInfo.Step++;
            }

            if (userInfo.Step == 4)
            {
                userInfo.Step++;
                await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : "Пришлите мне вашу фотку"
                    );

                return;
            }

            if (userInfo.Step == 5)
            {
                if (e.Message.Photo != null)
                {
                    var photos          = e.Message.Photo;
                    var photo           = photos[photos.Length - 1];
                    var fileId          = photo.FileId;
                    var photoIdentifier = Guid.NewGuid();
                    using (var fileStream = System.IO.File.OpenWrite($"files\\{photoIdentifier}.jpg"))
                    {
                        var fileInfo = await botClient.GetInfoAndDownloadFileAsync(
                            fileId : fileId,
                            destination : fileStream
                            );
                    }

                    userInfo.Photo.Path       = $"files\\{photoIdentifier}.jpg";
                    userInfo.Photo.DateCreate = dateCurrent;

                    userInfo.Photo.UserId = 1;
                    PhotoService.Save(userInfo.Photo);
                }
                userInfo.Step++;
            }

            if (userInfo.Step == 6)
            {
                if (userInfo.Photo.Path == null)
                {
                    await botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : "Че блин????"
                        );

                    userInfo.Step = 4;
                }
                else
                {
                    var emotionGuy     = new StartEmotionsAPI();
                    var currentEmotion = await emotionGuy.Start(userInfo.Photo.Path);

                    var    maxEm = new MaxEmotionKek();
                    string g     = maxEm.Max(currentEmotion);

                    var ty   = new EmotionToString();
                    var type = ty.ToStringEm(g);

                    await botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : type
                        );

                    userInfo.Step++;
                }
            }

            if (userInfo.Step == 7)
            {
                userInfo.Step++;
                await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : "Что ты хочешь сделать дальше?",
                    replyMarkup : new ReplyKeyboardMarkup
                {
                    Keyboard = new[]
                    {
                        new []
                        {
                            new KeyboardButton("Хочу получить фото обратно"),
                            new KeyboardButton("Устал"),
                        },
                        new []
                        {
                            new KeyboardButton("Хочу отправить фото снова"),
                            new KeyboardButton("Хочу кофе")
                        },
                    }
                }
                    );

                return;
            }

            if (userInfo.Step == 8)
            {
                if (e.Message.Text == "Хочу получить фото обратно")
                {
                    await botClient.SendPhotoAsync(
                        chatId : e.Message.Chat,
                        File.OpenRead(userInfo.Photo.Path),

                        replyMarkup : new ReplyKeyboardRemove()
                        );
                }

                if (e.Message.Text == "Устал")
                {
                    await botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : "Иди поспи",
                        replyMarkup : new ReplyKeyboardRemove()
                        );
                }

                if (e.Message.Text == "Хочу отправить фото сново")
                {
                    await botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : "Ок, я готов",
                        replyMarkup : new ReplyKeyboardRemove()
                        );

                    userInfo.Step = 4;
                }

                if (e.Message.Text == "Хочу кофе")
                {
                    await botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : "Советую сходить в Coffe Bean,говорят там скидки)",
                        replyMarkup : new ReplyKeyboardRemove()
                        );
                }
                userInfo.Step++;
            }

            if (userInfo.Step == 9)
            {
                await botClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : $"Теперь я устал, если хочешь еще поболтать, напиши мне попозже"
                    );

                userInfo.Step = 4;
            }
        }
コード例 #15
0
        public override async Task Begin(ITurnContext turnContext)
        {
            var state = turnContext.GetConversationState <ImageHuntState>();

            if (state.Status != Status.Started)
            {
                LogInfo <ImageHuntState>(turnContext, "Attempt to record image before start!");
                await turnContext.ReplyActivity($"Vous ne pouvez m'envoyer de images qu'après le début de la chasse!");

                await turnContext.End();

                return;
            }

            if (state.GameId == 0 ||
                state.TeamId == 0)
            {
                LogInfo <ImageHuntState>(turnContext, "Game not initialized!");

                await turnContext.ReplyActivity(
                    $"La chasse n'a pas été correctement initalisée, veuillez demander de l'assistance à l'orga");

                await turnContext.End();

                return;
            }

            if (turnContext.Activity.Document == null)
            {
                LogInfo <ImageHuntState>(turnContext, "No document received!");

                await turnContext.ReplyActivity(
                    $"Aucun document ne m'est envoyé, veuillez recommencer");

                await turnContext.End();

                return;
            }

            var document = turnContext.Activity.Document;

            if (document.MimeType != "image/jpeg")
            {
                LogInfo <ImageHuntState>(turnContext, "Document is not image");

                await turnContext.ReplyActivity(
                    $"Vous ne m'avez pas envoyé une image, je ne peux accepter d'autres documents");

                await turnContext.End();

                return;
            }
            byte[] imageBytes = null;

            using (var stream = new MemoryStream())
            {
                await _telegramBotClient.GetInfoAndDownloadFileAsync(document.FileId, stream);

                if (stream.Length == 0)
                {
                    LogInfo <ImageHuntState>(turnContext, "Problem while downloading image from Telegram");

                    await turnContext.ReplyActivity(
                        $"Un problème est apparu dans l'image que vous m'avez envoyé.");

                    await turnContext.End();

                    return;
                }
                imageBytes = new byte[stream.Length];
                stream.Read(imageBytes, 0, (int)stream.Length);
                var uploadRequest = new UploadImageRequest()
                {
                    GameId    = state.GameId,
                    TeamId    = state.TeamId,
                    Latitude  = state.CurrentLatitude,
                    Longitude = state.CurrentLongitude,
                    ImageName = turnContext.Activity.Text
                };
                uploadRequest.FormFile = new FormFile(stream, 0, stream.Length, "formFile", document.FileName);
                await _teamWebService.UploadImage(uploadRequest);
            }

            await base.Begin(turnContext);

            var activity = new Activity()
            {
                ActivityType = ActivityType.Message,
                ChatId       = turnContext.ChatId,
                Text         = "Votre image a bien été téléchargée, un validateur l'examinera pour vous attribuer les points"
            };

            LogInfo <ImageHuntState>(turnContext, "Image uploaded");

            await turnContext.ReplyActivity(activity);

            await turnContext.End();
        }
コード例 #16
0
        static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            if (e.Message != null)
            {
                Telegram.Bot.Types.Message message = e.Message;
                Console.WriteLine($"Received a message from {message.Chat.FirstName} at {message.Date}. It says: \"{e.Message.Text}\"");

                switch (message.Text)
                {
                case "/stop":
                    step = -1;
                    break;

                case "/start":

                    await bot.SendTextMessageAsync(
                        chatId : message.Chat,
                        text : "Send link",
                        replyToMessageId : message.MessageId
                        );

                    step = 0;
                    break;

                default:
                    if (step == 0)
                    {
                        link = message.Text;

                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "Send title",
                            replyToMessageId : message.MessageId
                            );

                        step = 1;

                        try
                        {
                            string id = YoutubeClient.ParseVideoId(link);

                            MediaStreamInfoSet streamInfoSet = await clientYT.GetVideoMediaStreamInfosAsync(id);     //So54Khf7bB8

                            video = await clientYT.GetVideoAsync(id);

                            duration = video.Duration;     // 00:07:14
                            AudioStreamInfo streamInfo = streamInfoSet.Audio.OrderBy(s => s.Bitrate).First();
                            string          ext        = streamInfo.Container.GetFileExtension();

                            Console.WriteLine("Downloading audio");

                            await clientYT.DownloadMediaStreamAsync(streamInfo, $"Audio\\audio.{ext}");

                            Console.WriteLine("Audio has been downloaded. Converting audio");

                            FFMpegConverter convertAudio = new NReco.VideoConverter.FFMpegConverter();
                            convertAudio.ConvertMedia($"Audio\\audio.{ext}", null, "Audio\\audio.ogg", null, new ConvertSettings()
                            {
                                //CustomOutputArgs = $"-b:a {streamInfo.Bitrate}"
                                CustomOutputArgs = $"-c:a libopus -b:a {streamInfo.Bitrate}"
                            });

                            Console.WriteLine("Converting has been completed.");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                            await bot.SendTextMessageAsync(
                                chatId : message.Chat,
                                text : "The link that you have sent is not valid or the file size is too big. Please, send it again",
                                replyToMessageId : message.MessageId
                                );

                            step = 0;
                        }
                    }
                    else if (step == 1)
                    {
                        title    = message.Text.ToUpper();
                        titleLen = title.Length - 27;

                        output = $"<b>{message.Text}</b>\n";

                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "Send author",
                            replyToMessageId : message.MessageId
                            );

                        step = 2;
                    }
                    else if (step == 2)
                    {
                        author    = message.Text.ToUpper();
                        authorLen = author.Length - 14;

                        output += $"{message.Text}\n\n";

                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "Send desription",
                            replyToMessageId : message.MessageId
                            );

                        step = 3;
                    }
                    else if (step == 3)
                    {
                        output += $"{message.Text}\n\n";

                        ReplyKeyboardMarkup replyKeyboardMarkup = new[]
                        {
                            new[] { "Бизнес", "Биография", "Психология", "Саморазвитие" },
                            new[] { "Философия", "Наука", "История", "Финансы" }
                        };

                        replyKeyboardMarkup.OneTimeKeyboard = true;

                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "Send genre",
                            replyToMessageId : message.MessageId,
                            replyMarkup : replyKeyboardMarkup
                            );

                        output += $"🔈 <b>Продолжительность ≈</b> {Math.Round(duration.TotalMinutes, MidpointRounding.AwayFromZero)} минут\n";

                        step = 4;
                    }
                    else if (step == 4)
                    {
                        genre   = message.Text.ToUpper();
                        output += $"📝 <b>Жанр:</b> #{message.Text}";

                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "Send image",
                            replyToMessageId : message.MessageId
                            );

                        step = 5;
                    }
                    else if (step == 5)
                    {
                        if (message.Type == MessageType.Photo)
                        {
                            FileStream fs = System.IO.File.OpenWrite("Image\\cover.png");
                            await bot.GetInfoAndDownloadFileAsync(message.Photo.Last().FileId, fs);

                            fs.Close();

                            await bot.SendTextMessageAsync(
                                chatId : message.Chat,
                                text : "Cover image received",
                                replyToMessageId : message.MessageId
                                );

                            FileStream pltrFile = File.OpenRead("Image\\palitre.png");

                            await bot.SendPhotoAsync(
                                chatId : message.Chat,
                                photo : pltrFile,
                                caption : "Choose your colors. First, send me primary color",
                                replyMarkup : replyKeyboardMarkupColor
                                );

                            pltrFile.Close();
                            step = 6;
                        }
                        else
                        {
                            await bot.SendTextMessageAsync(message.Chat, "I implores you to send photo and not anything else, capish?");

                            step = 5;
                        }
                    }
                    else if (step == 6)
                    {
                        if (message.Text[0] == '#')
                        {
                            primColor = message.Text;
                        }
                        else
                        {
                            primColor = '#' + message.Text;
                        }
                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "I have got primary color. Now, send me secondary color"
                            );

                        step = 7;
                    }
                    else if (step == 7)
                    {
                        if (message.Text[0] == '#')
                        {
                            secColor = message.Text;
                        }
                        else
                        {
                            secColor = '#' + message.Text;
                        }

                        replyKeyboardMarkupColor.OneTimeKeyboard = true;
                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "I have got secondary color. Now, send me background color",
                            replyMarkup : replyKeyboardMarkupColor
                            );

                        step = 8;
                    }
                    else if (step == 8)
                    {
                        if (message.Text[0] == '#')
                        {
                            backColor = message.Text;
                        }
                        else
                        {
                            backColor = '#' + message.Text;
                        }



                        await bot.SendTextMessageAsync(
                            chatId : message.Chat,
                            text : "I have got background color. Now, I will send you a final post"
                            );

                        if (authorLen > 0)
                        {
                            authorFontSize -= authorLen * 8;
                        }
                        if (titleLen > 0)
                        {
                            titleFontSize -= titleLen * 5;
                        }

                        using (MagickImage form = new MagickImage(MagickColors.White, 1920, 1080))
                        {
                            new Drawables()

                            //Draw rectangle
                            .FillColor(new MagickColor(backColor))
                            .Rectangle(0, 0, 840, 1080)

                            //Draw hashtag
                            .FontPointSize(100)
                            .Font("Font\\nrwstr.otf")
                            .FillColor(new MagickColor(secColor))
                            .Text(30, 124, "#")

                            //Draw genre
                            .Font("Font\\amcap.ttf")
                            .Text(124, 124, genre)

                            //Draw title
                            .FontPointSize(titleFontSize)
                            .FillColor(new MagickColor(primColor))
                            .Text(30, 520, title)

                            //Draw name of the author
                            .FontPointSize(authorFontSize)
                            .FillColor(new MagickColor(secColor))
                            .Text(30, 650, author)

                            //Draw name of the channel
                            .FillColor(new MagickColor(primColor))
                            .FontPointSize(50)
                            .Text(150, 960, "THINK! - АУДИОПОДКАСТЫ")

                            //Draw link of the channel
                            .Font("Font\\nrwstr.otf")
                            .FillColor(new MagickColor(secColor))
                            .FontPointSize(40)
                            .Text(150, 1010, "T.ME/THINKAUDIO")

                            .Draw(form);

                            using MagickImage cover = new MagickImage("Image\\cover.png");
                            cover.Resize(1280, 1280);
                            form.Composite(cover, 840, 0, CompositeOperator.Over);

                            //Draw logo of the channel
                            using MagickImage logo = new MagickImage("Image\\logo.png");
                            logo.Alpha(AlphaOption.Set);
                            logo.ColorFuzz = new Percentage(0);
                            logo.Settings.BackgroundColor = MagickColors.Transparent;
                            //logo.Settings.FillColor = MagickColors.White;
                            logo.Opaque(MagickColors.White, new MagickColor(primColor));
                            form.Composite(logo, 30, 920, CompositeOperator.Over);

                            form.Write("Image\\template.png");
                        }

                        await bot.SendTextMessageAsync(message.Chat, "Template has been created. Sending it to you");

                        using (var stream = new FileStream("Image\\template.png", FileMode.Open))
                        {
                            InputOnlineFile inputOnlineFile = new InputOnlineFile(stream, "template.png");
                            await bot.SendDocumentAsync(message.Chat, inputOnlineFile);
                        }


                        try
                        {
                            ImgurClient   client   = new ImgurClient("", "");
                            ImageEndpoint endpoint = new ImageEndpoint(client);
                            IImage        image;
                            using (FileStream fs = new FileStream("Image\\template.png", FileMode.Open))
                            {
                                await bot.SendTextMessageAsync(message.Chat, "Uploading Image to Imgur");

                                image = await endpoint.UploadImageStreamAsync(fs);
                            }
                            picLink = image.Link;
                            Console.WriteLine("Image uploaded. Image Url: " + image.Link);

                            output += $"<a href=\"{picLink}\">&#8205;</a>";

                            await bot.SendTextMessageAsync(
                                chatId : message.Chat,
                                text : output,
                                parseMode : ParseMode.Html
                                );
                        }
                        catch (ImgurException imgurEx)
                        {
                            Debug.Write("An error occurred uploading an image to Imgur.");
                            Debug.Write(imgurEx.Message);
                        }

                        using (var stream = new FileStream("Audio\\audio.ogg", FileMode.Open))
                        {
                            await bot.SendVoiceAsync(
                                chatId : message.Chat,
                                voice : stream

                                );
                        }
                        step = -1;
                    }
                    break;
                }
            }
        }
コード例 #17
0
        public override async Task Begin(ITurnContext turnContext)
        {
            var state = turnContext.GetConversationState <ImageHuntState>();

            if (state.Status != Status.Started)
            {
                LogInfo <ImageHuntState>(turnContext, "Attempt to record image before start!");
                await turnContext.ReplyActivity($"Vous ne pouvez m'envoyer de images qu'après le début de la chasse!");

                await turnContext.End();

                return;
            }
            if (state.GameId == 0 ||
                state.TeamId == 0 ||
                state.CurrentLatitude == 0.0 ||
                state.CurrentLongitude == 0.0)
            {
                LogInfo <ImageHuntState>(turnContext, "Game not initialized!");
                var errorMessage = $"La chasse n'a pas été correctement initalisée ou je ne sais pas où vous êtes, veuillez demander de l'assistance à l'orga";
                await turnContext.ReplyActivity(errorMessage);

                _logger.LogWarning(errorMessage);
                await turnContext.End();

                return;
            }
            byte[] imageBytes   = null;
            var    photoSizes   = turnContext.Activity.Pictures;
            var    biggestPhoto = photoSizes.OrderByDescending(p => p.FileSize).First();

            using (Stream stream = new MemoryStream())
            {
                var fileInfo = await _telegramBotClient.GetInfoAndDownloadFileAsync(biggestPhoto.FileId, stream);

                imageBytes = new byte[stream.Length];
                stream.Read(imageBytes, 0, (int)stream.Length);


                var uploadRequest = new UploadImageRequest()
                {
                    GameId    = state.GameId,
                    TeamId    = state.TeamId,
                    Latitude  = state.CurrentLatitude,
                    Longitude = state.CurrentLongitude,
                    ImageName = turnContext.Activity.Text
                };
                uploadRequest.FormFile = new FormFile(stream, 0, stream.Length, "formFile", "image.jpg");
                await _teamWebService.UploadImage(uploadRequest);

                _logger.LogInformation($"Image {turnContext.Activity.Pictures.First().FileId} had been uploaded");
            }

            await base.Begin(turnContext);

            var activity = new Activity()
            {
                ActivityType = ActivityType.Message, ChatId = turnContext.ChatId, Text = "Votre image a bien été téléchargée, un validateur l'examinera pour vous attribuer les points"
            };

            LogInfo <ImageHuntState>(turnContext, "Image uploaded");

            await turnContext.ReplyActivity(activity);

            await turnContext.End();
        }