Created
January 20, 2022 15:02
-
-
Save MeinLiX/45af0d1b36e454adbc95b327f6b3cb52 to your computer and use it in GitHub Desktop.
Speech to Text (GCP) Telegram Bot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Google.Cloud.Speech.V1; | |
using Telegram.Bot; | |
using static Google.Cloud.Speech.V1.RecognitionConfig.Types; | |
dotenv.net.DotEnv.Load(); | |
string TELEGRAM_BOT_TOKEN = Environment.GetEnvironmentVariable("TELEGRAM_BOT_TOKEN") ?? throw new NullReferenceException("TELEGRAM_BOT_TOKEN"); | |
string GOOGLE_APPLICATION_CREDENTIALS = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? throw new NullReferenceException("GOOGLE_APPLICATION_CREDENTIALS"); | |
string GOOGLE_APPLICATION_PROJECT_ID = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_PROJECT_ID") ?? throw new NullReferenceException("GOOGLE_APPLICATION_PROJECT_ID"); | |
string GetTestFromSpeech(string FilePath) | |
{ | |
RecognitionConfig config = new() | |
{ | |
Encoding = AudioEncoding.WebmOpus, | |
SampleRateHertz = 16000, | |
LanguageCode = LanguageCodes.Ukrainian.Ukraine | |
}; | |
return SpeechClient.Create().Recognize(config, RecognitionAudio.FetchFromUri($"https://api.telegram.org/file/bot{TELEGRAM_BOT_TOKEN}/{FilePath}")).Results[0].Alternatives[0].Transcript; | |
} | |
new TelegramBotClient(TELEGRAM_BOT_TOKEN).StartReceiving(new Telegram.Bot.Extensions.Polling.DefaultUpdateHandler(HandleUpdateAsync, HandleErrorAsync)); | |
async Task HandleErrorAsync(ITelegramBotClient bc, Exception err, CancellationToken ct) => Console.WriteLine(err.Message); | |
async Task HandleUpdateAsync(ITelegramBotClient botClient, Telegram.Bot.Types.Update update, CancellationToken canccellationToken) | |
{ | |
if (update.Type != Telegram.Bot.Types.Enums.UpdateType.Message && update?.Message?.Type != Telegram.Bot.Types.Enums.MessageType.Audio && update?.Message?.Voice is null) return; | |
Telegram.Bot.Types.File file = await botClient.GetFileAsync(update?.Message?.Voice?.FileId, canccellationToken); | |
await botClient.SendTextMessageAsync(update.Message.Chat.Id, text: GetTestFromSpeech(file.FilePath)); | |
} | |
Console.ReadKey(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nuget: