Skip to content

Instantly share code, notes, and snippets.

@MeinLiX
Created January 20, 2022 15:02
Show Gist options
  • Save MeinLiX/45af0d1b36e454adbc95b327f6b3cb52 to your computer and use it in GitHub Desktop.
Save MeinLiX/45af0d1b36e454adbc95b327f6b3cb52 to your computer and use it in GitHub Desktop.
Speech to Text (GCP) Telegram Bot
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();
@MeinLiX
Copy link
Author

MeinLiX commented Jan 20, 2022

Nuget:

- dotenv.net
- Google.Cloud.Speech.V1
- Telegram.Bot
- Telegram.Bot.Extensions.Polling

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment