From 0d993119bf686043d7f5e65ba54a197472851ec2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 14:01:26 +0000 Subject: [PATCH 1/3] feat!: typed models aligned with MAX OpenAPI schema (v0.8.0-alpha) - Every enum carries a snake_case JsonConverter, so models and enums deserialize with any JsonSerializerOptions (MessageLinkType failed with default options). - LinkedMessage.Type, MessageRecipient.ChatType, MarkupElement.Type are enums; InlineKeyboardAttachment.Payload is a typed InlineKeyboard; Chat.Participants and Image.Photos are typed dictionaries. - Required schema fields are non-nullable (Message, MessageBody, User, Chat, ChatMember, CallbackQuery, typed update wrappers, attachments, Video). - Add chat buttons, DataAttachment, ModifyMembersResponse, GetChatMembersByIdsAsync and RemoveChatMemberAsync(block). - Release workflow publishes the GitHub release as Latest. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013pSNnawFkxH4NpFXTzqjCT --- .github/workflows/release.yml | 9 +- CHANGELOG.md | 39 +++ README.md | 31 +- RELEASING.md | 1 + .../Samples/KeyboardBotSample.cs | 2 +- src/Max.Bot/Api/ChatsApi.cs | 44 ++- src/Max.Bot/Api/IChatsApi.cs | 35 +- src/Max.Bot/Max.Bot.csproj | 2 +- src/Max.Bot/Types/Attachment.cs | 56 +++- src/Max.Bot/Types/CallbackQuery.cs | 10 +- src/Max.Bot/Types/CallbackQueryUpdate.cs | 2 +- src/Max.Bot/Types/Chat.cs | 12 +- src/Max.Bot/Types/ChatMember.cs | 8 +- src/Max.Bot/Types/ChatMembersResponse.cs | 2 +- .../Converters/AttachmentJsonConverter.cs | 32 +- .../Converters/CallbackQueryJsonConverter.cs | 27 +- .../InlineKeyboardButtonJsonConverter.cs | 49 ++- .../Converters/JsonSnakeCaseEnumConverter.cs | 28 ++ .../Types/Converters/UpdateJsonConverter.cs | 9 +- src/Max.Bot/Types/Enums/ButtonIntent.cs | 4 +- src/Max.Bot/Types/Enums/ButtonType.cs | 20 +- src/Max.Bot/Types/Enums/ChatAction.cs | 15 +- .../Types/Enums/ChatAdminPermission.cs | 7 +- src/Max.Bot/Types/Enums/ChatStatus.cs | 4 +- src/Max.Bot/Types/Enums/ChatType.cs | 6 +- src/Max.Bot/Types/Enums/MarkupType.cs | 61 ++++ src/Max.Bot/Types/Enums/MessageLinkType.cs | 7 +- src/Max.Bot/Types/Enums/TextFormat.cs | 9 +- src/Max.Bot/Types/Enums/UpdateType.cs | 2 + src/Max.Bot/Types/Enums/UploadType.cs | 16 +- src/Max.Bot/Types/GetMessagesResponse.cs | 2 +- src/Max.Bot/Types/GetUpdatesResponse.cs | 2 +- src/Max.Bot/Types/Helpers/UpdateTypeHelper.cs | 4 +- src/Max.Bot/Types/Image.cs | 7 +- src/Max.Bot/Types/InlineKeyboardButton.cs | 32 +- src/Max.Bot/Types/Message.cs | 38 ++- src/Max.Bot/Types/MessageRecipient.cs | 13 +- src/Max.Bot/Types/MessageUpdate.cs | 2 +- src/Max.Bot/Types/ModifyMembersResponse.cs | 40 +++ src/Max.Bot/Types/Subscription.cs | 4 +- src/Max.Bot/Types/SubscriptionsResponse.cs | 2 +- src/Max.Bot/Types/Update.cs | 91 ++--- src/Max.Bot/Types/UpdateTypes.cs | 96 +++--- src/Max.Bot/Types/UploadResponse.cs | 2 +- src/Max.Bot/Types/User.cs | 6 +- src/Max.Bot/Types/Video.cs | 22 +- .../Max.Bot.Tests/Examples/SampleBotsTests.cs | 2 +- tests/Max.Bot.Tests/Unit/Api/ChatsApiTests.cs | 74 +++- .../Unit/Api/MessagesApiTests.cs | 22 +- .../Regression/ModelDeserializationTests.cs | 316 ++++++++++++++++++ .../Unit/Types/CallbackQueryTests.cs | 2 +- .../Unit/Types/MessageRecipientTests.cs | 15 +- .../Max.Bot.Tests/Unit/Types/MessageTests.cs | 16 +- tests/Max.Bot.Tests/Unit/Types/UserTests.cs | 2 +- tests/Max.Bot.Tests/Unit/Types/VideoTests.cs | 6 +- 55 files changed, 1058 insertions(+), 309 deletions(-) create mode 100644 src/Max.Bot/Types/Converters/JsonSnakeCaseEnumConverter.cs create mode 100644 src/Max.Bot/Types/Enums/MarkupType.cs create mode 100644 src/Max.Bot/Types/ModifyMembersResponse.cs create mode 100644 tests/Max.Bot.Tests/Unit/Regression/ModelDeserializationTests.cs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9eb5157..cf0f047 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -14,6 +14,11 @@ on: description: "Version to release, e.g. 0.7.0-alpha. Tag v 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 @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 5544849..3375960 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,45 @@ 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` с `JsonElement` внутри); добавлен шорткат `InlineKeyboardAttachment.Buttons`. +- **Typed dictionaries**: `Chat.Participants` — `Dictionary?` (user id → время последней активности), `Image.Photos` — `Dictionary?` (было `object`). +- **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`. +- **IChatsApi**: `AddChatMembersAsync` возвращает `ModifyMembersResponse` (наследник `Response`); новые члены интерфейса `GetChatMembersByIdsAsync` и `RemoveChatMemberAsync(chatId, userId, block)` — собственные реализации нужно дополнить. +- **Enum members** больше не помечены `[JsonPropertyName]` — `System.Text.Json` его для enum'ов игнорирует; значение API описано в XML-доке. + +### Added + +- **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`** — snake_case-конвертер, которым помечены все enum'ы библиотеки. + +### Fixed + +- **Enum deserialization without library options**: `MessageLinkType`, `ChatAction`, `UploadType`, `ChatAdminPermission`, `UpdateType` и другие enum'ы не разбирались обычным `JsonSerializer` — например, `JsonSerializer.SerializeToElement("reply").Deserialize()` падал с `JsonException`. Теперь у каждого enum'а есть `[JsonConverter]`, и модели разбираются одинаково с любыми `JsonSerializerOptions`. +- **Inline keyboard parsing**: кнопка с `"payload": null` больше не получает строку `"null"`; поля кнопки неожиданного типа и битый `payload` клавиатуры не роняют разбор всего сообщения. +- **Validation limits**: `InlineKeyboardButton.Text` — до 128 символов, `Payload` — до 1024 (было 64, по схеме MAX). +- **UpdateTypeHelper.FromString** принимает и PascalCase (`"MessageCreated"`). + +### Changed + +- **Releases**: GitHub Release создаётся как Latest (не pre-release), даже для `-alpha` версий; при ручном запуске это можно отключить параметром `latest`. + ## [0.7.1-alpha] - 2026-10-27 ### Fixed diff --git a/README.md b/README.md index 261dbb5..4e7632d 100644 --- a/README.md +++ b/README.md @@ -79,10 +79,37 @@ 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'ы. + +```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() ?? []) +{ + var buttons = keyboard.Buttons; // InlineKeyboardButton[][] вместо словаря +} +``` + +Все enum'ы помечены конвертером snake_case, поэтому модели и enum'ы разбираются и обычным `JsonSerializer` без +`MaxJsonSerializer.Options`: `JsonSerializer.Deserialize("\"reply\"")` вернёт `MessageLinkType.Reply`. +Если MAX пришлёт значение, неизвестное текущей версии библиотеки, nullable-поля вроде `LinkedMessage.Type` и +`MessageRecipient.ChatType` станут `null`, а не уронят разбор всего апдейта. + ## 🌐 Webhook Библиотека больше не добавляет эндпоинт в приложение автоматически. Подключите его явно: @@ -117,7 +144,7 @@ await app.Services.GetRequiredService().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. diff --git a/RELEASING.md b/RELEASING.md index 28ade2c..55f0543 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -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. diff --git a/examples/Max.Bot.Examples/Samples/KeyboardBotSample.cs b/examples/Max.Bot.Examples/Samples/KeyboardBotSample.cs index cfe66b1..e03915e 100644 --- a/examples/Max.Bot.Examples/Samples/KeyboardBotSample.cs +++ b/examples/Max.Bot.Examples/Samples/KeyboardBotSample.cs @@ -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."); } } diff --git a/src/Max.Bot/Api/ChatsApi.cs b/src/Max.Bot/Api/ChatsApi.cs index 9c4a485..ed4c3e0 100644 --- a/src/Max.Bot/Api/ChatsApi.cs +++ b/src/Max.Bot/Api/ChatsApi.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Globalization; +using System.Linq; using System.Net.Http; using System.Text.Json; using Max.Bot.Configuration; @@ -226,16 +227,48 @@ public async Task GetChatMembersPageAsync(long chatId, long } /// - public async Task AddChatMembersAsync(long chatId, AddChatMembersRequest request, CancellationToken cancellationToken = default) + public async Task GetChatMembersByIdsAsync(long chatId, IEnumerable userIds, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(userIds); + + var ids = userIds.Distinct().Select(id => id.ToString(CultureInfo.InvariantCulture)).ToArray(); + if (ids.Length == 0) + { + throw new ArgumentException("At least one user ID must be provided.", nameof(userIds)); + } + + var queryParams = new Dictionary + { + { "user_ids", string.Join(",", ids) } + }; + + var request = CreateRequest(HttpMethod.Get, string.Create(CultureInfo.InvariantCulture, $"/chats/{chatId}/members"), null, queryParams); + var response = await ExecuteRequestAsync(request, cancellationToken).ConfigureAwait(false); + return response.Members ?? []; + } + + /// + public async Task AddChatMembersAsync(long chatId, AddChatMembersRequest request, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(request); var apiRequest = CreateRequest(HttpMethod.Post, string.Create(CultureInfo.InvariantCulture, $"/chats/{chatId}/members"), request); - return await ExecuteRequestAsync(apiRequest, cancellationToken).ConfigureAwait(false); + return await ExecuteRequestAsync(apiRequest, cancellationToken).ConfigureAwait(false); + } + + /// + public Task RemoveChatMemberAsync(long chatId, long userId, CancellationToken cancellationToken = default) + { + return RemoveChatMemberCoreAsync(chatId, userId, null, cancellationToken); } /// - public async Task RemoveChatMemberAsync(long chatId, long userId, CancellationToken cancellationToken = default) + public Task RemoveChatMemberAsync(long chatId, long userId, bool block, CancellationToken cancellationToken = default) + { + return RemoveChatMemberCoreAsync(chatId, userId, block, cancellationToken); + } + + private async Task RemoveChatMemberCoreAsync(long chatId, long userId, bool? block, CancellationToken cancellationToken) { ValidateUserIdStrict(userId); @@ -244,6 +277,11 @@ public async Task RemoveChatMemberAsync(long chatId, long userId, Canc { "user_id", userId.ToString(CultureInfo.InvariantCulture) } }; + if (block == true) + { + queryParams["block"] = "true"; + } + var request = CreateRequest(HttpMethod.Delete, string.Create(CultureInfo.InvariantCulture, $"/chats/{chatId}/members"), null, queryParams); return await ExecuteRequestAsync(request, cancellationToken).ConfigureAwait(false); } diff --git a/src/Max.Bot/Api/IChatsApi.cs b/src/Max.Bot/Api/IChatsApi.cs index 87578a5..a80ed09 100644 --- a/src/Max.Bot/Api/IChatsApi.cs +++ b/src/Max.Bot/Api/IChatsApi.cs @@ -224,19 +224,36 @@ public interface IChatsApi /// Thrown when authentication fails. Task GetChatMembersPageAsync(long chatId, long? marker = null, int? count = null, CancellationToken cancellationToken = default); + /// + /// Gets the membership of the specified users in a chat (GET /chats/{chatId}/members?user_ids=...). + /// + /// The unique identifier of the chat. + /// Identifiers of the users to look up. Users that are not members are absent from the result. + /// A cancellation token to cancel the operation. + /// A task that represents the asynchronous operation. The task result contains the found members. + /// Thrown when userIds is null. + /// Thrown when userIds is empty. + /// Thrown when the API returns an error response. + /// Thrown when a network error occurs. + /// Thrown when authentication fails. + Task GetChatMembersByIdsAsync(long chatId, IEnumerable userIds, CancellationToken cancellationToken = default); + /// /// Adds members to a chat. /// /// The unique identifier of the chat. /// The request containing the user IDs to add. /// A cancellation token to cancel the operation. - /// A task that represents the asynchronous operation. The task result contains the response with success status. + /// + /// A task that represents the asynchronous operation. The task result contains the success status and + /// the users that could not be added (, ). + /// /// Thrown when chatId is less than or equal to zero. /// Thrown when request is null. /// Thrown when the API returns an error response. /// Thrown when a network error occurs. /// Thrown when authentication fails. - Task AddChatMembersAsync(long chatId, AddChatMembersRequest request, CancellationToken cancellationToken = default); + Task AddChatMembersAsync(long chatId, AddChatMembersRequest request, CancellationToken cancellationToken = default); /// /// Removes a member from a chat. @@ -250,5 +267,19 @@ public interface IChatsApi /// Thrown when a network error occurs. /// Thrown when authentication fails. Task RemoveChatMemberAsync(long chatId, long userId, CancellationToken cancellationToken = default); + + /// + /// Removes a member from a chat and optionally blocks them (DELETE /chats/{chatId}/members?user_id=...&block=...). + /// + /// The unique identifier of the chat. + /// The unique identifier of the user to remove. + /// true to block the user in the chat. Applies only to chats with a public or private link. + /// A cancellation token to cancel the operation. + /// A task that represents the asynchronous operation. The task result contains the response with success status. + /// Thrown when userId is less than or equal to zero. + /// Thrown when the API returns an error response. + /// Thrown when a network error occurs. + /// Thrown when authentication fails. + Task RemoveChatMemberAsync(long chatId, long userId, bool block, CancellationToken cancellationToken = default); } diff --git a/src/Max.Bot/Max.Bot.csproj b/src/Max.Bot/Max.Bot.csproj index 899205b..aa9d9ae 100644 --- a/src/Max.Bot/Max.Bot.csproj +++ b/src/Max.Bot/Max.Bot.csproj @@ -5,7 +5,7 @@ enable MaxMessenger.Bot - 0.7.1-alpha + 0.8.0-alpha MaxBotNet Contributors C# library for Max Messenger Bot API (.NET 10, .NET 9, .NET 8) Apache-2.0 diff --git a/src/Max.Bot/Types/Attachment.cs b/src/Max.Bot/Types/Attachment.cs index 69fd60b..365d75d 100644 --- a/src/Max.Bot/Types/Attachment.cs +++ b/src/Max.Bot/Types/Attachment.cs @@ -59,14 +59,14 @@ public class PhotoAttachment : Attachment /// Gets or sets the URL of the photo. /// [JsonPropertyName("url")] - public string? Url { get; set; } + public string Url { get; set; } = string.Empty; /// /// Gets or sets the attachment token. Use it to send the same media again /// (for example with ). /// [JsonPropertyName("token")] - public string? Token { get; set; } + public string Token { get; set; } = string.Empty; /// /// Initializes a new instance of the class. @@ -127,14 +127,14 @@ public class VideoAttachment : Attachment /// Gets or sets the URL of the video. /// [JsonPropertyName("url")] - public string? Url { get; set; } + public string Url { get; set; } = string.Empty; /// /// Gets or sets the attachment token. Use it to send the same media again /// (for example with ). /// [JsonPropertyName("token")] - public string? Token { get; set; } + public string Token { get; set; } = string.Empty; /// /// Gets or sets the video thumbnail. @@ -189,14 +189,14 @@ public class AudioAttachment : Attachment /// Gets or sets the URL of the audio file. /// [JsonPropertyName("url")] - public string? Url { get; set; } + public string Url { get; set; } = string.Empty; /// /// Gets or sets the attachment token. Use it to send the same media again /// (for example with ). /// [JsonPropertyName("token")] - public string? Token { get; set; } + public string Token { get; set; } = string.Empty; /// /// Gets or sets the audio transcription, if MAX provides it. @@ -233,13 +233,13 @@ public class DocumentAttachment : Attachment /// Gets or sets the name of the document file (filename in MAX API). /// [JsonPropertyName("file_name")] - public string? FileName { get; set; } + public string FileName { get; set; } = string.Empty; /// /// Gets or sets the size of the document file in bytes. /// [JsonPropertyName("file_size")] - public long? FileSize { get; set; } + public long FileSize { get; set; } /// /// Gets or sets the MIME type of the document. @@ -251,14 +251,14 @@ public class DocumentAttachment : Attachment /// Gets or sets the URL of the document. /// [JsonPropertyName("url")] - public string? Url { get; set; } + public string Url { get; set; } = string.Empty; /// /// Gets or sets the attachment token. Use it to send the same media again /// (for example with ). /// [JsonPropertyName("token")] - public string? Token { get; set; } + public string Token { get; set; } = string.Empty; /// /// Initializes a new instance of the class. @@ -346,10 +346,16 @@ public class InlineKeyboardAttachment : Attachment public string? CallbackId { get; set; } /// - /// Gets or sets the payload containing the keyboard buttons. + /// Gets or sets the keyboard sent with the message (payload.buttons). /// [JsonPropertyName("payload")] - public Dictionary? Payload { get; set; } + public InlineKeyboard Payload { get; set; } = new(); + + /// + /// Gets the keyboard buttons (payload.buttons). Shortcut for .. + /// + [JsonIgnore] + public InlineKeyboardButton[][] Buttons => Payload?.Buttons ?? Array.Empty(); /// /// Initializes a new instance of the class. @@ -366,25 +372,25 @@ public class StickerAttachment : Attachment /// Gets or sets the sticker image URL. /// [JsonPropertyName("url")] - public string? Url { get; set; } + public string Url { get; set; } = string.Empty; /// /// Gets or sets the sticker code. Use it with to send the same sticker. /// [JsonPropertyName("code")] - public string? Code { get; set; } + public string Code { get; set; } = string.Empty; /// /// Gets or sets the sticker width in pixels. /// [JsonPropertyName("width")] - public int? Width { get; set; } + public int Width { get; set; } /// /// Gets or sets the sticker height in pixels. /// [JsonPropertyName("height")] - public int? Height { get; set; } + public int Height { get; set; } /// /// Initializes a new instance of the class. @@ -433,6 +439,23 @@ public class ShareAttachment : Attachment public ShareAttachment() => Type = AttachmentTypeNames.Share; } +/// +/// Represents a data attachment (data) that MAX adds to a message sent by a message button of a reply keyboard. +/// +public class DataAttachment : Attachment +{ + /// + /// Gets or sets the payload of the pressed button. + /// + [JsonPropertyName("data")] + public string Data { get; set; } = string.Empty; + + /// + /// Initializes a new instance of the class. + /// + public DataAttachment() => Type = AttachmentTypeNames.Data; +} + internal static class AttachmentTypeNames { public const string Image = "image"; @@ -444,4 +467,5 @@ internal static class AttachmentTypeNames public const string Contact = "contact"; public const string Sticker = "sticker"; public const string Share = "share"; + public const string Data = "data"; } diff --git a/src/Max.Bot/Types/CallbackQuery.cs b/src/Max.Bot/Types/CallbackQuery.cs index 3eea1c1..84adc33 100644 --- a/src/Max.Bot/Types/CallbackQuery.cs +++ b/src/Max.Bot/Types/CallbackQuery.cs @@ -14,10 +14,10 @@ public class CallbackQuery /// Gets or sets the callback ID (current keyboard ID). /// This property maps to "callback_id" field from API. /// - /// The callback ID, or null if not available. + /// The callback ID. Always sent by MAX API; pass it to AnswerCallbackQueryAsync. [StringLength(512, ErrorMessage = "Callback ID must not exceed 512 characters.")] [JsonIgnore] - public string? CallbackId { get; set; } + public string CallbackId { get; set; } = string.Empty; /// /// Gets or sets the user who pressed the button. @@ -26,7 +26,7 @@ public class CallbackQuery /// The user who pressed the button. [Required(ErrorMessage = "User is required.")] [JsonIgnore] - public User? User { get; set; } + public User User { get; set; } = new(); /// /// Gets or sets the message with the inline button that was pressed. @@ -48,9 +48,9 @@ public class CallbackQuery /// /// Gets or sets the timestamp when the user pressed the button (Unix timestamp in milliseconds). /// - /// The timestamp when the button was pressed, or null if not available. + /// The timestamp when the button was pressed. [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] [JsonIgnore] - public long? Timestamp { get; set; } + public long Timestamp { get; set; } } diff --git a/src/Max.Bot/Types/CallbackQueryUpdate.cs b/src/Max.Bot/Types/CallbackQueryUpdate.cs index acafdc9..130ef23 100644 --- a/src/Max.Bot/Types/CallbackQueryUpdate.cs +++ b/src/Max.Bot/Types/CallbackQueryUpdate.cs @@ -19,7 +19,7 @@ public class CallbackQueryUpdate /// /// The timestamp when the update was created. [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] - public long? Timestamp { get; set; } + public long Timestamp { get; set; } /// /// Gets or sets the user locale for this update. diff --git a/src/Max.Bot/Types/Chat.cs b/src/Max.Bot/Types/Chat.cs index 9bac338..39d2687 100644 --- a/src/Max.Bot/Types/Chat.cs +++ b/src/Max.Bot/Types/Chat.cs @@ -57,15 +57,15 @@ public class Chat /// [Range(0, long.MaxValue, ErrorMessage = "LastEventTime cannot be negative.")] [JsonPropertyName("last_event_time")] - public long? LastEventTime { get; set; } + public long LastEventTime { get; set; } /// /// Gets or sets the number of participants in the chat. /// Always 2 for dialogs. /// - [Range(1, int.MaxValue, ErrorMessage = "ParticipantsCount must be greater than zero.")] + [Range(0, int.MaxValue, ErrorMessage = "ParticipantsCount cannot be negative.")] [JsonPropertyName("participants_count")] - public int? ParticipantsCount { get; set; } + public int ParticipantsCount { get; set; } /// /// Gets or sets the ID of the chat owner. @@ -75,11 +75,11 @@ public class Chat public long? OwnerId { get; set; } /// - /// Gets or sets the participants of the chat with their last activity time. - /// Can be null when requesting a list of chats. + /// Gets or sets the participants of the chat: user ID → time of the last activity (Unix timestamp in milliseconds). + /// Visible to chat admins only; can be null when requesting a list of chats. /// [JsonPropertyName("participants")] - public object? Participants { get; set; } + public Dictionary? Participants { get; set; } /// /// Gets or sets a value indicating whether the chat is public. diff --git a/src/Max.Bot/Types/ChatMember.cs b/src/Max.Bot/Types/ChatMember.cs index 06f5e4f..84dfe15 100644 --- a/src/Max.Bot/Types/ChatMember.cs +++ b/src/Max.Bot/Types/ChatMember.cs @@ -38,7 +38,7 @@ public class ChatMember /// Gets or sets the user's first name. /// [JsonPropertyName("first_name")] - public string? FirstName { get; set; } + public string FirstName { get; set; } = string.Empty; /// /// Gets or sets the user's last name. @@ -56,7 +56,7 @@ public class ChatMember /// Gets or sets the user's last activity time (Unix timestamp in milliseconds). /// [JsonPropertyName("last_activity_time")] - public long? LastActivityTime { get; set; } + public long LastActivityTime { get; set; } /// /// Gets or sets the user's description. @@ -68,7 +68,7 @@ public class ChatMember /// Gets or sets the user's last access time in this chat. /// [JsonPropertyName("last_access_time")] - public long? LastAccessTime { get; set; } + public long LastAccessTime { get; set; } /// /// Gets or sets a value indicating whether the user is the owner of the chat. @@ -86,7 +86,7 @@ public class ChatMember /// Gets or sets the time when the user joined the chat (Unix timestamp in seconds). /// [JsonPropertyName("join_time")] - public long? JoinTime { get; set; } + public long JoinTime { get; set; } /// /// Gets or sets the URL of the user's avatar. diff --git a/src/Max.Bot/Types/ChatMembersResponse.cs b/src/Max.Bot/Types/ChatMembersResponse.cs index 800a6b3..ab39a08 100644 --- a/src/Max.Bot/Types/ChatMembersResponse.cs +++ b/src/Max.Bot/Types/ChatMembersResponse.cs @@ -11,7 +11,7 @@ public class ChatMembersResponse /// Gets or sets the chat members. /// [JsonPropertyName("members")] - public ChatMember[] Members { get; set; } = default!; + public ChatMember[] Members { get; set; } = Array.Empty(); /// /// Gets or sets the marker for the next page. diff --git a/src/Max.Bot/Types/Converters/AttachmentJsonConverter.cs b/src/Max.Bot/Types/Converters/AttachmentJsonConverter.cs index b151aa8..b97a357 100644 --- a/src/Max.Bot/Types/Converters/AttachmentJsonConverter.cs +++ b/src/Max.Bot/Types/Converters/AttachmentJsonConverter.cs @@ -39,7 +39,7 @@ public class AttachmentJsonConverter : JsonConverter // Route by type name — primary and most reliable method if (IsType(typeString, AttachmentTypeNames.InlineKeyboard)) { - return JsonSerializer.Deserialize(root.GetRawText(), options); + return DeserializeInlineKeyboard(root, options); } if (IsType(typeString, AttachmentTypeNames.Image)) @@ -82,6 +82,11 @@ public class AttachmentJsonConverter : JsonConverter return DeserializeMerged(root, typeString, null, options); } + if (IsType(typeString, AttachmentTypeNames.Data)) + { + return DeserializeMerged(root, typeString, null, options); + } + // Fallback for unknown types — use DocumentAttachment as it has the most generic fields (url, token) return DeserializeMerged(root, typeString, null, options); } @@ -118,11 +123,36 @@ public override void Write(Utf8JsonWriter writer, Attachment value, JsonSerializ case ShareAttachment shareAttachment: JsonSerializer.Serialize(writer, shareAttachment, options); break; + case DataAttachment dataAttachment: + JsonSerializer.Serialize(writer, dataAttachment, options); + break; default: throw new JsonException($"Unknown attachment type: {value.GetType()}"); } } + /// + /// Inline keyboard keeps its buttons nested in payload, so it is deserialized as is (without merging). + /// A malformed keyboard yields an empty instead of breaking the whole message. + /// + private static InlineKeyboardAttachment DeserializeInlineKeyboard(JsonElement root, JsonSerializerOptions options) + { + InlineKeyboardAttachment? attachment; + try + { + attachment = root.Deserialize(options); + } + catch (Exception ex) when (ex is JsonException or InvalidOperationException or FormatException) + { + attachment = null; + } + + attachment ??= new InlineKeyboardAttachment(); + attachment.Payload ??= new InlineKeyboard(); + attachment.Type = AttachmentTypeNames.InlineKeyboard; + return attachment; + } + /// /// MAX API splits attachment data between the payload object (url, token, photo_id, vcf_info, ...) /// and the attachment root (filename, size, width, height, duration, thumbnail, ...). diff --git a/src/Max.Bot/Types/Converters/CallbackQueryJsonConverter.cs b/src/Max.Bot/Types/Converters/CallbackQueryJsonConverter.cs index e1be155..2ee3d3c 100644 --- a/src/Max.Bot/Types/Converters/CallbackQueryJsonConverter.cs +++ b/src/Max.Bot/Types/Converters/CallbackQueryJsonConverter.cs @@ -28,19 +28,19 @@ public override CallbackQuery Read(ref Utf8JsonReader reader, Type typeToConvert var callbackQuery = new CallbackQuery(); // Read callback_id (API format) - if (root.TryGetProperty("callback_id", out var callbackIdElement)) + if (root.TryGetProperty("callback_id", out var callbackIdElement) && callbackIdElement.ValueKind == JsonValueKind.String) { - callbackQuery.CallbackId = callbackIdElement.GetString(); + callbackQuery.CallbackId = callbackIdElement.GetString() ?? string.Empty; } // Read user (API format) - if (root.TryGetProperty("user", out var userElement)) + if (root.TryGetProperty("user", out var userElement) && userElement.ValueKind == JsonValueKind.Object) { - callbackQuery.User = JsonSerializer.Deserialize(userElement.GetRawText(), options); + callbackQuery.User = userElement.Deserialize(options) ?? new User(); } // Read payload (API format) - if (root.TryGetProperty("payload", out var payloadElement)) + if (root.TryGetProperty("payload", out var payloadElement) && payloadElement.ValueKind != JsonValueKind.Null) { callbackQuery.Payload = payloadElement.ValueKind == JsonValueKind.String ? payloadElement.GetString() @@ -48,9 +48,11 @@ public override CallbackQuery Read(ref Utf8JsonReader reader, Type typeToConvert } // Read timestamp - if (root.TryGetProperty("timestamp", out var timestampElement)) + if (root.TryGetProperty("timestamp", out var timestampElement) && + timestampElement.ValueKind == JsonValueKind.Number && + timestampElement.TryGetInt64(out var timestamp)) { - callbackQuery.Timestamp = timestampElement.GetInt64(); + callbackQuery.Timestamp = timestamp; } return callbackQuery; @@ -62,10 +64,7 @@ public override void Write(Utf8JsonWriter writer, CallbackQuery value, JsonSeria writer.WriteStartObject(); // Write callback_id (API format) - if (value.CallbackId != null) - { - writer.WriteString("callback_id", value.CallbackId); - } + writer.WriteString("callback_id", value.CallbackId ?? string.Empty); // Write user (API format) if (value.User != null) @@ -80,11 +79,7 @@ public override void Write(Utf8JsonWriter writer, CallbackQuery value, JsonSeria writer.WriteString("payload", value.Payload); } - // Write timestamp if present - if (value.Timestamp.HasValue) - { - writer.WriteNumber("timestamp", value.Timestamp.Value); - } + writer.WriteNumber("timestamp", value.Timestamp); writer.WriteEndObject(); } diff --git a/src/Max.Bot/Types/Converters/InlineKeyboardButtonJsonConverter.cs b/src/Max.Bot/Types/Converters/InlineKeyboardButtonJsonConverter.cs index 9b62675..6750414 100644 --- a/src/Max.Bot/Types/Converters/InlineKeyboardButtonJsonConverter.cs +++ b/src/Max.Bot/Types/Converters/InlineKeyboardButtonJsonConverter.cs @@ -30,10 +30,7 @@ public override InlineKeyboardButton Read(ref Utf8JsonReader reader, Type typeTo var button = new InlineKeyboardButton(); // Read text (required) - if (root.TryGetProperty("text", out var textElement)) - { - button.Text = textElement.GetString() ?? string.Empty; - } + button.Text = GetString(root, "text") ?? string.Empty; // Read type (new format) if (root.TryGetProperty("type", out var typeElement) && typeElement.ValueKind == JsonValueKind.String) @@ -46,7 +43,7 @@ public override InlineKeyboardButton Read(ref Utf8JsonReader reader, Type typeTo } // Read payload (new format) - if (root.TryGetProperty("payload", out var payloadElement)) + if (root.TryGetProperty("payload", out var payloadElement) && payloadElement.ValueKind != JsonValueKind.Null) { button.Payload = payloadElement.ValueKind == JsonValueKind.String ? payloadElement.GetString() @@ -54,9 +51,9 @@ public override InlineKeyboardButton Read(ref Utf8JsonReader reader, Type typeTo } // Read url (for link buttons) - if (root.TryGetProperty("url", out var urlElement)) + if (GetString(root, "url") is { } url) { - button.Url = urlElement.GetString(); + button.Url = url; if (button.Type == default(ButtonType) && !string.IsNullOrEmpty(button.Url)) { button.Type = ButtonType.Link; @@ -64,9 +61,8 @@ public override InlineKeyboardButton Read(ref Utf8JsonReader reader, Type typeTo } // Handle legacy callback_data format (for backward compatibility) - if (root.TryGetProperty("callback_data", out var callbackDataElement)) + if (GetString(root, "callback_data") is { } callbackData) { - var callbackData = callbackDataElement.GetString(); if (!string.IsNullOrEmpty(callbackData)) { button.Type = ButtonType.Callback; @@ -89,6 +85,14 @@ public override InlineKeyboardButton Read(ref Utf8JsonReader reader, Type typeTo button.Quick = quickElement.GetBoolean(); } + button.ChatTitle = GetString(root, "chat_title"); + button.ChatDescription = GetString(root, "chat_description"); + button.StartPayload = GetString(root, "start_payload"); + if (root.TryGetProperty("uuid", out var uuidElement) && uuidElement.ValueKind == JsonValueKind.Number && uuidElement.TryGetInt64(out var uuid)) + { + button.Uuid = uuid; + } + // Read intent (for callback buttons) if (root.TryGetProperty("intent", out var intentElement) && intentElement.ValueKind == JsonValueKind.String) { @@ -150,6 +154,26 @@ public override void Write(Utf8JsonWriter writer, InlineKeyboardButton value, Js writer.WriteBoolean("quick", value.Quick.Value); } + if (value.ChatTitle != null) + { + writer.WriteString("chat_title", value.ChatTitle); + } + + if (value.ChatDescription != null) + { + writer.WriteString("chat_description", value.ChatDescription); + } + + if (value.StartPayload != null) + { + writer.WriteString("start_payload", value.StartPayload); + } + + if (value.Uuid.HasValue) + { + writer.WriteNumber("uuid", value.Uuid.Value); + } + // Write intent (for callback buttons) if (value.Intent.HasValue) { @@ -160,6 +184,13 @@ public override void Write(Utf8JsonWriter writer, InlineKeyboardButton value, Js writer.WriteEndObject(); } + private static string? GetString(JsonElement root, string propertyName) + { + return root.TryGetProperty(propertyName, out var element) && element.ValueKind == JsonValueKind.String + ? element.GetString() + : null; + } + private static bool TryParseButtonIntent(string? value, out ButtonIntent intent) { intent = default; diff --git a/src/Max.Bot/Types/Converters/JsonSnakeCaseEnumConverter.cs b/src/Max.Bot/Types/Converters/JsonSnakeCaseEnumConverter.cs new file mode 100644 index 0000000..fe5ac52 --- /dev/null +++ b/src/Max.Bot/Types/Converters/JsonSnakeCaseEnumConverter.cs @@ -0,0 +1,28 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Max.Bot.Types.Converters; + +/// +/// Serializes an enum as the snake_case string used by MAX Bot API (for example, TypingOn → "typing_on") +/// and reads both snake_case and PascalCase names case-insensitively. +/// +/// +/// Every enum of the library is marked with this converter, so enum values are (de)serialized correctly with any +/// — including JsonSerializer.Deserialize<MessageLinkType>("\"reply\"") +/// with default options — and not only with . +/// An unknown string value throws ; library response models use +/// where MAX may add new values. +/// +/// The enum type. +public sealed class JsonSnakeCaseEnumConverter : JsonStringEnumConverter + where TEnum : struct, Enum +{ + /// + /// Initializes a new instance of the class. + /// + public JsonSnakeCaseEnumConverter() + : base(JsonNamingPolicy.SnakeCaseLower) + { + } +} diff --git a/src/Max.Bot/Types/Converters/UpdateJsonConverter.cs b/src/Max.Bot/Types/Converters/UpdateJsonConverter.cs index c1d9660..e59968c 100644 --- a/src/Max.Bot/Types/Converters/UpdateJsonConverter.cs +++ b/src/Max.Bot/Types/Converters/UpdateJsonConverter.cs @@ -38,7 +38,7 @@ public override Update Read(ref Utf8JsonReader reader, Type typeToConvert, JsonS update.UpdateTypeRaw = updateTypeElement.GetString(); } - update.Timestamp = GetInt64(root, "timestamp"); + update.Timestamp = GetInt64(root, "timestamp") ?? 0; update.UserLocale = GetString(root, "user_locale"); @@ -130,7 +130,7 @@ private static void InferChatFromMessage(Update update) var inferredChatId = update.ChatId == null ? recipientChatId : (long?)null; Chat? inferredChat = null; - if (update.Chat == null && Update.TryParseChatType(recipient.ChatType, out var chatType)) + if (update.Chat == null && recipient.ChatType is { } chatType) { inferredChat = new Chat { @@ -184,10 +184,7 @@ public override void Write(Utf8JsonWriter writer, Update value, JsonSerializerOp writer.WriteString("update_type", value.UpdateTypeRaw); } - if (value.Timestamp.HasValue) - { - writer.WriteNumber("timestamp", value.Timestamp.Value); - } + writer.WriteNumber("timestamp", value.Timestamp); if (value.UserLocale != null) { diff --git a/src/Max.Bot/Types/Enums/ButtonIntent.cs b/src/Max.Bot/Types/Enums/ButtonIntent.cs index ffd26df..c193f10 100644 --- a/src/Max.Bot/Types/Enums/ButtonIntent.cs +++ b/src/Max.Bot/Types/Enums/ButtonIntent.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using Max.Bot.Types.Converters; namespace Max.Bot.Types.Enums; @@ -6,7 +7,7 @@ namespace Max.Bot.Types.Enums; /// Represents the intent/style of a callback button. /// Affects how the button is displayed by the client. /// -[JsonConverter(typeof(JsonStringEnumConverter))] +[JsonConverter(typeof(JsonSnakeCaseEnumConverter))] public enum ButtonIntent { /// @@ -24,4 +25,3 @@ public enum ButtonIntent /// Negative } - diff --git a/src/Max.Bot/Types/Enums/ButtonType.cs b/src/Max.Bot/Types/Enums/ButtonType.cs index 0d293df..8f728f9 100644 --- a/src/Max.Bot/Types/Enums/ButtonType.cs +++ b/src/Max.Bot/Types/Enums/ButtonType.cs @@ -1,11 +1,12 @@ using System.Text.Json.Serialization; +using Max.Bot.Types.Converters; namespace Max.Bot.Types.Enums; /// /// Represents the type of an inline keyboard button. /// -[JsonConverter(typeof(JsonStringEnumConverter))] +[JsonConverter(typeof(JsonSnakeCaseEnumConverter))] public enum ButtonType { /// @@ -42,13 +43,12 @@ public enum ButtonType /// /// Clipboard button - copies to the user's clipboard. /// - Clipboard -} - - - - - - - + Clipboard, + /// + /// Chat button (chat) - creates a new chat with the bot as administrator when the first user presses it. + /// Configured by , , + /// and . + /// + Chat +} diff --git a/src/Max.Bot/Types/Enums/ChatAction.cs b/src/Max.Bot/Types/Enums/ChatAction.cs index 4281e1c..c18a544 100644 --- a/src/Max.Bot/Types/Enums/ChatAction.cs +++ b/src/Max.Bot/Types/Enums/ChatAction.cs @@ -1,46 +1,47 @@ using System.Text.Json.Serialization; +using Max.Bot.Types.Converters; namespace Max.Bot.Types.Enums; /// /// Represents actions that can be sent by the bot in a chat. /// +[JsonConverter(typeof(JsonSnakeCaseEnumConverter))] public enum ChatAction { /// /// Bot is typing a message. + /// Serialized as "typing_on". /// - [JsonPropertyName("typing_on")] TypingOn, /// /// Bot is sending a photo. + /// Serialized as "sending_photo". /// - [JsonPropertyName("sending_photo")] SendingPhoto, /// /// Bot is sending a video. + /// Serialized as "sending_video". /// - [JsonPropertyName("sending_video")] SendingVideo, /// /// Bot is sending an audio file. + /// Serialized as "sending_audio". /// - [JsonPropertyName("sending_audio")] SendingAudio, /// /// Bot is sending a file. + /// Serialized as "sending_file". /// - [JsonPropertyName("sending_file")] SendingFile, /// /// Bot marks messages as seen. + /// Serialized as "mark_seen". /// - [JsonPropertyName("mark_seen")] MarkSeen } - diff --git a/src/Max.Bot/Types/Enums/ChatAdminPermission.cs b/src/Max.Bot/Types/Enums/ChatAdminPermission.cs index dcdc57c..42dda39 100644 --- a/src/Max.Bot/Types/Enums/ChatAdminPermission.cs +++ b/src/Max.Bot/Types/Enums/ChatAdminPermission.cs @@ -1,10 +1,13 @@ +using System.Text.Json.Serialization; +using Max.Bot.Types.Converters; + namespace Max.Bot.Types.Enums; /// /// Represents chat admin permissions returned by the MAX API. -/// Serialized as snake_case by -/// (global JsonStringEnumConverter with SnakeCaseLower policy). +/// Serialized as snake_case (). /// +[JsonConverter(typeof(JsonSnakeCaseEnumConverter))] public enum ChatAdminPermission { /// diff --git a/src/Max.Bot/Types/Enums/ChatStatus.cs b/src/Max.Bot/Types/Enums/ChatStatus.cs index 836e932..56f7be7 100644 --- a/src/Max.Bot/Types/Enums/ChatStatus.cs +++ b/src/Max.Bot/Types/Enums/ChatStatus.cs @@ -1,11 +1,12 @@ using System.Text.Json.Serialization; +using Max.Bot.Types.Converters; namespace Max.Bot.Types.Enums; /// /// Represents the status of a chat. /// -[JsonConverter(typeof(JsonStringEnumConverter))] +[JsonConverter(typeof(JsonSnakeCaseEnumConverter))] public enum ChatStatus { /// @@ -33,4 +34,3 @@ public enum ChatStatus /// Suspended } - diff --git a/src/Max.Bot/Types/Enums/ChatType.cs b/src/Max.Bot/Types/Enums/ChatType.cs index 284e46d..9dfedc5 100644 --- a/src/Max.Bot/Types/Enums/ChatType.cs +++ b/src/Max.Bot/Types/Enums/ChatType.cs @@ -4,6 +4,7 @@ // 💡 Usage: Used by Chat and other chat-related payloads. using System.Text.Json.Serialization; +using Max.Bot.Types.Converters; namespace Max.Bot.Types.Enums; @@ -11,24 +12,21 @@ namespace Max.Bot.Types.Enums; /// Represents the type of a chat. /// Maps to the official Max API chat type values. /// -[JsonConverter(typeof(JsonStringEnumConverter))] +[JsonConverter(typeof(JsonSnakeCaseEnumConverter))] public enum ChatType { /// /// Group chat (type: "chat"). /// - [JsonPropertyName("chat")] Chat, /// /// Private dialog with a user (type: "dialog"). /// - [JsonPropertyName("dialog")] Dialog, /// /// Channel (type: "channel"). /// - [JsonPropertyName("channel")] Channel, } diff --git a/src/Max.Bot/Types/Enums/MarkupType.cs b/src/Max.Bot/Types/Enums/MarkupType.cs new file mode 100644 index 0000000..6891f0e --- /dev/null +++ b/src/Max.Bot/Types/Enums/MarkupType.cs @@ -0,0 +1,61 @@ +using System.Text.Json.Serialization; +using Max.Bot.Types.Converters; + +namespace Max.Bot.Types.Enums; + +/// +/// Represents the type of a text markup element (). +/// +[JsonConverter(typeof(JsonSnakeCaseEnumConverter))] +public enum MarkupType +{ + /// + /// Bold text. Serialized as "strong". + /// + Strong, + + /// + /// Italic text. Serialized as "emphasized". + /// + Emphasized, + + /// + /// Monospaced text or code block. Serialized as "monospaced". + /// + Monospaced, + + /// + /// Link (). Serialized as "link". + /// + Link, + + /// + /// Strikethrough text. Serialized as "strikethrough". + /// + Strikethrough, + + /// + /// Underlined text. Serialized as "underline". + /// + Underline, + + /// + /// User mention ( or ). Serialized as "user_mention". + /// + UserMention, + + /// + /// Heading. Serialized as "heading". + /// + Heading, + + /// + /// Highlighted text. Serialized as "highlighted". + /// + Highlighted, + + /// + /// Quote block. Serialized as "quote". + /// + Quote +} diff --git a/src/Max.Bot/Types/Enums/MessageLinkType.cs b/src/Max.Bot/Types/Enums/MessageLinkType.cs index 02f45ea..52417be 100644 --- a/src/Max.Bot/Types/Enums/MessageLinkType.cs +++ b/src/Max.Bot/Types/Enums/MessageLinkType.cs @@ -1,22 +1,23 @@ using System.Text.Json.Serialization; +using Max.Bot.Types.Converters; namespace Max.Bot.Types.Enums; /// /// Specifies the type of message link. /// +[JsonConverter(typeof(JsonSnakeCaseEnumConverter))] public enum MessageLinkType { /// /// Forward message link type. + /// Serialized as "forward". /// - [JsonPropertyName("forward")] Forward, /// /// Reply message link type. + /// Serialized as "reply". /// - [JsonPropertyName("reply")] Reply } - diff --git a/src/Max.Bot/Types/Enums/TextFormat.cs b/src/Max.Bot/Types/Enums/TextFormat.cs index f8caaca..07000a3 100644 --- a/src/Max.Bot/Types/Enums/TextFormat.cs +++ b/src/Max.Bot/Types/Enums/TextFormat.cs @@ -1,11 +1,12 @@ using System.Text.Json.Serialization; +using Max.Bot.Types.Converters; namespace Max.Bot.Types.Enums; /// /// Represents the text format for message content. /// -[JsonConverter(typeof(JsonStringEnumConverter))] +[JsonConverter(typeof(JsonSnakeCaseEnumConverter))] public enum TextFormat { /// @@ -18,9 +19,3 @@ public enum TextFormat /// Html } - - - - - - diff --git a/src/Max.Bot/Types/Enums/UpdateType.cs b/src/Max.Bot/Types/Enums/UpdateType.cs index c339082..c810e54 100644 --- a/src/Max.Bot/Types/Enums/UpdateType.cs +++ b/src/Max.Bot/Types/Enums/UpdateType.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using Max.Bot.Types.Converters; namespace Max.Bot.Types.Enums; @@ -6,6 +7,7 @@ namespace Max.Bot.Types.Enums; /// Represents the type of an update from Max Messenger API. /// Maps to the "update_type" field in the API response. /// +[JsonConverter(typeof(UpdateTypeJsonConverter))] public enum UpdateType { /// diff --git a/src/Max.Bot/Types/Enums/UploadType.cs b/src/Max.Bot/Types/Enums/UploadType.cs index 99e72cd..d9e90d2 100644 --- a/src/Max.Bot/Types/Enums/UploadType.cs +++ b/src/Max.Bot/Types/Enums/UploadType.cs @@ -1,39 +1,35 @@ using System.Text.Json.Serialization; +using Max.Bot.Types.Converters; namespace Max.Bot.Types.Enums; /// /// Represents the type of file to upload. /// +[JsonConverter(typeof(JsonSnakeCaseEnumConverter))] public enum UploadType { /// /// Image file. + /// Serialized as "image". /// - [JsonPropertyName("image")] Image, /// /// Video file. + /// Serialized as "video". /// - [JsonPropertyName("video")] Video, /// /// Audio file. + /// Serialized as "audio". /// - [JsonPropertyName("audio")] Audio, /// /// Generic file. + /// Serialized as "file". /// - [JsonPropertyName("file")] File } - - - - - - diff --git a/src/Max.Bot/Types/GetMessagesResponse.cs b/src/Max.Bot/Types/GetMessagesResponse.cs index a35bff1..41b00e0 100644 --- a/src/Max.Bot/Types/GetMessagesResponse.cs +++ b/src/Max.Bot/Types/GetMessagesResponse.cs @@ -12,5 +12,5 @@ public class GetMessagesResponse /// /// The list of messages. [JsonPropertyName("messages")] - public Message[] Messages { get; set; } = default!; + public Message[] Messages { get; set; } = Array.Empty(); } diff --git a/src/Max.Bot/Types/GetUpdatesResponse.cs b/src/Max.Bot/Types/GetUpdatesResponse.cs index 143c394..ea4bbb2 100644 --- a/src/Max.Bot/Types/GetUpdatesResponse.cs +++ b/src/Max.Bot/Types/GetUpdatesResponse.cs @@ -15,7 +15,7 @@ public class GetUpdatesResponse /// /// The list of updates. [JsonPropertyName("updates")] - public Update[] Updates { get; set; } = default!; + public Update[] Updates { get; set; } = Array.Empty(); /// /// Gets or sets the marker for the next page of updates. diff --git a/src/Max.Bot/Types/Helpers/UpdateTypeHelper.cs b/src/Max.Bot/Types/Helpers/UpdateTypeHelper.cs index 4541a37..18bac83 100644 --- a/src/Max.Bot/Types/Helpers/UpdateTypeHelper.cs +++ b/src/Max.Bot/Types/Helpers/UpdateTypeHelper.cs @@ -40,7 +40,7 @@ public static string ToStringValue(UpdateType updateType) /// /// Converts a string representation to enum. /// - /// The snake_case string (e.g., "message_created"). + /// The snake_case string (e.g., "message_created"); PascalCase names (e.g., "MessageCreated") are accepted too. /// The corresponding enum value, or if not recognized. public static UpdateType FromString(string? updateTypeString) { @@ -65,7 +65,7 @@ public static UpdateType FromString(string? updateTypeString) "user_removed" => UpdateType.UserRemoved, "chat_title_changed" => UpdateType.ChatTitleChanged, "message_chat_created" => UpdateType.MessageChatCreated, - _ => UpdateType.Unknown + _ => Converters.LenientEnumParser.TryParse(updateTypeString, out var parsed) ? parsed : UpdateType.Unknown }; } diff --git a/src/Max.Bot/Types/Image.cs b/src/Max.Bot/Types/Image.cs index d6b761e..9b0ba03 100644 --- a/src/Max.Bot/Types/Image.cs +++ b/src/Max.Bot/Types/Image.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using System.Text.Json.Serialization; namespace Max.Bot.Types; @@ -14,10 +15,10 @@ public class Image public long? PhotoId { get; set; } /// - /// Gets or sets the URL of the image. + /// Gets or sets the URL of the image. Always sent by MAX API. /// [JsonPropertyName("url")] - public string? Url { get; set; } + public string Url { get; set; } = string.Empty; /// /// Gets or sets the token of the image. @@ -29,5 +30,5 @@ public class Image /// Gets or sets the tokens received after image upload. /// [JsonPropertyName("photos")] - public object? Photos { get; set; } + public Dictionary? Photos { get; set; } } diff --git a/src/Max.Bot/Types/InlineKeyboardButton.cs b/src/Max.Bot/Types/InlineKeyboardButton.cs index e3ffba9..4d10a56 100644 --- a/src/Max.Bot/Types/InlineKeyboardButton.cs +++ b/src/Max.Bot/Types/InlineKeyboardButton.cs @@ -24,7 +24,7 @@ public class InlineKeyboardButton /// /// The text displayed on the button. [Required(ErrorMessage = "Text is required.")] - [StringLength(64, MinimumLength = 1, ErrorMessage = "Text must be between 1 and 64 characters.")] + [StringLength(128, MinimumLength = 1, ErrorMessage = "Text must be between 1 and 128 characters.")] [JsonPropertyName("text")] public string Text { get; set; } = string.Empty; @@ -32,7 +32,7 @@ public class InlineKeyboardButton /// Gets or sets the payload data for callback or message buttons. /// /// The payload data, or null if not applicable. - [StringLength(64, ErrorMessage = "Payload must not exceed 64 characters.")] + [StringLength(1024, ErrorMessage = "Payload must not exceed 1024 characters.")] [JsonPropertyName("payload")] public string? Payload { get; set; } @@ -85,6 +85,34 @@ public string? Url [JsonPropertyName("quick")] public bool? Quick { get; set; } + /// + /// Gets or sets the title of the chat created by a button. + /// + [StringLength(200, ErrorMessage = "Chat title must not exceed 200 characters.")] + [JsonPropertyName("chat_title")] + public string? ChatTitle { get; set; } + + /// + /// Gets or sets the description of the chat created by a button. + /// + [StringLength(400, ErrorMessage = "Chat description must not exceed 400 characters.")] + [JsonPropertyName("chat_description")] + public string? ChatDescription { get; set; } + + /// + /// Gets or sets the payload sent to the bot in message_chat_created when a button creates the chat. + /// + [StringLength(512, ErrorMessage = "Start payload must not exceed 512 characters.")] + [JsonPropertyName("start_payload")] + public string? StartPayload { get; set; } + + /// + /// Gets or sets the unique identifier of a button generated by MAX. + /// Pass it back unchanged when editing the message, otherwise a new chat is created on the next press. + /// + [JsonPropertyName("uuid")] + public long? Uuid { get; set; } + /// /// Gets or sets the callback data sent when the button is pressed. /// This property is for backward compatibility and automatically sets Type to Callback and Payload. diff --git a/src/Max.Bot/Types/Message.cs b/src/Max.Bot/Types/Message.cs index 3af8bf4..038cee0 100644 --- a/src/Max.Bot/Types/Message.cs +++ b/src/Max.Bot/Types/Message.cs @@ -5,6 +5,8 @@ using System.ComponentModel.DataAnnotations; using System.Text.Json.Serialization; +using Max.Bot.Types.Converters; +using Max.Bot.Types.Enums; namespace Max.Bot.Types; @@ -16,6 +18,7 @@ public class Message { /// /// Gets or sets the user who sent the message. + /// Can be null if the message was posted on behalf of a channel. /// Maps to "sender" field from API. /// [JsonPropertyName("sender")] @@ -23,10 +26,10 @@ public class Message /// /// Gets or sets the recipient of the message. - /// Can be a user or a chat. + /// Can be a user or a chat. Always present in MAX API responses. /// [JsonPropertyName("recipient")] - public MessageRecipient? Recipient { get; set; } + public MessageRecipient Recipient { get; set; } = new(); /// /// Gets or sets the timestamp when the message was created (Unix timestamp in milliseconds). @@ -34,7 +37,7 @@ public class Message /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] [JsonPropertyName("timestamp")] - public long? Timestamp { get; set; } + public long Timestamp { get; set; } /// /// Gets or sets the linked message (forwarded or reply message). @@ -53,6 +56,7 @@ public class Message /// /// Gets or sets the statistics of the message. + /// Available only for channel messages returned by GET /messages. /// Maps to "stat" field from API. /// [JsonPropertyName("stat")] @@ -97,20 +101,22 @@ public string? Text public class LinkedMessage { /// - /// Gets or sets the type of link. - /// Possible values: "forward", "reply". + /// Gets or sets the type of link: or . /// + /// The link type, or null if MAX sent a value unknown to this library version. [JsonPropertyName("type")] - public string? Type { get; set; } + [JsonConverter(typeof(LenientNullableEnumConverter))] + public MessageLinkType? Type { get; set; } /// /// Gets or sets the user who sent the original message. + /// Can be null if the message was posted on behalf of a channel. /// [JsonPropertyName("sender")] public User? Sender { get; set; } /// - /// Gets or sets the chat where the message was sent. + /// Gets or sets the chat where the message was originally posted. Present for forwarded messages only. /// [JsonPropertyName("chat_id")] public long? ChatId { get; set; } @@ -120,7 +126,7 @@ public class LinkedMessage /// Note: In API this is called "message" but contains only MessageBody fields, not full Message. /// [JsonPropertyName("message")] - public MessageBody? Message { get; set; } + public MessageBody Message { get; set; } = new(); /// /// Gets the text content of the linked message. @@ -132,13 +138,13 @@ public class LinkedMessage /// Gets the message ID of the linked message. /// [JsonIgnore] - public string? Mid => Message?.Mid; + public string Mid => Message?.Mid ?? string.Empty; /// /// Gets the sequence number of the linked message. /// [JsonIgnore] - public long? Seq => Message?.Seq; + public long Seq => Message?.Seq ?? 0; } /// @@ -151,7 +157,7 @@ public class MessageBody /// Gets or sets the message ID. /// [JsonPropertyName("mid")] - public string? Mid { get; set; } + public string Mid { get; set; } = string.Empty; /// /// Gets or sets the sequence number of the message. @@ -159,7 +165,7 @@ public class MessageBody /// [Range(0, long.MaxValue, ErrorMessage = "Sequence number cannot be negative.")] [JsonPropertyName("seq")] - public long? Seq { get; set; } + public long Seq { get; set; } /// /// Gets or sets the text content of the message. @@ -198,7 +204,7 @@ public class MessageStat /// [Range(0, int.MaxValue, ErrorMessage = "Views cannot be negative.")] [JsonPropertyName("views")] - public int? Views { get; set; } + public int Views { get; set; } } /// @@ -207,10 +213,12 @@ public class MessageStat public class MarkupElement { /// - /// Gets or sets the markup type (strong, emphasized, monospaced, link, strikethrough, underline, user_mention, heading, highlighted). + /// Gets or sets the markup type (strong, emphasized, monospaced, link, strikethrough, underline, user_mention, heading, highlighted, quote). /// + /// The markup type, or null if MAX sent a value unknown to this library version. [JsonPropertyName("type")] - public string? Type { get; set; } + [JsonConverter(typeof(LenientNullableEnumConverter))] + public MarkupType? Type { get; set; } /// /// Gets or sets the start position (in UTF-16 code units) of the element in the text. diff --git a/src/Max.Bot/Types/MessageRecipient.cs b/src/Max.Bot/Types/MessageRecipient.cs index 53d0cee..f1d894c 100644 --- a/src/Max.Bot/Types/MessageRecipient.cs +++ b/src/Max.Bot/Types/MessageRecipient.cs @@ -1,4 +1,6 @@ using System.Text.Json.Serialization; +using Max.Bot.Types.Converters; +using Max.Bot.Types.Enums; namespace Max.Bot.Types; @@ -9,18 +11,18 @@ public class MessageRecipient { /// /// Gets or sets the chat ID of the recipient. - /// For direct messages (dialogs), this can be null or 0. /// - /// The unique identifier of the chat, or null/0 for direct messages. + /// The unique identifier of the chat, or null if MAX did not send it. [JsonPropertyName("chat_id")] public long? ChatId { get; set; } /// - /// Gets or sets the type of the chat. + /// Gets or sets the type of the chat: , or . /// - /// The type of the chat (e.g., "dialog", "group", "channel"). + /// The type of the chat, or null if it is missing or unknown to this library version. [JsonPropertyName("chat_type")] - public string? ChatType { get; set; } + [JsonConverter(typeof(LenientNullableEnumConverter))] + public ChatType? ChatType { get; set; } /// /// Gets or sets the user ID of the recipient (for dialogs). @@ -29,4 +31,3 @@ public class MessageRecipient [JsonPropertyName("user_id")] public long? UserId { get; set; } } - diff --git a/src/Max.Bot/Types/MessageUpdate.cs b/src/Max.Bot/Types/MessageUpdate.cs index 2dca8b0..fe05c58 100644 --- a/src/Max.Bot/Types/MessageUpdate.cs +++ b/src/Max.Bot/Types/MessageUpdate.cs @@ -19,7 +19,7 @@ public class MessageUpdate /// /// The timestamp when the update was created. [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] - public long? Timestamp { get; set; } + public long Timestamp { get; set; } /// /// Gets or sets the user locale for this update. diff --git a/src/Max.Bot/Types/ModifyMembersResponse.cs b/src/Max.Bot/Types/ModifyMembersResponse.cs new file mode 100644 index 0000000..7465d10 --- /dev/null +++ b/src/Max.Bot/Types/ModifyMembersResponse.cs @@ -0,0 +1,40 @@ +using System.Text.Json.Serialization; + +namespace Max.Bot.Types; + +/// +/// Represents the result of POST /chats/{chatId}/members: success flag plus the users that could not be added. +/// +public class ModifyMembersResponse : Response +{ + /// + /// Gets or sets the identifiers of users that could not be added or removed. + /// + [JsonPropertyName("failed_user_ids")] + public long[]? FailedUserIds { get; set; } + + /// + /// Gets or sets the reasons why users could not be added, grouped by error code. + /// + [JsonPropertyName("failed_user_details")] + public FailedUserDetails[]? FailedUserDetails { get; set; } +} + +/// +/// Describes why some users could not be added to a chat. +/// +public class FailedUserDetails +{ + /// + /// Gets or sets the error code, for example add.participant.privacy (privacy settings) or + /// add.participant.not.found (user not found). + /// + [JsonPropertyName("error_code")] + public string ErrorCode { get; set; } = string.Empty; + + /// + /// Gets or sets the identifiers of users that failed with . + /// + [JsonPropertyName("user_ids")] + public long[] UserIds { get; set; } = Array.Empty(); +} diff --git a/src/Max.Bot/Types/Subscription.cs b/src/Max.Bot/Types/Subscription.cs index 46f5df0..8b78278 100644 --- a/src/Max.Bot/Types/Subscription.cs +++ b/src/Max.Bot/Types/Subscription.cs @@ -15,7 +15,7 @@ public class Subscription /// /// The webhook URL. [JsonPropertyName("url")] - public string Url { get; set; } = default!; + public string Url { get; set; } = string.Empty; /// /// Gets or sets the list of update types that this subscription receives. @@ -51,7 +51,7 @@ public class Subscription /// Gets or sets the Unix time (milliseconds) when the subscription was created, as returned by MAX API. /// [JsonPropertyName("time")] - public long? Time { get; set; } + public long Time { get; set; } /// /// Gets or sets the API version of the subscription. diff --git a/src/Max.Bot/Types/SubscriptionsResponse.cs b/src/Max.Bot/Types/SubscriptionsResponse.cs index 6778448..5806f06 100644 --- a/src/Max.Bot/Types/SubscriptionsResponse.cs +++ b/src/Max.Bot/Types/SubscriptionsResponse.cs @@ -12,7 +12,7 @@ public class SubscriptionsResponse /// /// The list of subscriptions. [JsonPropertyName("subscriptions")] - public Subscription[] Subscriptions { get; set; } = default!; + public Subscription[] Subscriptions { get; set; } = Array.Empty(); } diff --git a/src/Max.Bot/Types/Update.cs b/src/Max.Bot/Types/Update.cs index 98e52e3..71b281a 100644 --- a/src/Max.Bot/Types/Update.cs +++ b/src/Max.Bot/Types/Update.cs @@ -36,7 +36,7 @@ public class Update /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] [JsonPropertyName("timestamp")] - public long? Timestamp { get; set; } + public long Timestamp { get; set; } /// /// Gets or sets the user locale for this update. @@ -139,7 +139,7 @@ public ChatType? ChatType return Chat.Type; } - if (TryParseChatType(Message?.Recipient?.ChatType, out var chatType)) + if (Message?.Recipient?.ChatType is { } chatType) { return chatType; } @@ -325,9 +325,9 @@ public MessageRemovedUpdate? MessageRemovedUpdate Timestamp = Timestamp, UserLocale = UserLocale, Message = Message, - MessageId = MessageId ?? Message?.Mid, - ChatId = ChatId, - UserId = UserId + MessageId = MessageId ?? Message?.Mid ?? string.Empty, + ChatId = ChatId ?? 0, + UserId = UserId ?? 0 }; } } @@ -348,10 +348,10 @@ public BotAddedUpdate? BotAddedUpdate UpdateId = UpdateId, Timestamp = Timestamp, Chat = Chat, - ChatId = ChatId ?? Chat?.ChatId, - User = User, + ChatId = ChatId ?? Chat?.ChatId ?? 0, + User = User ?? new User(), InviterId = InviterId, - IsChannel = IsChannel + IsChannel = IsChannel ?? false }; } } @@ -372,9 +372,9 @@ public BotRemovedUpdate? BotRemovedUpdate UpdateId = UpdateId, Timestamp = Timestamp, Chat = Chat, - ChatId = ChatId ?? Chat?.ChatId, - User = User, - IsChannel = IsChannel + ChatId = ChatId ?? Chat?.ChatId ?? 0, + User = User ?? new User(), + IsChannel = IsChannel ?? false }; } } @@ -394,8 +394,8 @@ public BotStartedUpdate? BotStartedUpdate { UpdateId = UpdateId, Timestamp = Timestamp, - ChatId = ChatId, - User = User, + ChatId = ChatId ?? 0, + User = User ?? new User(), UserLocale = UserLocale, Payload = Payload }; @@ -417,8 +417,8 @@ public BotStoppedUpdate? BotStoppedUpdate { UpdateId = UpdateId, Timestamp = Timestamp, - ChatId = ChatId, - User = User, + ChatId = ChatId ?? 0, + User = User ?? new User(), UserLocale = UserLocale }; } @@ -440,10 +440,10 @@ public UserAddedUpdate? UserAddedUpdate UpdateId = UpdateId, Timestamp = Timestamp, Chat = Chat, - ChatId = ChatId ?? Chat?.ChatId, - User = User, + ChatId = ChatId ?? Chat?.ChatId ?? 0, + User = User ?? new User(), InviterId = InviterId, - IsChannel = IsChannel + IsChannel = IsChannel ?? false }; } } @@ -464,10 +464,10 @@ public UserRemovedUpdate? UserRemovedUpdate UpdateId = UpdateId, Timestamp = Timestamp, Chat = Chat, - ChatId = ChatId ?? Chat?.ChatId, - User = User, + ChatId = ChatId ?? Chat?.ChatId ?? 0, + User = User ?? new User(), AdminId = AdminId, - IsChannel = IsChannel + IsChannel = IsChannel ?? false }; } } @@ -488,9 +488,9 @@ public ChatTitleChangedUpdate? ChatTitleChangedUpdate UpdateId = UpdateId, Timestamp = Timestamp, Chat = Chat, - ChatId = ChatId ?? Chat?.ChatId, - User = User, - Title = Title ?? Chat?.Title + ChatId = ChatId ?? Chat?.ChatId ?? 0, + User = User ?? new User(), + Title = Title ?? Chat?.Title ?? string.Empty }; } } @@ -510,10 +510,10 @@ public DialogMutedUpdate? DialogMutedUpdate { UpdateId = UpdateId, Timestamp = Timestamp, - ChatId = ChatId, + ChatId = ChatId ?? 0, IsMuted = IsMuted, - MutedUntil = MutedUntil, - User = User, + MutedUntil = MutedUntil ?? 0, + User = User ?? new User(), UserLocale = UserLocale }; } @@ -534,9 +534,9 @@ public DialogUnmutedUpdate? DialogUnmutedUpdate { UpdateId = UpdateId, Timestamp = Timestamp, - ChatId = ChatId, + ChatId = ChatId ?? 0, IsMuted = IsMuted, - User = User, + User = User ?? new User(), UserLocale = UserLocale }; } @@ -557,8 +557,8 @@ public DialogClearedUpdate? DialogClearedUpdate { UpdateId = UpdateId, Timestamp = Timestamp, - ChatId = ChatId, - User = User, + ChatId = ChatId ?? 0, + User = User ?? new User(), UserLocale = UserLocale }; } @@ -579,8 +579,8 @@ public DialogRemovedUpdate? DialogRemovedUpdate { UpdateId = UpdateId, Timestamp = Timestamp, - ChatId = ChatId, - User = User, + ChatId = ChatId ?? 0, + User = User ?? new User(), UserLocale = UserLocale }; } @@ -603,9 +603,9 @@ public MessageChatCreatedUpdate? MessageChatCreatedUpdate Timestamp = Timestamp, UserLocale = UserLocale, Message = Message, - Chat = Chat, - ChatId = ChatId ?? Chat?.ChatId, - MessageId = MessageId, + Chat = Chat ?? new Chat(), + ChatId = ChatId ?? Chat?.ChatId ?? 0, + MessageId = MessageId ?? string.Empty, StartPayload = Payload }; } @@ -613,25 +613,6 @@ public MessageChatCreatedUpdate? MessageChatCreatedUpdate #endregion - internal static bool TryParseChatType(string? value, out ChatType chatType) - { - switch (value?.Trim().ToLowerInvariant()) - { - case "dialog": - chatType = Enums.ChatType.Dialog; - return true; - case "chat": - chatType = Enums.ChatType.Chat; - return true; - case "channel": - chatType = Enums.ChatType.Channel; - return true; - default: - chatType = default; - return false; - } - } - /// /// Parses the raw update_type string to UpdateType enum. /// diff --git a/src/Max.Bot/Types/UpdateTypes.cs b/src/Max.Bot/Types/UpdateTypes.cs index f267968..80d03d6 100644 --- a/src/Max.Bot/Types/UpdateTypes.cs +++ b/src/Max.Bot/Types/UpdateTypes.cs @@ -17,7 +17,7 @@ public class MessageEditedUpdate /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] - public long? Timestamp { get; set; } + public long Timestamp { get; set; } /// /// Gets or sets the user locale for this update. @@ -45,7 +45,7 @@ public class MessageRemovedUpdate /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] - public long? Timestamp { get; set; } + public long Timestamp { get; set; } /// /// Gets or sets the user locale for this update. @@ -60,17 +60,17 @@ public class MessageRemovedUpdate /// /// Gets or sets the identifier of the removed message (message_id). /// - public string? MessageId { get; set; } + public string MessageId { get; set; } = string.Empty; /// /// Gets or sets the chat identifier where the message was removed. /// - public long? ChatId { get; set; } + public long ChatId { get; set; } /// /// Gets or sets the identifier of the user who removed the message. /// - public long? UserId { get; set; } + public long UserId { get; set; } } /// @@ -89,7 +89,7 @@ public class BotAddedUpdate /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] - public long? Timestamp { get; set; } + public long Timestamp { get; set; } /// /// Gets or sets the chat where the bot was added. @@ -99,7 +99,7 @@ public class BotAddedUpdate /// /// Gets or sets the user (bot) that was added. /// - public User? User { get; set; } + public User User { get; set; } = new(); /// /// Gets or sets the ID of the user who invited the bot. @@ -109,12 +109,12 @@ public class BotAddedUpdate /// /// Gets or sets the identifier of the chat the bot was added to. /// - public long? ChatId { get; set; } + public long ChatId { get; set; } /// /// Gets or sets a value indicating whether the bot was added to a channel. /// - public bool? IsChannel { get; set; } + public bool IsChannel { get; set; } } /// @@ -133,7 +133,7 @@ public class BotRemovedUpdate /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] - public long? Timestamp { get; set; } + public long Timestamp { get; set; } /// /// Gets or sets the chat where the bot was removed. @@ -143,17 +143,17 @@ public class BotRemovedUpdate /// /// Gets or sets the user (bot) that was removed. /// - public User? User { get; set; } + public User User { get; set; } = new(); /// /// Gets or sets the identifier of the chat the bot was removed from. /// - public long? ChatId { get; set; } + public long ChatId { get; set; } /// /// Gets or sets a value indicating whether the bot was removed from a channel. /// - public bool? IsChannel { get; set; } + public bool IsChannel { get; set; } } /// @@ -172,17 +172,17 @@ public class BotStartedUpdate /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] - public long? Timestamp { get; set; } + public long Timestamp { get; set; } /// /// Gets or sets the chat ID where the bot was started. /// - public long? ChatId { get; set; } + public long ChatId { get; set; } /// /// Gets or sets the user who started the bot. /// - public User? User { get; set; } + public User User { get; set; } = new(); /// /// Gets or sets the user locale. @@ -211,17 +211,17 @@ public class BotStoppedUpdate /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] - public long? Timestamp { get; set; } + public long Timestamp { get; set; } /// /// Gets or sets the chat ID where the bot was stopped. /// - public long? ChatId { get; set; } + public long ChatId { get; set; } /// /// Gets or sets the user who stopped the bot. /// - public User? User { get; set; } + public User User { get; set; } = new(); /// /// Gets or sets the user locale. @@ -245,7 +245,7 @@ public class UserAddedUpdate /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] - public long? Timestamp { get; set; } + public long Timestamp { get; set; } /// /// Gets or sets the chat where the user was added. @@ -255,7 +255,7 @@ public class UserAddedUpdate /// /// Gets or sets the user that was added. /// - public User? User { get; set; } + public User User { get; set; } = new(); /// /// Gets or sets the ID of the user who invited the user. @@ -265,12 +265,12 @@ public class UserAddedUpdate /// /// Gets or sets the identifier of the chat the user was added to. /// - public long? ChatId { get; set; } + public long ChatId { get; set; } /// /// Gets or sets a value indicating whether the user was added to a channel. /// - public bool? IsChannel { get; set; } + public bool IsChannel { get; set; } } /// @@ -289,7 +289,7 @@ public class UserRemovedUpdate /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] - public long? Timestamp { get; set; } + public long Timestamp { get; set; } /// /// Gets or sets the chat where the user was removed. @@ -299,12 +299,12 @@ public class UserRemovedUpdate /// /// Gets or sets the user that was removed. /// - public User? User { get; set; } + public User User { get; set; } = new(); /// /// Gets or sets the identifier of the chat the user was removed from. /// - public long? ChatId { get; set; } + public long ChatId { get; set; } /// /// Gets or sets the identifier of the administrator who removed the user. @@ -314,7 +314,7 @@ public class UserRemovedUpdate /// /// Gets or sets a value indicating whether the user was removed from a channel. /// - public bool? IsChannel { get; set; } + public bool IsChannel { get; set; } } /// @@ -333,7 +333,7 @@ public class ChatTitleChangedUpdate /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] - public long? Timestamp { get; set; } + public long Timestamp { get; set; } /// /// Gets or sets the chat with the new title. @@ -343,17 +343,17 @@ public class ChatTitleChangedUpdate /// /// Gets or sets the user who changed the title. /// - public User? User { get; set; } + public User User { get; set; } = new(); /// /// Gets or sets the identifier of the chat whose title changed. /// - public long? ChatId { get; set; } + public long ChatId { get; set; } /// /// Gets or sets the new chat title. /// - public string? Title { get; set; } + public string Title { get; set; } = string.Empty; } /// @@ -372,12 +372,12 @@ public class DialogMutedUpdate /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] - public long? Timestamp { get; set; } + public long Timestamp { get; set; } /// /// Gets or sets the chat ID of the muted dialog. /// - public long? ChatId { get; set; } + public long ChatId { get; set; } /// /// Gets or sets whether the dialog is muted. @@ -387,12 +387,12 @@ public class DialogMutedUpdate /// /// Gets or sets the time (Unix milliseconds) until which the dialog is muted. /// - public long? MutedUntil { get; set; } + public long MutedUntil { get; set; } /// /// Gets or sets the user who muted the dialog. /// - public User? User { get; set; } + public User User { get; set; } = new(); /// /// Gets or sets the user locale. @@ -416,12 +416,12 @@ public class DialogUnmutedUpdate /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] - public long? Timestamp { get; set; } + public long Timestamp { get; set; } /// /// Gets or sets the chat ID of the unmuted dialog. /// - public long? ChatId { get; set; } + public long ChatId { get; set; } /// /// Gets or sets whether the dialog is muted. @@ -431,7 +431,7 @@ public class DialogUnmutedUpdate /// /// Gets or sets the user who unmuted the dialog. /// - public User? User { get; set; } + public User User { get; set; } = new(); /// /// Gets or sets the user locale. @@ -455,17 +455,17 @@ public class DialogClearedUpdate /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] - public long? Timestamp { get; set; } + public long Timestamp { get; set; } /// /// Gets or sets the chat ID of the cleared dialog. /// - public long? ChatId { get; set; } + public long ChatId { get; set; } /// /// Gets or sets the user who cleared the dialog. /// - public User? User { get; set; } + public User User { get; set; } = new(); /// /// Gets or sets the user locale. @@ -489,17 +489,17 @@ public class DialogRemovedUpdate /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] - public long? Timestamp { get; set; } + public long Timestamp { get; set; } /// /// Gets or sets the chat ID of the removed dialog. /// - public long? ChatId { get; set; } + public long ChatId { get; set; } /// /// Gets or sets the user who removed the dialog. /// - public User? User { get; set; } + public User User { get; set; } = new(); /// /// Gets or sets the user locale. @@ -523,7 +523,7 @@ public class MessageChatCreatedUpdate /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] - public long? Timestamp { get; set; } + public long Timestamp { get; set; } /// /// Gets or sets the user locale. @@ -538,17 +538,17 @@ public class MessageChatCreatedUpdate /// /// Gets or sets the created chat. /// - public Chat? Chat { get; set; } + public Chat Chat { get; set; } = new(); /// /// Gets or sets the identifier of the created chat. /// - public long? ChatId { get; set; } + public long ChatId { get; set; } /// /// Gets or sets the identifier of the message where the button was clicked. /// - public string? MessageId { get; set; } + public string MessageId { get; set; } = string.Empty; /// /// Gets or sets the payload from the chat button (start_payload). diff --git a/src/Max.Bot/Types/UploadResponse.cs b/src/Max.Bot/Types/UploadResponse.cs index 277133f..8288b0b 100644 --- a/src/Max.Bot/Types/UploadResponse.cs +++ b/src/Max.Bot/Types/UploadResponse.cs @@ -12,7 +12,7 @@ public class UploadResponse /// /// The upload URL. [JsonPropertyName("url")] - public string Url { get; set; } = default!; + public string Url { get; set; } = string.Empty; /// /// Gets or sets the token for video or audio uploads. diff --git a/src/Max.Bot/Types/User.cs b/src/Max.Bot/Types/User.cs index b80cf1a..5dfcb6c 100644 --- a/src/Max.Bot/Types/User.cs +++ b/src/Max.Bot/Types/User.cs @@ -27,10 +27,10 @@ public class User /// /// Gets or sets the first name of the user. /// - /// The first name of the user, or null if not available. + /// The first name of the user. Always sent by MAX API. [StringLength(64, ErrorMessage = "First name must not exceed 64 characters.")] [JsonPropertyName("first_name")] - public string? FirstName { get; set; } + public string FirstName { get; set; } = string.Empty; /// /// Gets or sets the last name of the user. @@ -53,7 +53,7 @@ public class User /// The timestamp of the user's last activity. [Range(0, long.MaxValue, ErrorMessage = "Last activity time cannot be negative.")] [JsonPropertyName("last_activity_time")] - public long? LastActivityTime { get; set; } + public long LastActivityTime { get; set; } /// /// Gets or sets the deprecated display name. diff --git a/src/Max.Bot/Types/Video.cs b/src/Max.Bot/Types/Video.cs index 33dfd1d..20a7b77 100644 --- a/src/Max.Bot/Types/Video.cs +++ b/src/Max.Bot/Types/Video.cs @@ -13,7 +13,7 @@ public class Video /// Gets or sets the media token returned by /videos/{token}. /// [JsonPropertyName("token")] - public string? Token { get; set; } + public string Token { get; set; } = string.Empty; /// /// Gets or sets the unique identifier of the video. @@ -35,26 +35,26 @@ public class Video /// /// Gets or sets the width of the video in pixels. /// - /// The width of the video in pixels, or null if not available. - [Range(1, int.MaxValue, ErrorMessage = "Width must be greater than zero if provided.")] + /// The width of the video in pixels. + [Range(0, int.MaxValue, ErrorMessage = "Width cannot be negative.")] [JsonPropertyName("width")] - public int? Width { get; set; } + public int Width { get; set; } /// /// Gets or sets the height of the video in pixels. /// - /// The height of the video in pixels, or null if not available. - [Range(1, int.MaxValue, ErrorMessage = "Height must be greater than zero if provided.")] + /// The height of the video in pixels. + [Range(0, int.MaxValue, ErrorMessage = "Height cannot be negative.")] [JsonPropertyName("height")] - public int? Height { get; set; } + public int Height { get; set; } /// /// Gets or sets the duration of the video in seconds. /// - /// The duration of the video in seconds, or null if not available. - [Range(1, int.MaxValue, ErrorMessage = "Duration must be greater than zero if provided.")] + /// The duration of the video in seconds. + [Range(0, int.MaxValue, ErrorMessage = "Duration cannot be negative.")] [JsonPropertyName("duration")] - public int? Duration { get; set; } + public int Duration { get; set; } /// /// Gets or sets the size of the video file in bytes. @@ -103,7 +103,7 @@ public class VideoThumbnail /// Gets or sets the thumbnail URL. /// [JsonPropertyName("url")] - public string? Url { get; set; } + public string Url { get; set; } = string.Empty; /// /// Gets or sets the thumbnail photo identifier. diff --git a/tests/Max.Bot.Tests/Examples/SampleBotsTests.cs b/tests/Max.Bot.Tests/Examples/SampleBotsTests.cs index fdddd5d..5e107fa 100644 --- a/tests/Max.Bot.Tests/Examples/SampleBotsTests.cs +++ b/tests/Max.Bot.Tests/Examples/SampleBotsTests.cs @@ -159,7 +159,7 @@ private static Update CreateMessageUpdate(string text) UpdateTypeRaw = "message_created", Message = new Message { - Recipient = new MessageRecipient { ChatId = 1337, ChatType = "chat" }, + Recipient = new MessageRecipient { ChatId = 1337, ChatType = ChatType.Chat }, Body = new MessageBody { Mid = "mid.sample.1", Text = text }, Timestamp = 1609459200000 } diff --git a/tests/Max.Bot.Tests/Unit/Api/ChatsApiTests.cs b/tests/Max.Bot.Tests/Unit/Api/ChatsApiTests.cs index dabd920..6628b08 100644 --- a/tests/Max.Bot.Tests/Unit/Api/ChatsApiTests.cs +++ b/tests/Max.Bot.Tests/Unit/Api/ChatsApiTests.cs @@ -803,16 +803,14 @@ public async Task AddChatMembersAsync_ShouldReturnResponse_WhenRequestSucceeds() // Arrange var chatId = 123456L; var request = new AddChatMembersRequest { UserIds = new[] { 100L, 200L } }; - var expectedResponse = new Response { Success = true }; - _mockHttpClient - .Setup(x => x.SendAsync( + .Setup(x => x.SendAsyncRaw( It.Is(req => req.Method == HttpMethod.Post && req.Endpoint == $"/chats/{chatId}/members" && req.Body != null), It.IsAny())) - .ReturnsAsync(expectedResponse); + .ReturnsAsync("""{"success":true,"failed_user_ids":[200]}"""); var chatsApi = new ChatsApi(_mockHttpClient.Object, _options); @@ -822,6 +820,7 @@ public async Task AddChatMembersAsync_ShouldReturnResponse_WhenRequestSucceeds() // Assert result.Should().NotBeNull(); result.Success.Should().BeTrue(); + result.FailedUserIds.Should().Equal(200L); } [Fact] @@ -887,5 +886,72 @@ await act.Should().ThrowAsync() .WithParameterName("userId"); } + [Theory] + [InlineData(true, "true")] + [InlineData(false, null)] + public async Task RemoveChatMemberAsync_WithBlock_ShouldPassBlockQueryParameter(bool block, string? expectedBlock) + { + // Arrange + MaxApiRequest? captured = null; + _mockHttpClient + .Setup(x => x.SendAsync(It.IsAny(), It.IsAny())) + .Callback((req, _) => captured = req) + .ReturnsAsync(new Response { Success = true }); + + var chatsApi = new ChatsApi(_mockHttpClient.Object, _options); + + // Act + var result = await chatsApi.RemoveChatMemberAsync(-100L, 789L, block); + + // Assert + result.Success.Should().BeTrue(); + captured.Should().NotBeNull(); + captured!.Method.Should().Be(HttpMethod.Delete); + captured.Endpoint.Should().Be("/chats/-100/members"); + captured.QueryParameters!["user_id"].Should().Be("789"); + captured.QueryParameters.GetValueOrDefault("block").Should().Be(expectedBlock); + } + + #endregion + + #region GetChatMembersByIdsAsync Tests + + [Fact] + public async Task GetChatMembersByIdsAsync_ShouldPassCommaSeparatedUserIds() + { + // Arrange + MaxApiRequest? captured = null; + _mockHttpClient + .Setup(x => x.SendAsyncRaw(It.IsAny(), It.IsAny())) + .Callback((req, _) => captured = req) + .ReturnsAsync("""{"members":[{"user_id":1},{"user_id":2}],"marker":null}"""); + + var chatsApi = new ChatsApi(_mockHttpClient.Object, _options); + + // Act + var result = await chatsApi.GetChatMembersByIdsAsync(123L, new[] { 1L, 2L, 2L }); + + // Assert + result.Select(m => m.Id).Should().Equal(1L, 2L); + captured.Should().NotBeNull(); + captured!.Method.Should().Be(HttpMethod.Get); + captured.Endpoint.Should().Be("/chats/123/members"); + captured.QueryParameters!["user_ids"].Should().Be("1,2"); + captured.QueryParameters.Should().NotContainKey("marker"); + } + + [Fact] + public async Task GetChatMembersByIdsAsync_ShouldThrow_WhenUserIdsAreEmpty() + { + // Arrange + var chatsApi = new ChatsApi(_mockHttpClient.Object, _options); + + // Act + var act = async () => await chatsApi.GetChatMembersByIdsAsync(123L, Array.Empty()); + + // Assert + await act.Should().ThrowAsync().WithParameterName("userIds"); + } + #endregion } diff --git a/tests/Max.Bot.Tests/Unit/Api/MessagesApiTests.cs b/tests/Max.Bot.Tests/Unit/Api/MessagesApiTests.cs index 495795b..6db62f2 100644 --- a/tests/Max.Bot.Tests/Unit/Api/MessagesApiTests.cs +++ b/tests/Max.Bot.Tests/Unit/Api/MessagesApiTests.cs @@ -42,7 +42,7 @@ public async Task SendMessageAsync_ShouldReturnMessage_WhenRequestSucceeds() var expectedMessage = new Message { Timestamp = 1609459200000, - Recipient = new MessageRecipient { ChatId = chatId, ChatType = "chat" }, + Recipient = new MessageRecipient { ChatId = chatId, ChatType = ChatType.Chat }, Body = new MessageBody { Mid = "mid.789", Text = text } }; @@ -96,8 +96,8 @@ public async Task GetMessagesAsync_ShouldReturnMessages_WhenRequestSucceeds() var chatId = 123456L; var expectedMessages = new[] { - new Message { Timestamp = 1609459200000, Recipient = new MessageRecipient { ChatId = chatId, ChatType = "chat" }, Body = new MessageBody { Mid = "mid.1", Text = "Message 1" } }, - new Message { Timestamp = 1609459200000, Recipient = new MessageRecipient { ChatId = chatId, ChatType = "chat" }, Body = new MessageBody { Mid = "mid.2", Text = "Message 2" } } + new Message { Timestamp = 1609459200000, Recipient = new MessageRecipient { ChatId = chatId, ChatType = ChatType.Chat }, Body = new MessageBody { Mid = "mid.1", Text = "Message 1" } }, + new Message { Timestamp = 1609459200000, Recipient = new MessageRecipient { ChatId = chatId, ChatType = ChatType.Chat }, Body = new MessageBody { Mid = "mid.2", Text = "Message 2" } } }; var response = new GetMessagesResponse @@ -209,7 +209,7 @@ public async Task EditMessageReplyMarkupAsync_ShouldRemoveKeyboard_WhenKeyboardI var currentMessage = new Message { Text = "Test message", - Recipient = new MessageRecipient { ChatId = 456, ChatType = "chat" }, + Recipient = new MessageRecipient { ChatId = 456, ChatType = ChatType.Chat }, Body = new MessageBody { Mid = "mid.current.123", @@ -276,7 +276,7 @@ public async Task EditMessageReplyMarkupAsync_ShouldReplaceKeyboard_WhenKeyboard var currentMessage = new Message { Text = "Test message", - Recipient = new MessageRecipient { ChatId = 456, ChatType = "chat" }, + Recipient = new MessageRecipient { ChatId = 456, ChatType = ChatType.Chat }, Body = new MessageBody { Mid = "mid.current.123", @@ -404,7 +404,7 @@ public async Task GetMessageAsync_ShouldReturnMessage_WhenRequestSucceeds() { Text = "Test message", Timestamp = 1609459200000, - Recipient = new MessageRecipient { ChatId = 456, ChatType = "chat" }, + Recipient = new MessageRecipient { ChatId = 456, ChatType = ChatType.Chat }, Body = new MessageBody { Mid = "msg-123", Text = "Test message" } }; @@ -651,7 +651,7 @@ public async Task SendMessageAsync_WithSendMessageRequest_ShouldReturnMessage_Wh { Text = request.Text, Timestamp = 1609459200000, - Recipient = new MessageRecipient { ChatId = chatId, ChatType = "chat" }, + Recipient = new MessageRecipient { ChatId = chatId, ChatType = ChatType.Chat }, Body = new MessageBody { Mid = "mid.789", Text = request.Text } }; @@ -742,7 +742,7 @@ public async Task SendMessageWithAttachmentAsync_ShouldReturnMessage_WhenRequest { Text = "With attachment", Timestamp = 1609459200000, - Recipient = new MessageRecipient { ChatId = chatId, ChatType = "chat" }, + Recipient = new MessageRecipient { ChatId = chatId, ChatType = ChatType.Chat }, Body = new MessageBody { Mid = "mid.789", Text = "With attachment" } }; @@ -801,7 +801,7 @@ public async Task SendMessageWithAttachmentAsync_ShouldRetry_WhenApiReturnsBadRe { Text = "With attachment", Timestamp = 1609459200000, - Recipient = new MessageRecipient { ChatId = chatId, ChatType = "chat" }, + Recipient = new MessageRecipient { ChatId = chatId, ChatType = ChatType.Chat }, Body = new MessageBody { Mid = "mid.retry", Text = "With attachment" } }; @@ -839,7 +839,7 @@ public async Task ForwardMessageAsync_ShouldReturnMessage_WhenRequestSucceeds() { Text = "Forwarded", Timestamp = 1609459200000, - Recipient = new MessageRecipient { ChatId = chatId, ChatType = "chat" }, + Recipient = new MessageRecipient { ChatId = chatId, ChatType = ChatType.Chat }, Body = new MessageBody { Mid = "mid.999", Text = "Forwarded" } }; @@ -898,7 +898,7 @@ public async Task ReplyToMessageAsync_ShouldReturnMessage_WhenRequestSucceeds() { Text = text, Timestamp = 1609459200000, - Recipient = new MessageRecipient { ChatId = chatId, ChatType = "chat" }, + Recipient = new MessageRecipient { ChatId = chatId, ChatType = ChatType.Chat }, Body = new MessageBody { Mid = "mid.999", Text = text } }; diff --git a/tests/Max.Bot.Tests/Unit/Regression/ModelDeserializationTests.cs b/tests/Max.Bot.Tests/Unit/Regression/ModelDeserializationTests.cs new file mode 100644 index 0000000..a27e982 --- /dev/null +++ b/tests/Max.Bot.Tests/Unit/Regression/ModelDeserializationTests.cs @@ -0,0 +1,316 @@ +// 📁 ModelDeserializationTests.cs - Regression tests for typed models in v0.8.0-alpha +// 🎯 Core function: Pins that enums and models deserialize with any JsonSerializerOptions and expose typed values. +// 🔗 Key dependencies: Max.Bot.Types models, enums, MaxJsonSerializer. +// 💡 Usage: Each test documents the failure scenario it guards against. + +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Serialization; +using FluentAssertions; +using Max.Bot.Networking; +using Max.Bot.Types; +using Max.Bot.Types.Enums; +using Xunit; + +namespace Max.Bot.Tests.Unit.Regression; + +public class ModelDeserializationTests +{ + private static readonly JsonSerializerOptions DefaultOptions = new(); + + private static readonly Assembly LibraryAssembly = typeof(Message).Assembly; + + private const string MessageCreatedJson = """ + { + "update_type": "message_created", + "timestamp": 1730300000000, + "user_locale": "ru", + "message": { + "sender": { "user_id": 1, "first_name": "Ann", "last_name": null, "username": null, "is_bot": false, "last_activity_time": 1730300000000 }, + "recipient": { "chat_id": -42, "chat_type": "chat", "user_id": null }, + "timestamp": 1730300000000, + "link": { + "type": "reply", + "sender": { "user_id": 2, "first_name": "Bob", "is_bot": false, "last_activity_time": 1 }, + "message": { "mid": "mid.original", "seq": 7, "text": "original", "attachments": null } + }, + "body": { + "mid": "mid.reply", + "seq": 8, + "text": "hello @bob", + "attachments": [ + { + "type": "inline_keyboard", + "callback_id": "kb-1", + "payload": { + "buttons": [ + [ { "type": "callback", "text": "Yes", "payload": "yes", "intent": "positive" } ], + [ { "type": "chat", "text": "Discuss", "chat_title": "Topic", "start_payload": "topic-1", "uuid": 123 } ] + ] + } + }, + { "type": "data", "data": "reply-keyboard-payload" } + ], + "markup": [ { "type": "user_mention", "from": 6, "length": 4, "user_id": 2 } ] + }, + "stat": { "views": 5 } + } + } + """; + + public static TheoryData LibraryEnums() + { + var data = new TheoryData(); + foreach (var type in LibraryAssembly.GetExportedTypes().Where(t => t.IsEnum).OrderBy(t => t.FullName, StringComparer.Ordinal)) + { + data.Add(type); + } + + return data; + } + + /// + /// Reported: JsonSerializer.SerializeToElement("reply").Deserialize<MessageLinkType>() threw because + /// MessageLinkType had no [JsonConverter] attribute (ChatType worked only thanks to case-insensitive parsing). + /// + [Fact] + public void MessageLinkType_ShouldDeserializeFromApiString_WithDefaultOptions() + { + JsonSerializer.SerializeToElement("reply").Deserialize().Should().Be(MessageLinkType.Reply); + JsonSerializer.SerializeToElement("forward").Deserialize().Should().Be(MessageLinkType.Forward); + JsonSerializer.Serialize(MessageLinkType.Reply).Should().Be("\"reply\""); + } + + [Theory] + [MemberData(nameof(LibraryEnums))] + public void Enum_ShouldDeclareJsonConverter(Type enumType) + { + enumType.GetCustomAttribute().Should().NotBeNull( + "every public enum must (de)serialize as MAX API strings without MaxJsonSerializer.Options"); + } + + [Theory] + [MemberData(nameof(LibraryEnums))] + public void Enum_ShouldRoundTripAsSnakeCaseString_WithDefaultAndLibraryOptions(Type enumType) + { + foreach (var value in Enum.GetValues(enumType)) + { + if (enumType == typeof(UpdateType) && (UpdateType)value == UpdateType.Unknown) + { + continue; + } + + var expectedJson = $"\"{JsonNamingPolicy.SnakeCaseLower.ConvertName(value.ToString()!)}\""; + + foreach (var options in new[] { DefaultOptions, MaxJsonSerializer.Options }) + { + JsonSerializer.Serialize(value, enumType, options).Should().Be(expectedJson, $"{enumType.Name}.{value}"); + JsonSerializer.Deserialize(expectedJson, enumType, options).Should().Be(value, $"{enumType.Name}.{value}"); + } + + // PascalCase names (as produced by older library versions) are still accepted. + JsonSerializer.Deserialize($"\"{value}\"", enumType, DefaultOptions).Should().Be(value); + } + } + + [Theory] + [InlineData("typing_on", ChatAction.TypingOn)] + [InlineData("mark_seen", ChatAction.MarkSeen)] + public void ChatAction_ShouldReadSnakeCase_WithDefaultOptions(string wireValue, ChatAction expected) + { + JsonSerializer.Deserialize($"\"{wireValue}\"").Should().Be(expected); + } + + [Fact] + public void ChatAdminPermissions_ShouldReadSnakeCase_WithDefaultOptions() + { + var permissions = JsonSerializer.Deserialize("""["read_all_messages","add_remove_members","post_edit_delete_message"]"""); + + permissions.Should().Equal(ChatAdminPermission.ReadAllMessages, ChatAdminPermission.AddRemoveMembers, ChatAdminPermission.PostEditDeleteMessage); + } + + [Fact] + public void UpdateType_ShouldReadApiString_WithDefaultOptions() + { + JsonSerializer.Deserialize("\"message_callback\"").Should().Be(UpdateType.MessageCallback); + JsonSerializer.Deserialize("\"something_new\"").Should().Be(UpdateType.Unknown); + } + + /// + /// Every property of a JSON model must carry an explicit [JsonPropertyName]; otherwise it is mapped only + /// with MaxJsonSerializer.Options (naming policy) and silently stays empty with any other options. + /// + [Fact] + public void JsonModels_ShouldDeclarePropertyNamesForEveryProperty() + { + var missing = new List(); + foreach (var type in LibraryAssembly.GetExportedTypes().Where(t => t.IsClass && t.Namespace?.StartsWith("Max.Bot.Types", StringComparison.Ordinal) == true)) + { + var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Where(p => p.GetIndexParameters().Length == 0) + .ToArray(); + + // Only JSON models (types with at least one mapped property) are checked; typed update wrappers are not serialized. + if (!properties.Any(p => p.GetCustomAttribute() != null)) + { + continue; + } + + missing.AddRange(properties + .Where(p => p.GetCustomAttribute() == null && + p.GetCustomAttribute() is not { Condition: JsonIgnoreCondition.Always } && + p.GetCustomAttribute() == null) + .Select(p => $"{type.Name}.{p.Name}")); + } + + missing.Should().BeEmpty(); + } + + [Fact] + public void MessageCreatedUpdate_ShouldBeFullyTyped_WithDefaultOptions() + { + var update = JsonSerializer.Deserialize(MessageCreatedJson)!; + + AssertTypedMessageCreatedUpdate(update); + } + + [Fact] + public void MessageCreatedUpdate_ShouldDeserializeTheSame_WithDefaultAndLibraryOptions() + { + var withDefault = JsonSerializer.Deserialize(MessageCreatedJson)!; + var withLibrary = MaxJsonSerializer.Deserialize(MessageCreatedJson); + + AssertTypedMessageCreatedUpdate(withLibrary); + JsonSerializer.Serialize(withDefault, MaxJsonSerializer.Options).Should().Be(JsonSerializer.Serialize(withLibrary, MaxJsonSerializer.Options)); + } + + [Fact] + public void LinkedMessage_ShouldReturnNullType_ForUnknownLinkType() + { + var message = JsonSerializer.Deserialize("""{"recipient":{"chat_id":1,"chat_type":"secret_chat"},"timestamp":1,"link":{"type":"quote","message":{"mid":"m","seq":1}}}""")!; + + message.Link!.Type.Should().BeNull(); + message.Recipient.ChatType.Should().BeNull(); + message.Link.Mid.Should().Be("m"); + } + + [Fact] + public void Message_RequiredFields_ShouldBeNonNullable_WhenMissingInJson() + { + var message = JsonSerializer.Deserialize("{}")!; + + message.Recipient.Should().NotBeNull(); + message.Timestamp.Should().Be(0); + message.Body.Should().BeNull("MAX sends no body for messages that contain only a forwarded message"); + } + + [Fact] + public void Chat_Participants_ShouldBeTypedDictionary() + { + var chat = JsonSerializer.Deserialize("""{"chat_id":-1,"type":"chat","status":"active","title":"t","last_event_time":5,"participants_count":2,"is_public":false,"participants":{"10":1730300000000,"20":1730300000001}}""")!; + + chat.Participants.Should().BeEquivalentTo(new Dictionary { [10] = 1730300000000, [20] = 1730300000001 }); + chat.LastEventTime.Should().Be(5); + chat.ParticipantsCount.Should().Be(2); + chat.Status.Should().Be(ChatStatus.Active); + } + + [Fact] + public void BotStartedUpdate_ShouldExposeNonNullableRequiredFields() + { + var update = JsonSerializer.Deserialize("""{"update_type":"bot_started","timestamp":10,"chat_id":77,"user":{"user_id":5,"first_name":"Ann","is_bot":false,"last_activity_time":1},"payload":"ref"}""")!; + + var started = update.BotStartedUpdate!; + started.ChatId.Should().Be(77); + started.User.Id.Should().Be(5); + started.Timestamp.Should().Be(10); + started.Payload.Should().Be("ref"); + } + + [Fact] + public void CallbackUpdate_ShouldExposeNonNullableCallbackFields_WithDefaultOptions() + { + var update = JsonSerializer.Deserialize("""{"update_type":"message_callback","timestamp":10,"callback":{"timestamp":11,"callback_id":"cb-1","payload":"yes","user":{"user_id":5,"first_name":"Ann","is_bot":false,"last_activity_time":1}},"message":null}""")!; + + update.Callback!.CallbackId.Should().Be("cb-1"); + update.Callback.User.Id.Should().Be(5); + update.Callback.Timestamp.Should().Be(11); + update.Message.Should().BeNull(); + } + + [Fact] + public void ChatButton_ShouldRoundTrip() + { + var button = new InlineKeyboardButton + { + Type = ButtonType.Chat, + Text = "Discuss", + ChatTitle = "Topic", + ChatDescription = "About", + StartPayload = "topic-1", + Uuid = 42 + }; + + var json = MaxJsonSerializer.Serialize(button); + json.Should().Be("""{"type":"chat","text":"Discuss","chat_title":"Topic","chat_description":"About","start_payload":"topic-1","uuid":42}"""); + + var parsed = JsonSerializer.Deserialize(json)!; + parsed.Should().BeEquivalentTo(button); + } + + [Fact] + public void InlineKeyboardAttachment_WithMalformedPayload_ShouldNotBreakMessage() + { + var body = JsonSerializer.Deserialize("""{"mid":"m","seq":1,"attachments":[{"type":"inline_keyboard","payload":{"buttons":"oops"}},{"type":"image","payload":{"photo_id":1,"url":"u","token":"t"}}]}""")!; + + body.Attachments.Should().HaveCount(2); + body.Attachments![0].Should().BeOfType().Which.Buttons.Should().BeEmpty(); + body.Attachments[1].Should().BeOfType().Which.Url.Should().Be("u"); + } + + [Fact] + public void AddChatMembersResult_ShouldExposeFailedUsers() + { + var result = JsonSerializer.Deserialize("""{"success":false,"message":"partial","failed_user_ids":[3],"failed_user_details":[{"error_code":"add.participant.privacy","user_ids":[3]}]}""")!; + + result.Success.Should().BeFalse(); + result.FailedUserIds.Should().Equal(3L); + result.FailedUserDetails.Should().ContainSingle().Which.ErrorCode.Should().Be("add.participant.privacy"); + } + + private static void AssertTypedMessageCreatedUpdate(Update update) + { + update.Type.Should().Be(UpdateType.MessageCreated); + update.Timestamp.Should().Be(1730300000000); + update.ChatId.Should().Be(-42); + update.ChatType.Should().Be(ChatType.Chat); + + var message = update.Message!; + message.Recipient.ChatType.Should().Be(ChatType.Chat); + message.Sender!.FirstName.Should().Be("Ann"); + message.Sender.LastActivityTime.Should().Be(1730300000000); + message.Stat!.Views.Should().Be(5); + + message.Link!.Type.Should().Be(MessageLinkType.Reply); + message.Link.Sender!.Id.Should().Be(2); + message.Link.Message.Mid.Should().Be("mid.original"); + message.Link.Seq.Should().Be(7); + + message.Body!.Mid.Should().Be("mid.reply"); + message.Body.Seq.Should().Be(8); + message.Body.Markup.Should().ContainSingle().Which.Type.Should().Be(MarkupType.UserMention); + + var keyboard = message.Body.Attachments![0].Should().BeOfType().Subject; + keyboard.CallbackId.Should().Be("kb-1"); + keyboard.Buttons.Should().HaveCount(2); + keyboard.Buttons[0][0].Type.Should().Be(ButtonType.Callback); + keyboard.Buttons[0][0].Payload.Should().Be("yes"); + keyboard.Buttons[0][0].Intent.Should().Be(ButtonIntent.Positive); + keyboard.Buttons[1][0].Type.Should().Be(ButtonType.Chat); + keyboard.Buttons[1][0].ChatTitle.Should().Be("Topic"); + keyboard.Buttons[1][0].StartPayload.Should().Be("topic-1"); + keyboard.Buttons[1][0].Uuid.Should().Be(123); + + message.Body.Attachments[1].Should().BeOfType().Which.Data.Should().Be("reply-keyboard-payload"); + } +} diff --git a/tests/Max.Bot.Tests/Unit/Types/CallbackQueryTests.cs b/tests/Max.Bot.Tests/Unit/Types/CallbackQueryTests.cs index 78c9ecc..5864616 100644 --- a/tests/Max.Bot.Tests/Unit/Types/CallbackQueryTests.cs +++ b/tests/Max.Bot.Tests/Unit/Types/CallbackQueryTests.cs @@ -43,7 +43,7 @@ public void CallbackQuery_ShouldDeserialize_WithNullableFields() callbackQuery.User!.Id.Should().Be(123); callbackQuery.Message.Should().BeNull(); callbackQuery.Payload.Should().BeNull(); - callbackQuery.Timestamp.Should().BeNull(); + callbackQuery.Timestamp.Should().Be(0); } [Fact] diff --git a/tests/Max.Bot.Tests/Unit/Types/MessageRecipientTests.cs b/tests/Max.Bot.Tests/Unit/Types/MessageRecipientTests.cs index 3ab3151..05883d2 100644 --- a/tests/Max.Bot.Tests/Unit/Types/MessageRecipientTests.cs +++ b/tests/Max.Bot.Tests/Unit/Types/MessageRecipientTests.cs @@ -6,6 +6,7 @@ using FluentAssertions; using Max.Bot.Networking; using Max.Bot.Types; +using Max.Bot.Types.Enums; namespace Max.Bot.Tests.Unit.Types; @@ -23,7 +24,7 @@ public void Deserialize_ShouldAcceptChatIdZero() // Assert result.Should().NotBeNull(); result!.ChatId.Should().Be(0); - result.ChatType.Should().Be("dialog"); + result.ChatType.Should().Be(ChatType.Dialog); result.UserId.Should().Be(12345); } @@ -39,7 +40,7 @@ public void Deserialize_ShouldAcceptNullChatId() // Assert result.Should().NotBeNull(); result!.ChatId.Should().BeNull(); - result.ChatType.Should().Be("dialog"); + result.ChatType.Should().Be(ChatType.Dialog); result.UserId.Should().Be(67890); } @@ -55,7 +56,7 @@ public void Deserialize_ShouldAcceptPositiveChatId() // Assert result.Should().NotBeNull(); result!.ChatId.Should().Be(987654321); - result.ChatType.Should().Be("chat"); + result.ChatType.Should().Be(ChatType.Chat); } [Fact] @@ -85,7 +86,7 @@ public void Deserialize_ShouldAcceptNullUserId() // Assert result.Should().NotBeNull(); result!.ChatId.Should().Be(123456); - result.ChatType.Should().Be("chat"); + result.ChatType.Should().Be(ChatType.Chat); result.UserId.Should().BeNull(); } @@ -96,7 +97,7 @@ public void Serialize_ShouldSerializeChatIdZero() var recipient = new MessageRecipient { ChatId = 0, - ChatType = "dialog", + ChatType = ChatType.Dialog, UserId = 12345 }; @@ -116,7 +117,7 @@ public void Serialize_ShouldNotIncludeNullChatId() // Arrange var recipient = new MessageRecipient { - ChatType = "dialog", + ChatType = ChatType.Dialog, UserId = 67890 }; @@ -137,7 +138,7 @@ public void Serialize_ShouldSerializePositiveChatId() var recipient = new MessageRecipient { ChatId = 987654321, - ChatType = "chat" + ChatType = ChatType.Chat }; // Act diff --git a/tests/Max.Bot.Tests/Unit/Types/MessageTests.cs b/tests/Max.Bot.Tests/Unit/Types/MessageTests.cs index f2aa2c8..9fffec7 100644 --- a/tests/Max.Bot.Tests/Unit/Types/MessageTests.cs +++ b/tests/Max.Bot.Tests/Unit/Types/MessageTests.cs @@ -6,6 +6,7 @@ using FluentAssertions; using Max.Bot.Networking; using Max.Bot.Types; +using Max.Bot.Types.Enums; using Xunit; namespace Max.Bot.Tests.Unit.Types; @@ -25,7 +26,7 @@ public void Deserialize_ShouldDeserializeMessage() result.Should().NotBeNull(); result!.Recipient.Should().NotBeNull(); result.Recipient!.ChatId.Should().Be(456); - result.Recipient.ChatType.Should().Be("dialog"); + result.Recipient.ChatType.Should().Be(ChatType.Dialog); result.Sender.Should().NotBeNull(); result.Sender!.Id.Should().Be(789); result.Sender.Username.Should().Be("testuser"); @@ -46,9 +47,10 @@ public void Deserialize_ShouldDeserializeMessageWithNullFields() // Assert result.Should().NotBeNull(); - result!.Recipient.Should().BeNull(); + result!.Recipient.Should().NotBeNull(); + result.Recipient.ChatType.Should().BeNull(); result.Text.Should().BeNull(); - result.Timestamp.Should().BeNull(); + result.Timestamp.Should().Be(0); } [Fact] @@ -58,7 +60,7 @@ public void Serialize_ShouldSerializeMessage() var message = new Message { Sender = new User { Id = 789, Username = "testuser" }, - Recipient = new MessageRecipient { ChatId = 456, ChatType = "dialog" }, + Recipient = new MessageRecipient { ChatId = 456, ChatType = ChatType.Dialog }, Body = new MessageBody { Mid = "mid.123", Text = "Hello" }, Timestamp = 1609459200000 }; @@ -91,7 +93,7 @@ public void Serialize_ShouldNotIncludeNullFields() json.Should().NotBeNullOrEmpty(); json.Should().Contain("\"timestamp\":1609459200000"); json.Should().NotContain("\"sender\""); - json.Should().NotContain("\"recipient\""); + json.Should().Contain("\"recipient\":{}"); json.Should().NotContain("\"text\""); } @@ -128,7 +130,7 @@ public void Deserialize_ShouldDeserializeMessageWithLink() // Assert result.Should().NotBeNull(); result!.Link.Should().NotBeNull(); - result.Link!.Type.Should().Be("reply"); + result.Link!.Type.Should().Be(MessageLinkType.Reply); result.Link.ChatId.Should().Be(456); result.Link.Sender.Should().NotBeNull(); result.Link.Sender!.Id.Should().Be(789); @@ -144,7 +146,7 @@ public void Serialize_ShouldSerializeMessageWithNewFields() var message = new Message { Sender = new User { Id = 789, Username = "testuser" }, - Recipient = new MessageRecipient { ChatId = 456, ChatType = "dialog" }, + Recipient = new MessageRecipient { ChatId = 456, ChatType = ChatType.Dialog }, Timestamp = 1609459200000, Body = new MessageBody { Mid = "mid.123", Text = "Hello", Attachments = Array.Empty() }, Stat = new MessageStat { ReadCount = 5 }, diff --git a/tests/Max.Bot.Tests/Unit/Types/UserTests.cs b/tests/Max.Bot.Tests/Unit/Types/UserTests.cs index 1ab8311..88b6ddc 100644 --- a/tests/Max.Bot.Tests/Unit/Types/UserTests.cs +++ b/tests/Max.Bot.Tests/Unit/Types/UserTests.cs @@ -44,7 +44,7 @@ public void Deserialize_ShouldDeserializeUserWithNullFields() result.Should().NotBeNull(); result!.Id.Should().Be(123); result.Username.Should().BeNull(); - result.FirstName.Should().BeNull(); + result.FirstName.Should().BeEmpty(); result.LastName.Should().BeNull(); result.IsBot.Should().BeTrue(); } diff --git a/tests/Max.Bot.Tests/Unit/Types/VideoTests.cs b/tests/Max.Bot.Tests/Unit/Types/VideoTests.cs index efddfc8..0994491 100644 --- a/tests/Max.Bot.Tests/Unit/Types/VideoTests.cs +++ b/tests/Max.Bot.Tests/Unit/Types/VideoTests.cs @@ -41,9 +41,9 @@ public void Video_ShouldDeserialize_WithNullableFields() video.Should().NotBeNull(); video.Id.Should().Be(123); video.FileId.Should().Be("video123"); - video.Width.Should().BeNull(); - video.Height.Should().BeNull(); - video.Duration.Should().BeNull(); + video.Width.Should().Be(0); + video.Height.Should().Be(0); + video.Duration.Should().Be(0); video.FileSize.Should().BeNull(); video.MimeType.Should().BeNull(); video.Url.Should().BeNull(); From d5f66f56c4764c2f546d91154451d24eb0b0f39f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 14:05:27 +0000 Subject: [PATCH 2/3] test: nullable enum properties serialize as snake_case with default options Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013pSNnawFkxH4NpFXTzqjCT --- .../Unit/Regression/ModelDeserializationTests.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/Max.Bot.Tests/Unit/Regression/ModelDeserializationTests.cs b/tests/Max.Bot.Tests/Unit/Regression/ModelDeserializationTests.cs index a27e982..f680629 100644 --- a/tests/Max.Bot.Tests/Unit/Regression/ModelDeserializationTests.cs +++ b/tests/Max.Bot.Tests/Unit/Regression/ModelDeserializationTests.cs @@ -129,6 +129,16 @@ public void ChatAdminPermissions_ShouldReadSnakeCase_WithDefaultOptions() permissions.Should().Equal(ChatAdminPermission.ReadAllMessages, ChatAdminPermission.AddRemoveMembers, ChatAdminPermission.PostEditDeleteMessage); } + [Fact] + public void NullableEnumProperties_ShouldUseSnakeCase_WithDefaultOptions() + { + var json = JsonSerializer.Serialize(new Max.Bot.Types.Requests.SendMessageRequest { Text = "hi", Format = TextFormat.Html }); + json.Should().Contain("\"format\":\"html\""); + + var action = JsonSerializer.Serialize(new Max.Bot.Types.Requests.SendChatActionRequest { Action = ChatAction.TypingOn }); + action.Should().Be("""{"action":"typing_on"}"""); + } + [Fact] public void UpdateType_ShouldReadApiString_WithDefaultOptions() { From ced5b962b087ba52309869d166285ec650b9731d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 14:27:58 +0000 Subject: [PATCH 3/3] fix: address review findings for v0.8.0-alpha - MaxJsonSerializer.Options: UpdateTypeJsonConverter precedes the generic enum converter, so unknown update types map to UpdateType.Unknown instead of failing GET /subscriptions. - Required fields tolerate an explicit JSON null (0, empty string, new object). - reply_keyboard: ReplyKeyboardAttachment, ReplyKeyboardButton and AttachmentRequest.ReplyKeyboard; unknown attachments become UnknownAttachment with the raw JSON instead of an empty DocumentAttachment. - Typed update wrappers are JSON-mapped; BotAddedUpdate.InviterId and DialogMuted/Unmuted IsMuted are derived; Update.IsChatInferred is public. - Typed VideoUrls and UpdateChatRequest.Icon; add User.IsOfficial, SetWebhookRequest.Version/SelfSignedCert, Subscription.SelfSignedCert. - Fix docs and changelog wording and footer links. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013pSNnawFkxH4NpFXTzqjCT --- CHANGELOG.md | 18 ++- README.md | 11 +- src/Max.Bot/Networking/MaxJsonSerializer.cs | 6 +- src/Max.Bot/Types/Attachment.cs | 57 +++++++- src/Max.Bot/Types/CallbackQuery.cs | 2 +- src/Max.Bot/Types/CallbackQueryUpdate.cs | 9 +- src/Max.Bot/Types/Chat.cs | 2 + src/Max.Bot/Types/ChatMember.cs | 4 + .../Converters/AttachmentJsonConverter.cs | 23 ++- .../Converters/JsonSnakeCaseEnumConverter.cs | 7 +- .../Converters/NullTolerantConverters.cs | 75 ++++++++++ src/Max.Bot/Types/Enums/ReplyButtonType.cs | 27 ++++ src/Max.Bot/Types/Image.cs | 1 + src/Max.Bot/Types/Message.cs | 6 + src/Max.Bot/Types/MessageUpdate.cs | 8 +- src/Max.Bot/Types/ReplyKeyboardButton.cs | 72 ++++++++++ .../Types/Requests/AttachmentRequest.cs | 45 ++++++ .../Types/Requests/SetWebhookRequest.cs | 12 ++ .../Types/Requests/UpdateChatRequest.cs | 2 +- src/Max.Bot/Types/Subscription.cs | 8 ++ src/Max.Bot/Types/Update.cs | 25 ++-- src/Max.Bot/Types/UpdateTypes.cs | 135 +++++++++++++++--- src/Max.Bot/Types/User.cs | 8 ++ src/Max.Bot/Types/Video.cs | 9 +- src/Max.Bot/Types/VideoUrls.cs | 65 +++++++++ .../Unit/Api/MessagesApiTests.cs | 2 +- .../Unit/Regression/IssueRegressionTests.cs | 2 +- .../Regression/ModelDeserializationTests.cs | 124 ++++++++++++++++ .../Unit/Types/AttachmentFormatTests.cs | 6 +- 29 files changed, 717 insertions(+), 54 deletions(-) create mode 100644 src/Max.Bot/Types/Converters/NullTolerantConverters.cs create mode 100644 src/Max.Bot/Types/Enums/ReplyButtonType.cs create mode 100644 src/Max.Bot/Types/ReplyKeyboardButton.cs create mode 100644 src/Max.Bot/Types/VideoUrls.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 3375960..e352adc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,7 +15,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **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` с `JsonElement` внутри); добавлен шорткат `InlineKeyboardAttachment.Buttons`. -- **Typed dictionaries**: `Chat.Participants` — `Dictionary?` (user id → время последней активности), `Image.Photos` — `Dictionary?` (было `object`). +- **Typed dictionaries and objects**: `Chat.Participants` — `Dictionary?` (user id → время последней активности), `Image.Photos` — `Dictionary?` (было `object`), `Video.Urls` — `VideoUrls` с `Mp4P1080`…`Mp4P144`, `Hls` и `BestMp4` (было `Dictionary`), `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`. @@ -24,11 +25,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `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`) — кого не удалось добавить и почему. @@ -37,9 +44,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- **Enum deserialization without library options**: `MessageLinkType`, `ChatAction`, `UploadType`, `ChatAdminPermission`, `UpdateType` и другие enum'ы не разбирались обычным `JsonSerializer` — например, `JsonSerializer.SerializeToElement("reply").Deserialize()` падал с `JsonException`. Теперь у каждого enum'а есть `[JsonConverter]`, и модели разбираются одинаково с любыми `JsonSerializerOptions`. +- **Enum deserialization without library options**: `MessageLinkType`, `ChatAction`, `UploadType`, `ChatAdminPermission`, `UpdateType` и другие enum'ы не разбирались обычным `JsonSerializer` — например, `JsonSerializer.SerializeToElement("reply").Deserialize()` падал с `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 символов, `Payload` — до 1024 (было 64, по схеме MAX). +- **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 @@ -428,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 diff --git a/README.md b/README.md index 4e7632d..fe77971 100644 --- a/README.md +++ b/README.md @@ -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`. @@ -87,7 +88,8 @@ await client.Messages.AnswerCallbackQueryAsync( Модели повторяют [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'ы. +а строковые значения API разобраны в enum'ы. Nullable остаются только поля, которые MAX действительно может не прислать: +`Message.Body` (сообщение только с пересылкой), `Message.Sender` (пост от имени канала), необязательные поля схемы. ```csharp var message = update.Message!; @@ -105,8 +107,9 @@ foreach (var keyboard in message.Body?.Attachments?.OfType("\"reply\"")` вернёт `MessageLinkType.Reply`. +Все enum'ы помечены конвертером snake_case, поэтому модели и enum'ы разбираются и обычным `JsonSerializer` с опциями +по умолчанию: `JsonSerializer.Deserialize("\"reply\"")` вернёт `MessageLinkType.Reply`. Свой +`JsonStringEnumConverter` в `JsonSerializerOptions` имеет приоритет над атрибутом типа — для данных MAX берите `MaxJsonSerializer.Options`. Если MAX пришлёт значение, неизвестное текущей версии библиотеки, nullable-поля вроде `LinkedMessage.Type` и `MessageRecipient.ChatType` станут `null`, а не уронят разбор всего апдейта. diff --git a/src/Max.Bot/Networking/MaxJsonSerializer.cs b/src/Max.Bot/Networking/MaxJsonSerializer.cs index a69e2e9..7ee12b3 100644 --- a/src/Max.Bot/Networking/MaxJsonSerializer.cs +++ b/src/Max.Bot/Networking/MaxJsonSerializer.cs @@ -21,10 +21,12 @@ public static class MaxJsonSerializer PropertyNameCaseInsensitive = true, Converters = { + // * UpdateTypeJsonConverter must precede the generic enum converter: the first matching converter wins, + // * and it maps update types unknown to this library version to UpdateType.Unknown instead of throwing. + new Types.Converters.UpdateTypeJsonConverter(), new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseLower), new UnixTimestampJsonConverter(), - new Types.Converters.AttachmentJsonConverter(), - new Types.Converters.UpdateTypeJsonConverter() + new Types.Converters.AttachmentJsonConverter() } }; diff --git a/src/Max.Bot/Types/Attachment.cs b/src/Max.Bot/Types/Attachment.cs index 365d75d..4535627 100644 --- a/src/Max.Bot/Types/Attachment.cs +++ b/src/Max.Bot/Types/Attachment.cs @@ -456,16 +456,71 @@ public class DataAttachment : Attachment public DataAttachment() => Type = AttachmentTypeNames.Data; } -internal static class AttachmentTypeNames +/// +/// Represents a custom reply keyboard (reply_keyboard) attached to a message. +/// +public class ReplyKeyboardAttachment : Attachment +{ + /// + /// Gets or sets the keyboard buttons (rows of buttons). + /// + [JsonPropertyName("buttons")] + public ReplyKeyboardButton[][] Buttons { get; set; } = Array.Empty(); + + /// + /// Initializes a new instance of the class. + /// + public ReplyKeyboardAttachment() => Type = AttachmentTypeNames.ReplyKeyboard; +} + +/// +/// Represents an attachment of a type unknown to this library version. +/// The original JSON is kept in . +/// +public class UnknownAttachment : Attachment +{ + /// + /// Gets or sets the original JSON of the attachment. + /// + [JsonIgnore] + public string RawJson { get; set; } = "{}"; +} + +/// +/// Attachment type names used by MAX Bot API in . +/// +public static class AttachmentTypeNames { + /// Image (). public const string Image = "image"; + + /// Video (). public const string Video = "video"; + + /// Audio (). public const string Audio = "audio"; + + /// File (). public const string File = "file"; + + /// Inline keyboard (). public const string InlineKeyboard = "inline_keyboard"; + + /// Reply keyboard (). + public const string ReplyKeyboard = "reply_keyboard"; + + /// Location (). public const string Location = "location"; + + /// Contact (). public const string Contact = "contact"; + + /// Sticker (). public const string Sticker = "sticker"; + + /// Link preview (). public const string Share = "share"; + + /// Reply keyboard button payload (). public const string Data = "data"; } diff --git a/src/Max.Bot/Types/CallbackQuery.cs b/src/Max.Bot/Types/CallbackQuery.cs index 84adc33..ccc984d 100644 --- a/src/Max.Bot/Types/CallbackQuery.cs +++ b/src/Max.Bot/Types/CallbackQuery.cs @@ -41,7 +41,7 @@ public class CallbackQuery /// This property maps to "payload" field from API. /// /// The callback payload, or null if not available. - [StringLength(64, ErrorMessage = "Payload must not exceed 64 characters.")] + [StringLength(1024, ErrorMessage = "Payload must not exceed 1024 characters.")] [JsonIgnore] public string? Payload { get; set; } diff --git a/src/Max.Bot/Types/CallbackQueryUpdate.cs b/src/Max.Bot/Types/CallbackQueryUpdate.cs index 130ef23..7d5d14d 100644 --- a/src/Max.Bot/Types/CallbackQueryUpdate.cs +++ b/src/Max.Bot/Types/CallbackQueryUpdate.cs @@ -1,4 +1,5 @@ using System.ComponentModel.DataAnnotations; +using System.Text.Json.Serialization; namespace Max.Bot.Types; @@ -8,10 +9,12 @@ namespace Max.Bot.Types; public class CallbackQueryUpdate { /// - /// Gets or sets the unique identifier of the update. + /// Gets or sets the identifier of the update. MAX Bot API does not send update_id, so it is 0 for API updates; + /// use for long polling. /// /// The unique identifier of the update. [Range(0, long.MaxValue, ErrorMessage = "Update ID cannot be negative.")] + [JsonPropertyName("update_id")] public long UpdateId { get; set; } /// @@ -19,18 +22,21 @@ public class CallbackQueryUpdate /// /// The timestamp when the update was created. [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] + [JsonPropertyName("timestamp")] public long Timestamp { get; set; } /// /// Gets or sets the user locale for this update. /// /// The locale code (e.g., "ru", "en"). + [JsonPropertyName("user_locale")] public string? UserLocale { get; set; } /// /// Gets or sets the callback query in this update. /// /// The callback query in this update. + [JsonPropertyName("callback")] public CallbackQuery CallbackQuery { get; set; } = null!; /// @@ -40,6 +46,7 @@ public class CallbackQueryUpdate /// MAX webhook delivers message payload at update level for message_callback, /// so consumers should read message from this property. /// + [JsonPropertyName("message")] public Message? Message { get; set; } } diff --git a/src/Max.Bot/Types/Chat.cs b/src/Max.Bot/Types/Chat.cs index 39d2687..7bff893 100644 --- a/src/Max.Bot/Types/Chat.cs +++ b/src/Max.Bot/Types/Chat.cs @@ -57,6 +57,7 @@ public class Chat /// [Range(0, long.MaxValue, ErrorMessage = "LastEventTime cannot be negative.")] [JsonPropertyName("last_event_time")] + [JsonConverter(typeof(Converters.NullAsDefaultConverter))] public long LastEventTime { get; set; } /// @@ -65,6 +66,7 @@ public class Chat /// [Range(0, int.MaxValue, ErrorMessage = "ParticipantsCount cannot be negative.")] [JsonPropertyName("participants_count")] + [JsonConverter(typeof(Converters.NullAsDefaultConverter))] public int ParticipantsCount { get; set; } /// diff --git a/src/Max.Bot/Types/ChatMember.cs b/src/Max.Bot/Types/ChatMember.cs index 84dfe15..bb54781 100644 --- a/src/Max.Bot/Types/ChatMember.cs +++ b/src/Max.Bot/Types/ChatMember.cs @@ -38,6 +38,7 @@ public class ChatMember /// Gets or sets the user's first name. /// [JsonPropertyName("first_name")] + [JsonConverter(typeof(Converters.NullAsEmptyStringConverter))] public string FirstName { get; set; } = string.Empty; /// @@ -56,6 +57,7 @@ public class ChatMember /// Gets or sets the user's last activity time (Unix timestamp in milliseconds). /// [JsonPropertyName("last_activity_time")] + [JsonConverter(typeof(Converters.NullAsDefaultConverter))] public long LastActivityTime { get; set; } /// @@ -68,6 +70,7 @@ public class ChatMember /// Gets or sets the user's last access time in this chat. /// [JsonPropertyName("last_access_time")] + [JsonConverter(typeof(Converters.NullAsDefaultConverter))] public long LastAccessTime { get; set; } /// @@ -86,6 +89,7 @@ public class ChatMember /// Gets or sets the time when the user joined the chat (Unix timestamp in seconds). /// [JsonPropertyName("join_time")] + [JsonConverter(typeof(Converters.NullAsDefaultConverter))] public long JoinTime { get; set; } /// diff --git a/src/Max.Bot/Types/Converters/AttachmentJsonConverter.cs b/src/Max.Bot/Types/Converters/AttachmentJsonConverter.cs index b97a357..59f1206 100644 --- a/src/Max.Bot/Types/Converters/AttachmentJsonConverter.cs +++ b/src/Max.Bot/Types/Converters/AttachmentJsonConverter.cs @@ -87,8 +87,17 @@ public class AttachmentJsonConverter : JsonConverter return DeserializeMerged(root, typeString, null, options); } - // Fallback for unknown types — use DocumentAttachment as it has the most generic fields (url, token) - return DeserializeMerged(root, typeString, null, options); + if (IsType(typeString, AttachmentTypeNames.ReplyKeyboard)) + { + return DeserializeMerged(root, typeString, null, options); + } + + // Types unknown to this library version keep their raw JSON. + return new UnknownAttachment + { + Type = typeString ?? string.Empty, + RawJson = root.GetRawText() + }; } /// @@ -125,6 +134,16 @@ public override void Write(Utf8JsonWriter writer, Attachment value, JsonSerializ break; case DataAttachment dataAttachment: JsonSerializer.Serialize(writer, dataAttachment, options); + break; + case ReplyKeyboardAttachment replyKeyboardAttachment: + JsonSerializer.Serialize(writer, replyKeyboardAttachment, options); + break; + case UnknownAttachment unknownAttachment: + using (var document = JsonDocument.Parse(unknownAttachment.RawJson)) + { + document.RootElement.WriteTo(writer); + } + break; default: throw new JsonException($"Unknown attachment type: {value.GetType()}"); diff --git a/src/Max.Bot/Types/Converters/JsonSnakeCaseEnumConverter.cs b/src/Max.Bot/Types/Converters/JsonSnakeCaseEnumConverter.cs index fe5ac52..c94ec6c 100644 --- a/src/Max.Bot/Types/Converters/JsonSnakeCaseEnumConverter.cs +++ b/src/Max.Bot/Types/Converters/JsonSnakeCaseEnumConverter.cs @@ -8,9 +8,10 @@ namespace Max.Bot.Types.Converters; /// and reads both snake_case and PascalCase names case-insensitively. /// /// -/// Every enum of the library is marked with this converter, so enum values are (de)serialized correctly with any -/// — including JsonSerializer.Deserialize<MessageLinkType>("\"reply\"") -/// with default options — and not only with . +/// Every enum of the library is marked with this converter, so enum values are (de)serialized correctly not only with +/// but also with default options, for example +/// JsonSerializer.Deserialize<MessageLinkType>("\"reply\""). An enum converter registered in +/// takes precedence over this attribute. /// An unknown string value throws ; library response models use /// where MAX may add new values. /// diff --git a/src/Max.Bot/Types/Converters/NullTolerantConverters.cs b/src/Max.Bot/Types/Converters/NullTolerantConverters.cs new file mode 100644 index 0000000..c9ce500 --- /dev/null +++ b/src/Max.Bot/Types/Converters/NullTolerantConverters.cs @@ -0,0 +1,75 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Max.Bot.Types.Converters; + +/// +/// Reads a JSON null as default(T) for a non-nullable value-type property that MAX API documents as required, +/// so an unexpected null does not break deserialization of the whole response or update. +/// +/// The value type. +public sealed class NullAsDefaultConverter : JsonConverter + where T : struct +{ + /// + public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.TokenType == JsonTokenType.Null + ? default + : JsonSerializer.Deserialize(ref reader, options); + } + + /// + public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) + { + JsonSerializer.Serialize(writer, value, options); + } +} + +/// +/// Reads a JSON null as for a non-nullable string property that MAX API documents as required. +/// +public sealed class NullAsEmptyStringConverter : JsonConverter +{ + /// + public override bool HandleNull => true; + + /// + public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.TokenType == JsonTokenType.Null + ? string.Empty + : reader.GetString() ?? string.Empty; + } + + /// + public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) + { + writer.WriteStringValue(value ?? string.Empty); + } +} + +/// +/// Reads a JSON null as a new empty for a non-nullable object property that MAX API documents as required. +/// +/// The object type. +public sealed class NullAsNewConverter : JsonConverter + where T : class, new() +{ + /// + public override bool HandleNull => true; + + /// + public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.TokenType == JsonTokenType.Null + ? new T() + : JsonSerializer.Deserialize(ref reader, options) ?? new T(); + } + + /// + public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) + { + JsonSerializer.Serialize(writer, value ?? new T(), options); + } +} diff --git a/src/Max.Bot/Types/Enums/ReplyButtonType.cs b/src/Max.Bot/Types/Enums/ReplyButtonType.cs new file mode 100644 index 0000000..c743faa --- /dev/null +++ b/src/Max.Bot/Types/Enums/ReplyButtonType.cs @@ -0,0 +1,27 @@ +using System.Text.Json.Serialization; +using Max.Bot.Types.Converters; + +namespace Max.Bot.Types.Enums; + +/// +/// Represents the type of a reply keyboard button (). +/// +[JsonConverter(typeof(JsonSnakeCaseEnumConverter))] +public enum ReplyButtonType +{ + /// + /// Sends a message on behalf of the user; the button payload arrives as . + /// Serialized as "message". + /// + Message, + + /// + /// Sends the user's geo location. Serialized as "user_geo_location". + /// + UserGeoLocation, + + /// + /// Sends the user's contact. Serialized as "user_contact". + /// + UserContact +} diff --git a/src/Max.Bot/Types/Image.cs b/src/Max.Bot/Types/Image.cs index 9b0ba03..1058413 100644 --- a/src/Max.Bot/Types/Image.cs +++ b/src/Max.Bot/Types/Image.cs @@ -18,6 +18,7 @@ public class Image /// Gets or sets the URL of the image. Always sent by MAX API. /// [JsonPropertyName("url")] + [JsonConverter(typeof(Converters.NullAsEmptyStringConverter))] public string Url { get; set; } = string.Empty; /// diff --git a/src/Max.Bot/Types/Message.cs b/src/Max.Bot/Types/Message.cs index 038cee0..61ceace 100644 --- a/src/Max.Bot/Types/Message.cs +++ b/src/Max.Bot/Types/Message.cs @@ -29,6 +29,7 @@ public class Message /// Can be a user or a chat. Always present in MAX API responses. /// [JsonPropertyName("recipient")] + [JsonConverter(typeof(Converters.NullAsNewConverter))] public MessageRecipient Recipient { get; set; } = new(); /// @@ -37,6 +38,7 @@ public class Message /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] [JsonPropertyName("timestamp")] + [JsonConverter(typeof(Converters.NullAsDefaultConverter))] public long Timestamp { get; set; } /// @@ -126,6 +128,7 @@ public class LinkedMessage /// Note: In API this is called "message" but contains only MessageBody fields, not full Message. /// [JsonPropertyName("message")] + [JsonConverter(typeof(Converters.NullAsNewConverter))] public MessageBody Message { get; set; } = new(); /// @@ -157,6 +160,7 @@ public class MessageBody /// Gets or sets the message ID. /// [JsonPropertyName("mid")] + [JsonConverter(typeof(Converters.NullAsEmptyStringConverter))] public string Mid { get; set; } = string.Empty; /// @@ -165,6 +169,7 @@ public class MessageBody /// [Range(0, long.MaxValue, ErrorMessage = "Sequence number cannot be negative.")] [JsonPropertyName("seq")] + [JsonConverter(typeof(Converters.NullAsDefaultConverter))] public long Seq { get; set; } /// @@ -204,6 +209,7 @@ public class MessageStat /// [Range(0, int.MaxValue, ErrorMessage = "Views cannot be negative.")] [JsonPropertyName("views")] + [JsonConverter(typeof(Converters.NullAsDefaultConverter))] public int Views { get; set; } } diff --git a/src/Max.Bot/Types/MessageUpdate.cs b/src/Max.Bot/Types/MessageUpdate.cs index fe05c58..6da1648 100644 --- a/src/Max.Bot/Types/MessageUpdate.cs +++ b/src/Max.Bot/Types/MessageUpdate.cs @@ -1,4 +1,5 @@ using System.ComponentModel.DataAnnotations; +using System.Text.Json.Serialization; namespace Max.Bot.Types; @@ -8,10 +9,12 @@ namespace Max.Bot.Types; public class MessageUpdate { /// - /// Gets or sets the unique identifier of the update. + /// Gets or sets the identifier of the update. MAX Bot API does not send update_id, so it is 0 for API updates; + /// use for long polling. /// /// The unique identifier of the update. [Range(0, long.MaxValue, ErrorMessage = "Update ID cannot be negative.")] + [JsonPropertyName("update_id")] public long UpdateId { get; set; } /// @@ -19,18 +22,21 @@ public class MessageUpdate /// /// The timestamp when the update was created. [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] + [JsonPropertyName("timestamp")] public long Timestamp { get; set; } /// /// Gets or sets the user locale for this update. /// /// The locale code (e.g., "ru", "en"). + [JsonPropertyName("user_locale")] public string? UserLocale { get; set; } /// /// Gets or sets the message in this update. /// /// The message in this update. + [JsonPropertyName("message")] public Message Message { get; set; } = null!; } diff --git a/src/Max.Bot/Types/ReplyKeyboardButton.cs b/src/Max.Bot/Types/ReplyKeyboardButton.cs new file mode 100644 index 0000000..67ea3e4 --- /dev/null +++ b/src/Max.Bot/Types/ReplyKeyboardButton.cs @@ -0,0 +1,72 @@ +using System.ComponentModel.DataAnnotations; +using System.Text.Json.Serialization; +using Max.Bot.Types.Enums; + +namespace Max.Bot.Types; + +/// +/// Represents a button of a reply keyboard (). +/// +public class ReplyKeyboardButton +{ + /// + /// Gets or sets the type of the button. + /// + [JsonPropertyName("type")] + public ReplyButtonType Type { get; set; } + + /// + /// Gets or sets the visible text of the button. + /// + [Required(ErrorMessage = "Text is required.")] + [StringLength(128, MinimumLength = 1, ErrorMessage = "Text must be between 1 and 128 characters.")] + [JsonPropertyName("text")] + public string Text { get; set; } = string.Empty; + + /// + /// Gets or sets the payload sent with the message when a button is pressed. + /// + [StringLength(1024, ErrorMessage = "Payload must not exceed 1024 characters.")] + [JsonPropertyName("payload")] + public string? Payload { get; set; } + + /// + /// Gets or sets the intent of a button. Affects how the client displays it. + /// + [JsonPropertyName("intent")] + public ButtonIntent? Intent { get; set; } + + /// + /// Gets or sets a value indicating whether a button sends the location + /// without asking the user for confirmation. + /// + [JsonPropertyName("quick")] + public bool? Quick { get; set; } + + /// + /// Creates a button that sends a message with the given payload. + /// + /// The visible text of the button. + /// The payload delivered to the bot as . + /// The optional intent of the button. + /// A new reply keyboard button. + public static ReplyKeyboardButton Message(string text, string? payload = null, ButtonIntent? intent = null) => + new() { Type = ReplyButtonType.Message, Text = text, Payload = payload, Intent = intent }; + + /// + /// Creates a button that sends the user's geo location. + /// + /// The visible text of the button. + /// true to send the location without confirmation. + /// A new reply keyboard button. + public static ReplyKeyboardButton GeoLocation(string text, bool? quick = null) => + new() { Type = ReplyButtonType.UserGeoLocation, Text = text, Quick = quick }; + + /// + /// Creates a button that sends the user's contact. + /// + /// The visible text of the button. + /// A new reply keyboard button. + public static ReplyKeyboardButton Contact(string text) => + new() { Type = ReplyButtonType.UserContact, Text = text }; +} diff --git a/src/Max.Bot/Types/Requests/AttachmentRequest.cs b/src/Max.Bot/Types/Requests/AttachmentRequest.cs index 96944ae..5de5c2b 100644 --- a/src/Max.Bot/Types/Requests/AttachmentRequest.cs +++ b/src/Max.Bot/Types/Requests/AttachmentRequest.cs @@ -45,6 +45,25 @@ public class AttachmentRequest [JsonPropertyName("longitude")] public double? Longitude { get; set; } + /// + /// Gets or sets the buttons of a reply_keyboard attachment (rows of buttons). Use to create it. + /// + [JsonPropertyName("buttons")] + public ReplyKeyboardButton[][]? Buttons { get; set; } + + /// + /// Gets or sets a value indicating whether a reply_keyboard is shown in a group chat only to the user + /// who mentioned the bot or replied to it. + /// + [JsonPropertyName("direct")] + public bool? Direct { get; set; } + + /// + /// Gets or sets the identifier of the only chat participant who sees a reply_keyboard. + /// + [JsonPropertyName("direct_user_id")] + public long? DirectUserId { get; set; } + /// /// Creates an image attachment from any public image URL. MAX downloads the image itself. /// @@ -270,6 +289,32 @@ public static AttachmentRequest Keyboard(InlineKeyboard keyboard) }; } + /// + /// Creates a reply keyboard attachment (reply_keyboard): buttons shown instead of the user's keyboard. + /// + /// The rows of buttons. + /// true to show the keyboard in a group chat only to the user who mentioned the bot or replied to it. + /// The identifier of the only chat participant who sees the keyboard. + /// The attachment request. + public static AttachmentRequest ReplyKeyboard(ReplyKeyboardButton[][] buttons, bool? direct = null, long? directUserId = null) + { + ArgumentNullException.ThrowIfNull(buttons); + + var rows = buttons.Select(row => row ?? Array.Empty()).Where(row => row.Length > 0).ToArray(); + if (rows.Length == 0) + { + throw new ArgumentException("Reply keyboard must contain at least one button.", nameof(buttons)); + } + + return new AttachmentRequest + { + Type = AttachmentTypeNames.ReplyKeyboard, + Buttons = rows, + Direct = direct, + DirectUserId = directUserId + }; + } + private static AttachmentRequest CreateTokenAttachment(string type, string token) { ArgumentException.ThrowIfNullOrWhiteSpace(token); diff --git a/src/Max.Bot/Types/Requests/SetWebhookRequest.cs b/src/Max.Bot/Types/Requests/SetWebhookRequest.cs index ede2a50..aab8263 100644 --- a/src/Max.Bot/Types/Requests/SetWebhookRequest.cs +++ b/src/Max.Bot/Types/Requests/SetWebhookRequest.cs @@ -32,6 +32,18 @@ public class SetWebhookRequest /// The secret string (5-256 characters, A-Z, a-z, 0-9, hyphen, underscore). [JsonPropertyName("secret")] public string? Secret { get; set; } + + /// + /// Gets or sets the X.509 certificate in PEM format. Needed only if the webhook endpoint uses a self-signed certificate. + /// + [JsonPropertyName("self_signed_cert")] + public string? SelfSignedCert { get; set; } + + /// + /// Gets or sets the Bot API version that defines the model representation of webhook updates (for example, "0.0.30"). + /// + [JsonPropertyName("version")] + public string? Version { get; set; } } diff --git a/src/Max.Bot/Types/Requests/UpdateChatRequest.cs b/src/Max.Bot/Types/Requests/UpdateChatRequest.cs index 6f4dfff..b5307fd 100644 --- a/src/Max.Bot/Types/Requests/UpdateChatRequest.cs +++ b/src/Max.Bot/Types/Requests/UpdateChatRequest.cs @@ -17,7 +17,7 @@ public class UpdateChatRequest /// If null, the icon is not changed. /// [JsonPropertyName("icon")] - public object? Icon { get; set; } + public ImageAttachmentRequestPayload? Icon { get; set; } /// /// Gets or sets the chat title. diff --git a/src/Max.Bot/Types/Subscription.cs b/src/Max.Bot/Types/Subscription.cs index 8b78278..9265b8d 100644 --- a/src/Max.Bot/Types/Subscription.cs +++ b/src/Max.Bot/Types/Subscription.cs @@ -15,6 +15,7 @@ public class Subscription /// /// The webhook URL. [JsonPropertyName("url")] + [JsonConverter(typeof(Converters.NullAsEmptyStringConverter))] public string Url { get; set; } = string.Empty; /// @@ -31,6 +32,12 @@ public class Subscription [JsonPropertyName("secret")] public string? Secret { get; set; } + /// + /// Gets or sets the self-signed X.509 certificate (PEM) of the webhook endpoint, if one was provided. + /// + [JsonPropertyName("self_signed_cert")] + public string? SelfSignedCert { get; set; } + /// /// Gets or sets the timestamp when the subscription was created. /// @@ -51,6 +58,7 @@ public class Subscription /// Gets or sets the Unix time (milliseconds) when the subscription was created, as returned by MAX API. /// [JsonPropertyName("time")] + [JsonConverter(typeof(Converters.NullAsDefaultConverter))] public long Time { get; set; } /// diff --git a/src/Max.Bot/Types/Update.cs b/src/Max.Bot/Types/Update.cs index 71b281a..058ab49 100644 --- a/src/Max.Bot/Types/Update.cs +++ b/src/Max.Bot/Types/Update.cs @@ -14,7 +14,8 @@ namespace Max.Bot.Types; public class Update { /// - /// Gets or sets the unique identifier of the update. + /// Gets or sets the identifier of the update. MAX Bot API does not send update_id, so it is 0 for API updates; + /// use for long polling. /// [Range(0, long.MaxValue, ErrorMessage = "Update ID cannot be negative.")] [JsonPropertyName("update_id")] @@ -54,7 +55,7 @@ public class Update /// /// Gets or sets the message in this update. - /// Present in: message_created, message_edited, message_removed, message_chat_created. + /// Present in: message_created, message_edited and message_callback (can be null if the message was deleted). /// [JsonPropertyName("message")] public Message? Message { get; set; } @@ -177,7 +178,7 @@ public ChatType? ChatType /// /// Gets or sets the new chat title. - /// Present in: chat_title_changed, message_chat_created. + /// Present in: chat_title_changed. For message_chat_created use Chat.Title. /// [JsonIgnore] public string? Title { get; set; } @@ -197,17 +198,19 @@ public ChatType? ChatType public long? MutedUntil { get; set; } /// - /// Gets or sets a value indicating whether was built from message.recipient - /// rather than received from MAX API. + /// Gets a value indicating whether is a partial chat built from message.recipient + /// rather than received from MAX API. A partial chat has only and ; + /// other fields keep their defaults — request the full chat with GetChatAsync if needed. /// [JsonIgnore] - internal bool IsChatInferred { get; private set; } + public bool IsChatInferred { get; private set; } /// - /// Gets or sets a value indicating whether was taken from message.recipient. + /// Gets a value indicating whether was taken from message.recipient or the chat object + /// rather than from the root chat_id field. /// [JsonIgnore] - internal bool IsChatIdInferred { get; private set; } + public bool IsChatIdInferred { get; private set; } /// /// Fills and from values inferred from message.recipient @@ -350,7 +353,7 @@ public BotAddedUpdate? BotAddedUpdate Chat = Chat, ChatId = ChatId ?? Chat?.ChatId ?? 0, User = User ?? new User(), - InviterId = InviterId, + InviterId = InviterId ?? User?.Id, IsChannel = IsChannel ?? false }; } @@ -511,7 +514,7 @@ public DialogMutedUpdate? DialogMutedUpdate UpdateId = UpdateId, Timestamp = Timestamp, ChatId = ChatId ?? 0, - IsMuted = IsMuted, + IsMuted = IsMuted ?? true, MutedUntil = MutedUntil ?? 0, User = User ?? new User(), UserLocale = UserLocale @@ -535,7 +538,7 @@ public DialogUnmutedUpdate? DialogUnmutedUpdate UpdateId = UpdateId, Timestamp = Timestamp, ChatId = ChatId ?? 0, - IsMuted = IsMuted, + IsMuted = IsMuted ?? false, User = User ?? new User(), UserLocale = UserLocale }; diff --git a/src/Max.Bot/Types/UpdateTypes.cs b/src/Max.Bot/Types/UpdateTypes.cs index 80d03d6..04bdb81 100644 --- a/src/Max.Bot/Types/UpdateTypes.cs +++ b/src/Max.Bot/Types/UpdateTypes.cs @@ -1,4 +1,5 @@ using System.ComponentModel.DataAnnotations; +using System.Text.Json.Serialization; namespace Max.Bot.Types; @@ -8,25 +9,30 @@ namespace Max.Bot.Types; public class MessageEditedUpdate { /// - /// Gets or sets the unique identifier of the update. + /// Gets or sets the identifier of the update. MAX Bot API does not send update_id, so it is 0 for API updates; + /// use for long polling. /// [Range(0, long.MaxValue, ErrorMessage = "Update ID cannot be negative.")] + [JsonPropertyName("update_id")] public long UpdateId { get; set; } /// /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] + [JsonPropertyName("timestamp")] public long Timestamp { get; set; } /// /// Gets or sets the user locale for this update. /// + [JsonPropertyName("user_locale")] public string? UserLocale { get; set; } /// /// Gets or sets the edited message. /// + [JsonPropertyName("message")] public Message Message { get; set; } = null!; } @@ -36,40 +42,48 @@ public class MessageEditedUpdate public class MessageRemovedUpdate { /// - /// Gets or sets the unique identifier of the update. + /// Gets or sets the identifier of the update. MAX Bot API does not send update_id, so it is 0 for API updates; + /// use for long polling. /// [Range(0, long.MaxValue, ErrorMessage = "Update ID cannot be negative.")] + [JsonPropertyName("update_id")] public long UpdateId { get; set; } /// /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] + [JsonPropertyName("timestamp")] public long Timestamp { get; set; } /// /// Gets or sets the user locale for this update. /// + [JsonPropertyName("user_locale")] public string? UserLocale { get; set; } /// /// Gets or sets the removed message. /// + [JsonPropertyName("message")] public Message? Message { get; set; } /// /// Gets or sets the identifier of the removed message (message_id). /// + [JsonPropertyName("message_id")] public string MessageId { get; set; } = string.Empty; /// /// Gets or sets the chat identifier where the message was removed. /// + [JsonPropertyName("chat_id")] public long ChatId { get; set; } /// /// Gets or sets the identifier of the user who removed the message. /// + [JsonPropertyName("user_id")] public long UserId { get; set; } } @@ -80,40 +94,48 @@ public class MessageRemovedUpdate public class BotAddedUpdate { /// - /// Gets or sets the unique identifier of the update. + /// Gets or sets the identifier of the update. MAX Bot API does not send update_id, so it is 0 for API updates; + /// use for long polling. /// [Range(0, long.MaxValue, ErrorMessage = "Update ID cannot be negative.")] + [JsonPropertyName("update_id")] public long UpdateId { get; set; } /// /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] + [JsonPropertyName("timestamp")] public long Timestamp { get; set; } /// /// Gets or sets the chat where the bot was added. /// + [JsonPropertyName("chat")] public Chat? Chat { get; set; } /// - /// Gets or sets the user (bot) that was added. + /// Gets or sets the user who added the bot to the chat. /// + [JsonPropertyName("user")] public User User { get; set; } = new(); /// - /// Gets or sets the ID of the user who invited the bot. + /// Gets or sets the ID of the user who added the bot. MAX sends it as , so it equals User.Id. /// + [JsonPropertyName("inviter_id")] public long? InviterId { get; set; } /// /// Gets or sets the identifier of the chat the bot was added to. /// + [JsonPropertyName("chat_id")] public long ChatId { get; set; } /// /// Gets or sets a value indicating whether the bot was added to a channel. /// + [JsonPropertyName("is_channel")] public bool IsChannel { get; set; } } @@ -124,35 +146,42 @@ public class BotAddedUpdate public class BotRemovedUpdate { /// - /// Gets or sets the unique identifier of the update. + /// Gets or sets the identifier of the update. MAX Bot API does not send update_id, so it is 0 for API updates; + /// use for long polling. /// [Range(0, long.MaxValue, ErrorMessage = "Update ID cannot be negative.")] + [JsonPropertyName("update_id")] public long UpdateId { get; set; } /// /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] + [JsonPropertyName("timestamp")] public long Timestamp { get; set; } /// /// Gets or sets the chat where the bot was removed. /// + [JsonPropertyName("chat")] public Chat? Chat { get; set; } /// - /// Gets or sets the user (bot) that was removed. + /// Gets or sets the user who removed the bot from the chat. /// + [JsonPropertyName("user")] public User User { get; set; } = new(); /// /// Gets or sets the identifier of the chat the bot was removed from. /// + [JsonPropertyName("chat_id")] public long ChatId { get; set; } /// /// Gets or sets a value indicating whether the bot was removed from a channel. /// + [JsonPropertyName("is_channel")] public bool IsChannel { get; set; } } @@ -163,35 +192,42 @@ public class BotRemovedUpdate public class BotStartedUpdate { /// - /// Gets or sets the unique identifier of the update. + /// Gets or sets the identifier of the update. MAX Bot API does not send update_id, so it is 0 for API updates; + /// use for long polling. /// [Range(0, long.MaxValue, ErrorMessage = "Update ID cannot be negative.")] + [JsonPropertyName("update_id")] public long UpdateId { get; set; } /// /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] + [JsonPropertyName("timestamp")] public long Timestamp { get; set; } /// /// Gets or sets the chat ID where the bot was started. /// + [JsonPropertyName("chat_id")] public long ChatId { get; set; } /// /// Gets or sets the user who started the bot. /// + [JsonPropertyName("user")] public User User { get; set; } = new(); /// /// Gets or sets the user locale. /// + [JsonPropertyName("user_locale")] public string? UserLocale { get; set; } /// /// Gets or sets the deep-link payload. /// + [JsonPropertyName("payload")] public string? Payload { get; set; } } @@ -202,30 +238,36 @@ public class BotStartedUpdate public class BotStoppedUpdate { /// - /// Gets or sets the unique identifier of the update. + /// Gets or sets the identifier of the update. MAX Bot API does not send update_id, so it is 0 for API updates; + /// use for long polling. /// [Range(0, long.MaxValue, ErrorMessage = "Update ID cannot be negative.")] + [JsonPropertyName("update_id")] public long UpdateId { get; set; } /// /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] + [JsonPropertyName("timestamp")] public long Timestamp { get; set; } /// /// Gets or sets the chat ID where the bot was stopped. /// + [JsonPropertyName("chat_id")] public long ChatId { get; set; } /// /// Gets or sets the user who stopped the bot. /// + [JsonPropertyName("user")] public User User { get; set; } = new(); /// /// Gets or sets the user locale. /// + [JsonPropertyName("user_locale")] public string? UserLocale { get; set; } } @@ -236,40 +278,48 @@ public class BotStoppedUpdate public class UserAddedUpdate { /// - /// Gets or sets the unique identifier of the update. + /// Gets or sets the identifier of the update. MAX Bot API does not send update_id, so it is 0 for API updates; + /// use for long polling. /// [Range(0, long.MaxValue, ErrorMessage = "Update ID cannot be negative.")] + [JsonPropertyName("update_id")] public long UpdateId { get; set; } /// /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] + [JsonPropertyName("timestamp")] public long Timestamp { get; set; } /// /// Gets or sets the chat where the user was added. /// + [JsonPropertyName("chat")] public Chat? Chat { get; set; } /// /// Gets or sets the user that was added. /// + [JsonPropertyName("user")] public User User { get; set; } = new(); /// /// Gets or sets the ID of the user who invited the user. /// + [JsonPropertyName("inviter_id")] public long? InviterId { get; set; } /// /// Gets or sets the identifier of the chat the user was added to. /// + [JsonPropertyName("chat_id")] public long ChatId { get; set; } /// /// Gets or sets a value indicating whether the user was added to a channel. /// + [JsonPropertyName("is_channel")] public bool IsChannel { get; set; } } @@ -280,40 +330,48 @@ public class UserAddedUpdate public class UserRemovedUpdate { /// - /// Gets or sets the unique identifier of the update. + /// Gets or sets the identifier of the update. MAX Bot API does not send update_id, so it is 0 for API updates; + /// use for long polling. /// [Range(0, long.MaxValue, ErrorMessage = "Update ID cannot be negative.")] + [JsonPropertyName("update_id")] public long UpdateId { get; set; } /// /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] + [JsonPropertyName("timestamp")] public long Timestamp { get; set; } /// /// Gets or sets the chat where the user was removed. /// + [JsonPropertyName("chat")] public Chat? Chat { get; set; } /// /// Gets or sets the user that was removed. /// + [JsonPropertyName("user")] public User User { get; set; } = new(); /// /// Gets or sets the identifier of the chat the user was removed from. /// + [JsonPropertyName("chat_id")] public long ChatId { get; set; } /// /// Gets or sets the identifier of the administrator who removed the user. /// + [JsonPropertyName("admin_id")] public long? AdminId { get; set; } /// /// Gets or sets a value indicating whether the user was removed from a channel. /// + [JsonPropertyName("is_channel")] public bool IsChannel { get; set; } } @@ -324,35 +382,42 @@ public class UserRemovedUpdate public class ChatTitleChangedUpdate { /// - /// Gets or sets the unique identifier of the update. + /// Gets or sets the identifier of the update. MAX Bot API does not send update_id, so it is 0 for API updates; + /// use for long polling. /// [Range(0, long.MaxValue, ErrorMessage = "Update ID cannot be negative.")] + [JsonPropertyName("update_id")] public long UpdateId { get; set; } /// /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] + [JsonPropertyName("timestamp")] public long Timestamp { get; set; } /// /// Gets or sets the chat with the new title. /// + [JsonPropertyName("chat")] public Chat? Chat { get; set; } /// /// Gets or sets the user who changed the title. /// + [JsonPropertyName("user")] public User User { get; set; } = new(); /// /// Gets or sets the identifier of the chat whose title changed. /// + [JsonPropertyName("chat_id")] public long ChatId { get; set; } /// /// Gets or sets the new chat title. /// + [JsonPropertyName("title")] public string Title { get; set; } = string.Empty; } @@ -363,40 +428,48 @@ public class ChatTitleChangedUpdate public class DialogMutedUpdate { /// - /// Gets or sets the unique identifier of the update. + /// Gets or sets the identifier of the update. MAX Bot API does not send update_id, so it is 0 for API updates; + /// use for long polling. /// [Range(0, long.MaxValue, ErrorMessage = "Update ID cannot be negative.")] + [JsonPropertyName("update_id")] public long UpdateId { get; set; } /// /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] + [JsonPropertyName("timestamp")] public long Timestamp { get; set; } /// /// Gets or sets the chat ID of the muted dialog. /// + [JsonPropertyName("chat_id")] public long ChatId { get; set; } /// /// Gets or sets whether the dialog is muted. /// + [JsonPropertyName("is_muted")] public bool? IsMuted { get; set; } /// /// Gets or sets the time (Unix milliseconds) until which the dialog is muted. /// + [JsonPropertyName("muted_until")] public long MutedUntil { get; set; } /// /// Gets or sets the user who muted the dialog. /// + [JsonPropertyName("user")] public User User { get; set; } = new(); /// /// Gets or sets the user locale. /// + [JsonPropertyName("user_locale")] public string? UserLocale { get; set; } } @@ -407,35 +480,42 @@ public class DialogMutedUpdate public class DialogUnmutedUpdate { /// - /// Gets or sets the unique identifier of the update. + /// Gets or sets the identifier of the update. MAX Bot API does not send update_id, so it is 0 for API updates; + /// use for long polling. /// [Range(0, long.MaxValue, ErrorMessage = "Update ID cannot be negative.")] + [JsonPropertyName("update_id")] public long UpdateId { get; set; } /// /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] + [JsonPropertyName("timestamp")] public long Timestamp { get; set; } /// /// Gets or sets the chat ID of the unmuted dialog. /// + [JsonPropertyName("chat_id")] public long ChatId { get; set; } /// /// Gets or sets whether the dialog is muted. /// + [JsonPropertyName("is_muted")] public bool? IsMuted { get; set; } /// /// Gets or sets the user who unmuted the dialog. /// + [JsonPropertyName("user")] public User User { get; set; } = new(); /// /// Gets or sets the user locale. /// + [JsonPropertyName("user_locale")] public string? UserLocale { get; set; } } @@ -446,30 +526,36 @@ public class DialogUnmutedUpdate public class DialogClearedUpdate { /// - /// Gets or sets the unique identifier of the update. + /// Gets or sets the identifier of the update. MAX Bot API does not send update_id, so it is 0 for API updates; + /// use for long polling. /// [Range(0, long.MaxValue, ErrorMessage = "Update ID cannot be negative.")] + [JsonPropertyName("update_id")] public long UpdateId { get; set; } /// /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] + [JsonPropertyName("timestamp")] public long Timestamp { get; set; } /// /// Gets or sets the chat ID of the cleared dialog. /// + [JsonPropertyName("chat_id")] public long ChatId { get; set; } /// /// Gets or sets the user who cleared the dialog. /// + [JsonPropertyName("user")] public User User { get; set; } = new(); /// /// Gets or sets the user locale. /// + [JsonPropertyName("user_locale")] public string? UserLocale { get; set; } } @@ -480,30 +566,36 @@ public class DialogClearedUpdate public class DialogRemovedUpdate { /// - /// Gets or sets the unique identifier of the update. + /// Gets or sets the identifier of the update. MAX Bot API does not send update_id, so it is 0 for API updates; + /// use for long polling. /// [Range(0, long.MaxValue, ErrorMessage = "Update ID cannot be negative.")] + [JsonPropertyName("update_id")] public long UpdateId { get; set; } /// /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] + [JsonPropertyName("timestamp")] public long Timestamp { get; set; } /// /// Gets or sets the chat ID of the removed dialog. /// + [JsonPropertyName("chat_id")] public long ChatId { get; set; } /// /// Gets or sets the user who removed the dialog. /// + [JsonPropertyName("user")] public User User { get; set; } = new(); /// /// Gets or sets the user locale. /// + [JsonPropertyName("user_locale")] public string? UserLocale { get; set; } } @@ -514,45 +606,54 @@ public class DialogRemovedUpdate public class MessageChatCreatedUpdate { /// - /// Gets or sets the unique identifier of the update. + /// Gets or sets the identifier of the update. MAX Bot API does not send update_id, so it is 0 for API updates; + /// use for long polling. /// [Range(0, long.MaxValue, ErrorMessage = "Update ID cannot be negative.")] + [JsonPropertyName("update_id")] public long UpdateId { get; set; } /// /// Gets or sets the timestamp of the update (Unix timestamp in milliseconds). /// [Range(0, long.MaxValue, ErrorMessage = "Timestamp cannot be negative.")] + [JsonPropertyName("timestamp")] public long Timestamp { get; set; } /// /// Gets or sets the user locale. /// + [JsonPropertyName("user_locale")] public string? UserLocale { get; set; } /// /// Gets or sets the message that created the chat. /// + [JsonPropertyName("message")] public Message? Message { get; set; } /// /// Gets or sets the created chat. /// + [JsonPropertyName("chat")] public Chat Chat { get; set; } = new(); /// /// Gets or sets the identifier of the created chat. /// + [JsonPropertyName("chat_id")] public long ChatId { get; set; } /// /// Gets or sets the identifier of the message where the button was clicked. /// + [JsonPropertyName("message_id")] public string MessageId { get; set; } = string.Empty; /// /// Gets or sets the payload from the chat button (start_payload). /// + [JsonPropertyName("start_payload")] public string? StartPayload { get; set; } } diff --git a/src/Max.Bot/Types/User.cs b/src/Max.Bot/Types/User.cs index 5dfcb6c..a35b636 100644 --- a/src/Max.Bot/Types/User.cs +++ b/src/Max.Bot/Types/User.cs @@ -30,6 +30,7 @@ public class User /// The first name of the user. Always sent by MAX API. [StringLength(64, ErrorMessage = "First name must not exceed 64 characters.")] [JsonPropertyName("first_name")] + [JsonConverter(typeof(Converters.NullAsEmptyStringConverter))] public string FirstName { get; set; } = string.Empty; /// @@ -53,6 +54,7 @@ public class User /// The timestamp of the user's last activity. [Range(0, long.MaxValue, ErrorMessage = "Last activity time cannot be negative.")] [JsonPropertyName("last_activity_time")] + [JsonConverter(typeof(Converters.NullAsDefaultConverter))] public long LastActivityTime { get; set; } /// @@ -86,5 +88,11 @@ public class User [MaxLength(32, ErrorMessage = "Commands must not exceed 32 items.")] [JsonPropertyName("commands")] public BotCommand[]? Commands { get; set; } + + /// + /// Gets or sets a value indicating whether the bot is official. Returned by GET /me. + /// + [JsonPropertyName("is_official")] + public bool? IsOfficial { get; set; } } diff --git a/src/Max.Bot/Types/Video.cs b/src/Max.Bot/Types/Video.cs index 20a7b77..c899717 100644 --- a/src/Max.Bot/Types/Video.cs +++ b/src/Max.Bot/Types/Video.cs @@ -13,6 +13,7 @@ public class Video /// Gets or sets the media token returned by /videos/{token}. /// [JsonPropertyName("token")] + [JsonConverter(typeof(Converters.NullAsEmptyStringConverter))] public string Token { get; set; } = string.Empty; /// @@ -38,6 +39,7 @@ public class Video /// The width of the video in pixels. [Range(0, int.MaxValue, ErrorMessage = "Width cannot be negative.")] [JsonPropertyName("width")] + [JsonConverter(typeof(Converters.NullAsDefaultConverter))] public int Width { get; set; } /// @@ -46,6 +48,7 @@ public class Video /// The height of the video in pixels. [Range(0, int.MaxValue, ErrorMessage = "Height cannot be negative.")] [JsonPropertyName("height")] + [JsonConverter(typeof(Converters.NullAsDefaultConverter))] public int Height { get; set; } /// @@ -54,6 +57,7 @@ public class Video /// The duration of the video in seconds. [Range(0, int.MaxValue, ErrorMessage = "Duration cannot be negative.")] [JsonPropertyName("duration")] + [JsonConverter(typeof(Converters.NullAsDefaultConverter))] public int Duration { get; set; } /// @@ -82,10 +86,10 @@ public class Video public string? Url { get; set; } /// - /// Gets or sets quality-specific video URLs keyed by rendition name (for example, mp4_720). + /// Gets or sets the URLs to download or play the video, per rendition. null if the video is unavailable. /// [JsonPropertyName("urls")] - public Dictionary? Urls { get; set; } + public VideoUrls? Urls { get; set; } /// /// Gets or sets the thumbnail for this video. @@ -103,6 +107,7 @@ public class VideoThumbnail /// Gets or sets the thumbnail URL. /// [JsonPropertyName("url")] + [JsonConverter(typeof(Converters.NullAsEmptyStringConverter))] public string Url { get; set; } = string.Empty; /// diff --git a/src/Max.Bot/Types/VideoUrls.cs b/src/Max.Bot/Types/VideoUrls.cs new file mode 100644 index 0000000..231f6fd --- /dev/null +++ b/src/Max.Bot/Types/VideoUrls.cs @@ -0,0 +1,65 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Max.Bot.Types; + +/// +/// Represents the URLs to download or play a video (urls of GET /videos/{token}). +/// Each rendition is null if it is not available. +/// +public class VideoUrls +{ + /// + /// Gets or sets the MP4 URL in 1080p (mp4_1080). + /// + [JsonPropertyName("mp4_1080")] + public string? Mp4P1080 { get; set; } + + /// + /// Gets or sets the MP4 URL in 720p (mp4_720). + /// + [JsonPropertyName("mp4_720")] + public string? Mp4P720 { get; set; } + + /// + /// Gets or sets the MP4 URL in 480p (mp4_480). + /// + [JsonPropertyName("mp4_480")] + public string? Mp4P480 { get; set; } + + /// + /// Gets or sets the MP4 URL in 360p (mp4_360). + /// + [JsonPropertyName("mp4_360")] + public string? Mp4P360 { get; set; } + + /// + /// Gets or sets the MP4 URL in 240p (mp4_240). + /// + [JsonPropertyName("mp4_240")] + public string? Mp4P240 { get; set; } + + /// + /// Gets or sets the MP4 URL in 144p (mp4_144). + /// + [JsonPropertyName("mp4_144")] + public string? Mp4P144 { get; set; } + + /// + /// Gets or sets the live streaming (HLS) URL (hls). + /// + [JsonPropertyName("hls")] + public string? Hls { get; set; } + + /// + /// Gets or sets renditions unknown to this library version, keyed by their API name. + /// + [JsonExtensionData] + public Dictionary? AdditionalUrls { get; set; } + + /// + /// Gets the URL of the best available MP4 rendition, or null if there is none. + /// + [JsonIgnore] + public string? BestMp4 => Mp4P1080 ?? Mp4P720 ?? Mp4P480 ?? Mp4P360 ?? Mp4P240 ?? Mp4P144; +} diff --git a/tests/Max.Bot.Tests/Unit/Api/MessagesApiTests.cs b/tests/Max.Bot.Tests/Unit/Api/MessagesApiTests.cs index 6db62f2..9489918 100644 --- a/tests/Max.Bot.Tests/Unit/Api/MessagesApiTests.cs +++ b/tests/Max.Bot.Tests/Unit/Api/MessagesApiTests.cs @@ -538,7 +538,7 @@ public async Task GetVideoAsync_ShouldMapTokenUrlsAndThumbnail_WhenResponseUsesN result.Height.Should().Be(1280); result.Duration.Should().Be(6633); result.Urls.Should().NotBeNull(); - result.Urls!["mp4_720"].Should().Be("http://vd555.okcdn.ru/video.mp4"); + result.Urls!.Mp4P720.Should().Be("http://vd555.okcdn.ru/video.mp4"); result.Thumbnail.Should().NotBeNull(); result.Thumbnail!.Url.Should().Be("https://pimg.mycdn.me/thumb.jpg"); } diff --git a/tests/Max.Bot.Tests/Unit/Regression/IssueRegressionTests.cs b/tests/Max.Bot.Tests/Unit/Regression/IssueRegressionTests.cs index 5f42683..6a87a30 100644 --- a/tests/Max.Bot.Tests/Unit/Regression/IssueRegressionTests.cs +++ b/tests/Max.Bot.Tests/Unit/Regression/IssueRegressionTests.cs @@ -364,7 +364,7 @@ public async Task Issue21_GetVideoAsync_ShouldReadUrlsObject() var api = new MessagesApi(_http.Object, _options); var video = await api.GetVideoAsync("video-token"); - video.Urls.Should().ContainKey("mp4_480").WhoseValue.Should().Be("https://v/480"); + video.Urls!.Mp4P480.Should().Be("https://v/480"); video.Thumbnail!.Url.Should().Be("https://thumb"); video.Duration.Should().Be(12); } diff --git a/tests/Max.Bot.Tests/Unit/Regression/ModelDeserializationTests.cs b/tests/Max.Bot.Tests/Unit/Regression/ModelDeserializationTests.cs index f680629..7322e9c 100644 --- a/tests/Max.Bot.Tests/Unit/Regression/ModelDeserializationTests.cs +++ b/tests/Max.Bot.Tests/Unit/Regression/ModelDeserializationTests.cs @@ -288,6 +288,130 @@ public void AddChatMembersResult_ShouldExposeFailedUsers() result.FailedUserDetails.Should().ContainSingle().Which.ErrorCode.Should().Be("add.participant.privacy"); } + public static TheoryData OptionsKinds() => new() { "default", "library" }; + + private static JsonSerializerOptions GetOptions(string kind) => kind == "library" ? MaxJsonSerializer.Options : DefaultOptions; + + /// + /// Review: fields made non-nullable must tolerate an explicit JSON null instead of failing the whole update. + /// + [Theory] + [MemberData(nameof(OptionsKinds))] + public void RequiredFields_WithExplicitNull_ShouldFallBackToDefaults(string optionsKind) + { + var options = GetOptions(optionsKind); + + var message = JsonSerializer.Deserialize("""{"recipient":null,"timestamp":null,"sender":{"user_id":1,"first_name":null,"last_activity_time":null},"link":{"type":"forward","message":null},"body":{"mid":null,"seq":null,"text":null},"stat":{"views":null}}""", options)!; + message.Recipient.Should().NotBeNull(); + message.Timestamp.Should().Be(0); + message.Sender!.FirstName.Should().BeEmpty(); + message.Sender.LastActivityTime.Should().Be(0); + message.Link!.Message.Should().NotBeNull(); + message.Body!.Mid.Should().BeEmpty(); + message.Body.Seq.Should().Be(0); + message.Stat!.Views.Should().Be(0); + + var chat = JsonSerializer.Deserialize("""{"chat_id":1,"type":"chat","last_event_time":null,"participants_count":null}""", options)!; + chat.LastEventTime.Should().Be(0); + chat.ParticipantsCount.Should().Be(0); + + var member = JsonSerializer.Deserialize("""{"user_id":1,"first_name":null,"join_time":null,"last_access_time":null}""", options)!; + member.FirstName.Should().BeEmpty(); + member.JoinTime.Should().Be(0); + + var video = JsonSerializer.Deserialize