/yandex-messenger-bot-dotnet

Yandex Messenger Bot .NET SDK

Primary LanguageC#MIT LicenseMIT

Yandex Messenger Bot dotnet SDK

License: MIT

GitHub Workflow Status

Nuget (with prereleases) Nuget

Nuget (with prereleases) Nuget

This repository represents dotnet wrapper for Yandex Messenger Bot API. The repository contains two libraries:


Usage

Pre requirements

Create a new bot and generate a new access token in the admin console. Also for ASP.NET applications you can setup a webhook url.

Console applications

Install package: dotnet add package Yandex.Messenger.Bot.Sdk

Create the bot client using generated access token:

var yandexBotClient = new YandexMessengerBotClient("<TOKEN>");

Subscribe on all messages:

yandexBotClient.Updates.Subscribe(async (update, cancel) =>
{
    await yandexBotClient.Chats.SendMessage(new SendMessageRequest
    {
        Text = $"{update.From.Login} you sent: \"{update.Text}\"",
        ChatId = update.Chat.Id
    }, cancel);
});

Or subscribe on concrete messages:

yandexBotClient.Updates.Subscribe("/help", async (update, token) =>
{
    await yandexBotClient.Chats.SendMessage(new SendMessageRequest()
    {
        Text = $"Hi, {update.From.Login}! I'm EchoBot, I'll repeat all your messages!", 
        ChatId = update.Chat.Id
    }, token);
})

Poll updates from chats:

while (true)
{
    await yandexBotClient.Updates.GetUpdates(new GetUpdateRequest());
    await Task.Delay(3000);
}

ASP.NET Core applications

Install package: dotnet add package Yandex.Messenger.Bot.AspNetCore

Add configuration to your application:

{
  "YandexMessengerBot": {
    "Token": "<TOKEN>",
    "WebhookEndpoint": "/hook"
  }
}

Setup a container:

builder.Services.AddYandexMessengerBotSdk(builder.Configuration);

Subscribe on messages:

builder.Services.AddYandexMessengerObserver(async (provider, update, cancellationToken) =>
{
    var logger = provider.GetService<ILogger<Program>>();
    logger!.LogInformation(
        "User {login} sent message: {msg}.",
        update.From.Login,
        update.Text);

    var chats = provider.GetService<IChats>();
    await chats!.SendMessage(new SendMessageRequest
    {
        Text = $"{update.From.Login} you sent: \"{update.Text}\"",
        ChatId = update.Chat.Id
    }, cancellationToken);
});

Insert webhook handler into a middleware pipeline:

app.UseYandexMessengerWebhook();

Look for the full examples!