This repository represents dotnet wrapper for Yandex Messenger Bot API. The repository contains two libraries:
- Yandex.Messenger.Bot.Sdk - contains number of objects and abstractions that covers all API methods.
- Yandex.Messenger.Bot.AspNetCore - contains numbers of extension methods for integrating SDK into an ASP.NET Core applications using webhooks.
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.
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);
}
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!