Path: redb-route/redb.Route.Telegram/TelegramUpdateSerializer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Telegram/TelegramUpdateSerializer.cs
----
using System.Text.Json;
using Telegram.Bot;
using Telegram.Bot.Types;
using redb.Route.Abstractions;
namespace redb.Route.Telegram;
///
/// Deserializes a Telegram from a raw JSON byte array received
/// via webhook (HTTP POST from Telegram servers).
///
/// Uses — the same
/// that Telegram.Bot uses internally, ensuring correct handling of polymorphic
/// fields (e.g. MaybeInaccessibleMessage).
///
///
/// Serialization () is intentionally not supported:
/// the Telegram Bot API is inbound-only in the webhook path.
///
///
public sealed class TelegramUpdateSerializer : IMessageSerializer
{
///
public string ContentType => "application/json";
///
public byte[] Serialize(T value) =>
throw new NotSupportedException(
$"{nameof(TelegramUpdateSerializer)} is receive-only. " +
"Use Telegram.Bot client methods to send messages.");
///
public T? Deserialize(byte[] data)
{
if (typeof(T) != typeof(Update))
throw new NotSupportedException(
$"{nameof(TelegramUpdateSerializer)} only deserializes {nameof(Update)}. " +
$"Requested type: {typeof(T).Name}");
return (T?)(object?)DeserializeUpdate(data);
}
///
public object? Deserialize(byte[] data, Type type)
{
if (type != typeof(Update))
throw new NotSupportedException(
$"{nameof(TelegramUpdateSerializer)} only deserializes {nameof(Update)}. " +
$"Requested type: {type.Name}");
return DeserializeUpdate(data);
}
// ── Internal ──────────────────────────────────────────────────────────────
private static Update DeserializeUpdate(byte[] data)
{
var update = JsonSerializer.Deserialize(data, JsonBotAPI.Options);
return update ?? throw new InvalidOperationException(
"Telegram webhook: failed to deserialize Update — JSON body was null or empty.");
}
}