Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ on:
description: "Version to release, e.g. 0.7.0-alpha. Tag v<version> is created on the selected commit."
required: true
type: string
latest:
description: "Mark the GitHub release as Latest. Uncheck to publish it as a pre-release instead."
required: false
default: true
type: boolean

permissions:
contents: write
Expand Down Expand Up @@ -193,7 +198,9 @@ jobs:
target_commitish: ${{ github.sha }}
name: MaxMessenger.Bot ${{ steps.version.outputs.tag }}
body_path: ${{ runner.temp }}/release-notes.md
prerelease: ${{ contains(steps.version.outputs.value, '-') }}
# * Alpha versions are the project's regular releases, so they are published as Latest too.
prerelease: ${{ github.event_name == 'workflow_dispatch' && !inputs.latest }}
make_latest: ${{ github.event_name != 'workflow_dispatch' || inputs.latest }}
files: |
./nupkgs/*.nupkg
./nupkgs/*.snupkg
51 changes: 50 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,54 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [0.8.0-alpha] - 2026-10-30

Модели приведены к [OpenAPI-схеме MAX Bot API](https://github.com/max-messenger/max-bot-api-client-go/blob/main/schema.yaml): строковые и `object`-поля стали типизированными, а nullability совпадает с документацией — меньше ручного разбора и null-проверок. Спасибо @diquoks за отзыв!

### Breaking Changes

- **Typed enums instead of strings**: `LinkedMessage.Type` — `MessageLinkType?` (было `string`), `MessageRecipient.ChatType` — `ChatType?` (было `string`), `MarkupElement.Type` — новый enum `MarkupType?`. Неизвестное библиотеке значение превращается в `null`, а не роняет разбор апдейта.
- **Typed inline keyboard**: `InlineKeyboardAttachment.Payload` — `InlineKeyboard` с `InlineKeyboardButton[][] Buttons` (было `Dictionary<string, object>` с `JsonElement` внутри); добавлен шорткат `InlineKeyboardAttachment.Buttons`.
- **Typed dictionaries and objects**: `Chat.Participants` — `Dictionary<long, long>?` (user id → время последней активности), `Image.Photos` — `Dictionary<string, PhotoSizeToken>?` (было `object`), `Video.Urls` — `VideoUrls` с `Mp4P1080`…`Mp4P144`, `Hls` и `BestMp4` (было `Dictionary<string, string>`), `UpdateChatRequest.Icon` — `ImageAttachmentRequestPayload?` (было `object`).
- **Unknown attachments**: вложение неизвестного библиотеке типа разбирается в `UnknownAttachment` с исходным JSON в `RawJson`, а не в пустой `DocumentAttachment`.
- **Required fields are non-nullable** (по схеме они всегда приходят):
- `Message.Recipient` (`new()` по умолчанию), `Message.Timestamp` — `long`; `MessageBody.Mid` — `string`, `MessageBody.Seq` — `long`; `LinkedMessage.Message` — `MessageBody`, `LinkedMessage.Mid`/`Seq` — `string`/`long`; `MessageStat.Views` — `int`.
- `User.FirstName` — `string`, `User.LastActivityTime` — `long`; то же для `ChatMember` плюс `LastAccessTime`, `JoinTime` — `long`.
- `Chat.LastEventTime` — `long`, `Chat.ParticipantsCount` — `int`; `Image.Url` — `string`; `Subscription.Time` — `long`.
- `CallbackQuery.CallbackId` — `string`, `CallbackQuery.User` — `User`, `CallbackQuery.Timestamp` — `long`.
- `Update.Timestamp` и `Timestamp` всех типизированных обёрток — `long`. В обёртках обязательные поля тоже не nullable: `ChatId` (`long`), `User`, `IsChannel` (`bool`), `MessageRemovedUpdate.MessageId`/`UserId`, `ChatTitleChangedUpdate.Title`, `DialogMutedUpdate.MutedUntil`, `MessageChatCreatedUpdate.Chat`/`MessageId`.
- Вложения: `Url`/`Token` у фото, видео, аудио и файлов — `string`; `DocumentAttachment.FileName` — `string`, `FileSize` — `long`; у стикера `Url`/`Code` — `string`, `Width`/`Height` — `int`. `Video` (`GET /videos/{token}`): `Token` — `string`, `Width`/`Height`/`Duration` — `int`.
- Массивы в ответах (`GetMessagesResponse.Messages`, `ChatMembersResponse.Members`, `SubscriptionsResponse.Subscriptions`, `GetUpdatesResponse.Updates`) по умолчанию пустые, а не `null`.
- Явный `null` от API в этих полях не роняет разбор: он превращается в `0`, `""` или пустой объект.
- Осознанно остаются nullable: `Message.Body` (MAX присылает `null` для сообщений только с пересылкой), `Message.Sender`/`LinkedMessage.Sender` (сообщения от имени канала) и enum'ы с мягким разбором — `Chat.Status`, `LinkedMessage.Type`, `MessageRecipient.ChatType`, `MarkupElement.Type` (`null` для неизвестного значения).
- **IChatsApi**: `AddChatMembersAsync` возвращает `ModifyMembersResponse` (наследник `Response`); новые члены интерфейса `GetChatMembersByIdsAsync` и `RemoveChatMemberAsync(chatId, userId, block)` — собственные реализации нужно дополнить.
- **Enum members** больше не помечены `[JsonPropertyName]` — `System.Text.Json` его для enum'ов игнорирует; значение API описано в XML-доке.

### Added

- **Reply keyboard**: `ReplyKeyboardAttachment` во входящих сообщениях и `AttachmentRequest.ReplyKeyboard(buttons, direct, directUserId)` с кнопками `ReplyKeyboardButton.Message/GeoLocation/Contact` для отправки.
- **Typed update wrappers are JSON-mapped**: `BotStartedUpdate`, `MessageRemovedUpdate` и остальные обёртки можно десериализовать прямо из JSON события. `BotAddedUpdate.InviterId` заполняется из `user` (MAX присылает пригласившего там), `DialogMutedUpdate`/`DialogUnmutedUpdate.IsMuted` — из типа события.
- **Partial chat flag**: `Update.IsChatInferred`/`IsChatIdInferred` стали публичными — `Update.Chat` для сообщений собирается из `message.recipient` и содержит только `ChatId` и `Type`.
- **Schema fields**: `User.IsOfficial` (`is_official`), `SetWebhookRequest.Version`/`SelfSignedCert`, `Subscription.SelfSignedCert`; `AttachmentTypeNames` стал публичным.
- **Chat button**: `ButtonType.Chat` и поля `InlineKeyboardButton.ChatTitle`, `ChatDescription`, `StartPayload`, `Uuid` (кнопка `chat`, создающая чат).
- **Data attachment**: `DataAttachment` (`type: "data"`) с payload нажатой кнопки reply-клавиатуры — раньше разбирался как пустой `DocumentAttachment`.
- **Add members result**: `ModifyMembersResponse.FailedUserIds` и `FailedUserDetails` (`error_code`, `user_ids`) — кого не удалось добавить и почему.
- **Chat members**: `GetChatMembersByIdsAsync(chatId, userIds)` (`user_ids`) и `RemoveChatMemberAsync(chatId, userId, block)` (`block=true` блокирует участника).
- **`JsonSnakeCaseEnumConverter<TEnum>`** — snake_case-конвертер, которым помечены все enum'ы библиотеки.

### Fixed

- **Enum deserialization without library options**: `MessageLinkType`, `ChatAction`, `UploadType`, `ChatAdminPermission`, `UpdateType` и другие enum'ы не разбирались обычным `JsonSerializer` — например, `JsonSerializer.SerializeToElement("reply").Deserialize<MessageLinkType>()` падал с `JsonException`. Теперь у каждого enum'а есть `[JsonConverter]`, и модели разбираются одинаково с `MaxJsonSerializer.Options` и с опциями по умолчанию. Если в ваших `JsonSerializerOptions` зарегистрирован свой `JsonStringEnumConverter`, он имеет приоритет над атрибутом типа — для данных MAX используйте `MaxJsonSerializer.Options`.
- **Unknown update types**: `UpdateTypeJsonConverter` в `MaxJsonSerializer.Options` перекрывался общим enum-конвертером, поэтому новый тип события (например, `comment_created`) в `GET /subscriptions` ронял весь ответ. Теперь он превращается в `UpdateType.Unknown`.
- **Inline keyboard parsing**: кнопка с `"payload": null` больше не получает строку `"null"`; поля кнопки неожиданного типа и битый `payload` клавиатуры не роняют разбор всего сообщения.
- **Validation limits**: `InlineKeyboardButton.Text` — до 128 символов, `InlineKeyboardButton.Payload` и `CallbackQuery.Payload` — до 1024 (было 64, по схеме MAX).
- **Docs**: исправлены описания `BotAddedUpdate.User`/`BotRemovedUpdate.User` (это пригласивший/удаливший пользователь, а не бот), `Update.Message`, `Update.Title`; у `UpdateId` указано, что MAX не присылает `update_id`.
- **UpdateTypeHelper.FromString** принимает и PascalCase (`"MessageCreated"`).

### Changed

- **Releases**: GitHub Release создаётся как Latest (не pre-release), даже для `-alpha` версий; при ручном запуске это можно отключить параметром `latest`.

## [0.7.1-alpha] - 2026-10-27

### Fixed
Expand Down Expand Up @@ -389,7 +437,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

---

[Unreleased]: https://github.com/NanoAgents/MaxBotNet/compare/v0.7.1-alpha...HEAD
[Unreleased]: https://github.com/NanoAgents/MaxBotNet/compare/v0.8.0-alpha...HEAD
[0.8.0-alpha]: https://github.com/NanoAgents/MaxBotNet/compare/v0.7.1-alpha...v0.8.0-alpha
[0.7.1-alpha]: https://github.com/NanoAgents/MaxBotNet/compare/v0.7.0-alpha...v0.7.1-alpha
[0.7.0-alpha]: https://github.com/NanoAgents/MaxBotNet/compare/v0.6.3-alpha...v0.7.0-alpha
[0.6.3-alpha]: https://github.com/NanoAgents/MaxBotNet/compare/v0.6.2-alpha...v0.6.3-alpha
Expand Down
36 changes: 33 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ var upload = await client.Files.UploadAsync(UploadType.File, stream, "report.pdf
await client.Messages.SendMessageWithAttachmentAsync(AttachmentRequest.FromUpload(UploadType.File, upload), chatId: chatId);
```

Также доступны `AttachmentRequest.Image(token)`, `Video`, `Audio`, `File`, `Sticker`, `Contact`, `Location`, `Share` и `Keyboard`.
Также доступны `AttachmentRequest.Image(token)`, `Video`, `Audio`, `File`, `Sticker`, `Contact`, `Location`, `Share`, `Keyboard` и `ReplyKeyboard`
(кнопки `ReplyKeyboardButton.Message`, `GeoLocation`, `Contact` вместо клавиатуры пользователя; payload нажатой кнопки приходит как `DataAttachment`).
Если MAX ещё обрабатывает только что загруженный файл, API отвечает `attachment.not.ready`: `SendMessageAsync(SendMessageRequest)`,
`SendMessageWithAttachment(s)Async` и `EditMessageAsync` с вложениями повторяют запрос автоматически, а при исчерпании попыток выбрасывается `MaxAttachmentNotReadyException`.

Expand All @@ -79,10 +80,39 @@ await client.Messages.SendMessageWithAttachmentAsync(AttachmentRequest.FromUploa
```csharp
var callback = update.Callback!;
await client.Messages.AnswerCallbackQueryAsync(
callback.CallbackId!,
callback.CallbackId,
new AnswerCallbackQueryRequest { Notification = "Принято!" });
```

## 🧾 Типизированные модели

Модели повторяют [OpenAPI-схему MAX Bot API](https://github.com/max-messenger/max-bot-api-client-go/blob/main/schema.yaml):
обязательные поля не nullable (`Message.Recipient`, `Message.Timestamp`, `MessageBody.Mid`, `CallbackQuery.CallbackId`, `User.FirstName`, …),
а строковые значения API разобраны в enum'ы. Nullable остаются только поля, которые MAX действительно может не прислать:
`Message.Body` (сообщение только с пересылкой), `Message.Sender` (пост от имени канала), необязательные поля схемы.

```csharp
var message = update.Message!;
if (message.Link?.Type == MessageLinkType.Reply) // "forward" | "reply"
{
Console.WriteLine($"Ответ на {message.Link.Mid}");
}

var chatType = message.Recipient.ChatType; // ChatType.Dialog | Chat | Channel
var mentions = message.Body?.Markup?.Where(m => m.Type == MarkupType.UserMention);

foreach (var keyboard in message.Body?.Attachments?.OfType<InlineKeyboardAttachment>() ?? [])
{
var buttons = keyboard.Buttons; // InlineKeyboardButton[][] вместо словаря
}
```

Все enum'ы помечены конвертером snake_case, поэтому модели и enum'ы разбираются и обычным `JsonSerializer` с опциями
по умолчанию: `JsonSerializer.Deserialize<MessageLinkType>("\"reply\"")` вернёт `MessageLinkType.Reply`. Свой
`JsonStringEnumConverter` в `JsonSerializerOptions` имеет приоритет над атрибутом типа — для данных MAX берите `MaxJsonSerializer.Options`.
Если MAX пришлёт значение, неизвестное текущей версии библиотеки, nullable-поля вроде `LinkedMessage.Type` и
`MessageRecipient.ChatType` станут `null`, а не уронят разбор всего апдейта.

## 🌐 Webhook

Библиотека больше не добавляет эндпоинт в приложение автоматически. Подключите его явно:
Expand Down Expand Up @@ -117,7 +147,7 @@ await app.Services.GetRequiredService<MaxClient>().ConfigureWebhookAsync();
## 🧪 Тесты и качество

- `dotnet build -warnaserror` — проверяет, что все публичные API имеют XML-доки.
- `dotnet test` — 690+ модульных тестов, включая регрессионные тесты по issue и проверки сериализации на реальных ответах MAX API.
- `dotnet test` — 760+ модульных тестов, включая регрессионные тесты по issue и проверки сериализации на реальных ответах MAX API.
- GitHub Actions workflow `.github/workflows/ci.yml` (Ubuntu + Windows) гоняет форматирование, `dotnet format analyzers`, покрытие (минимум 60 % линий, целимся в 85 %) и `dotnet pack`, загружая артефакты для ревью.
- Smoke-тесты для примеров используют `LoopbackSampleRuntime` и проходят весь `SampleRegistry`, повторяя подход Telegram.Bot и VkNet к офлайн-интеграциям, чтобы код примеров и документация не расходились.
- Фикстуры API (`tests/Max.Bot.Tests/Integration/Fixtures`) помогают детерминированно воспроизводить ответы `/subscriptions` и `/updates` без реального HTTP.
Expand Down
1 change: 1 addition & 0 deletions RELEASING.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ Tag format must stay `vX.Y.Z` or `vX.Y.Z-alpha`, because `.github/workflows/rele
- Tag push (or a manual `workflow_dispatch` run with `version`) triggers `.github/workflows/release.yml`.
- Workflow steps: restore → format → analyzers → build → tests → validate version/changelog → `dotnet pack` → upload artifacts → `dotnet nuget push` → GitHub Release.
- Release notes are extracted from the matching `CHANGELOG.md` section.
- The GitHub Release is published as **Latest** (not a pre-release), including `-alpha` versions — they are the project's regular releases. For a manual run, uncheck the `latest` input to publish a pre-release instead.
- NuGet publishing requires the `NUGET_API_KEY` secret.
- GitHub Release creation requires workflow `contents: write` permission.
- Monitor the run in GitHub Actions. The run must be green before announcing the release.
Expand Down
2 changes: 1 addition & 1 deletion examples/Max.Bot.Examples/Samples/KeyboardBotSample.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ private static async Task HandleCallbackAsync(SampleExecutionContext sampleConte
Notification = responseText
};

await context.Api.Messages.AnswerCallbackQueryAsync(callback.CallbackId ?? string.Empty, request, cancellationToken).ConfigureAwait(false);
await context.Api.Messages.AnswerCallbackQueryAsync(callback.CallbackId, request, cancellationToken).ConfigureAwait(false);
sampleContext.Output.WriteLine($"Callback '{callback.Payload}' processed.");
}
}
Expand Down
Loading
Loading