mod api;
pub(super) mod wire;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use adk_core::audit_log::{
AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind, AuditTrail,
};
use adk_core::principal::SubjectRef;
use adk_core::{AdkError, ApprovalRequest, ApprovalService, ErrorCategory, ErrorComponent};
use adk_kernel::KernelError;
use adk_kernel::channels::{
ChannelAnswer, ChannelBinding, ChannelBindingStore, ChannelGateway, ChannelInbound,
ChannelNotice, ChannelSink, DecisionCard, InboundBody, InboundOutcome, StopNotice,
};
use async_trait::async_trait;
use chrono::{FixedOffset, Utc};
use serde_json::{Value, json};
use tokio::task::JoinHandle;
use crate::answers::{AnswerLog, AnswerRecord, SURFACE_AUDIT_DECIDE};
use crate::error::{Result, SurfaceError};
use crate::origin::{Origin, SurfaceKind, Via};
use crate::rules::Answer;
use crate::words;
use api::BotApi;
use wire::{Outgoing, Parsed, Press};
pub const TELEGRAM_CHANNEL: &str = "telegram";
pub const TELEGRAM: &str = "Telegram";
const DEFAULT_API_BASE: &str = "https://api.telegram.org";
const DEFAULT_POLL_TIMEOUT: Duration = Duration::from_secs(25);
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
const MIN_BACKOFF: Duration = Duration::from_secs(1);
const MAX_BACKOFF: Duration = Duration::from_secs(60);
const UPDATE_ATTEMPTS: u32 = 5;
tokio::task_local! {
static HANDLING: Arc<Handling>;
}
struct Handling {
thread: String,
account: String,
paired: bool,
bindings: Arc<dyn ChannelBindingStore>,
press: Option<PressedCard>,
}
struct PressedCard {
message: Option<i64>,
decision: String,
}
#[derive(Default)]
struct Reads {
handled: BTreeSet<i64>,
failures: HashMap<i64, u32>,
}
impl Reads {
fn done(&mut self, id: i64) {
self.handled.insert(id);
self.failures.remove(&id);
}
fn failed(&mut self, id: i64) -> u32 {
let failures = self.failures.entry(id).or_default();
*failures += 1;
*failures
}
fn acknowledged(&mut self, updates: &[Value]) -> Option<i64> {
let mut ids: Vec<i64> =
updates.iter().filter_map(|update| update.get("update_id")?.as_i64()).collect();
ids.sort_unstable();
let mut next = None;
for id in ids {
if !self.handled.remove(&id) {
break;
}
next = Some(id + 1);
}
next
}
}
fn may_clear(error: &KernelError) -> bool {
if matches!(error, KernelError::Frozen { .. }) {
return false;
}
match error.category() {
ErrorCategory::Unavailable | ErrorCategory::Timeout | ErrorCategory::RateLimited => true,
ErrorCategory::InvalidInput
| ErrorCategory::Unauthorized
| ErrorCategory::Forbidden
| ErrorCategory::NotFound
| ErrorCategory::Cancelled
| ErrorCategory::Internal
| ErrorCategory::Unsupported
| ErrorCategory::ResourceExhausted
| ErrorCategory::Conflict => false,
}
}
async fn is_paired(gateway: &ChannelGateway, account: &str) -> bool {
let id = ChannelBinding::id_for(TELEGRAM_CHANNEL, account);
match gateway.bindings().get_binding(&id).await {
Ok(binding) => binding.is_some_and(|binding| binding.is_active()),
Err(error) => {
tracing::debug!(error = %error, "a telegram account's pairing could not be read");
true
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum TelegramError {
#[error(
"Telegram refused the bot token: check TELEGRAM_BOT_TOKEN, or ask @BotFather for a new one"
)]
Unauthorized,
#[error(
"another process reads this bot's updates, or the bot has a webhook: stop the other \
process or delete the webhook (`deleteWebhook`); the adapter keeps trying"
)]
Conflict,
#[error("Telegram asked to wait {retry_after} s before {method}: the bot is sending too much")]
RateLimited {
method: String,
retry_after: u64,
},
#[error("Telegram refused {method} ({code}): {description}")]
Refused {
method: String,
code: i64,
description: String,
},
#[error(
"Telegram could not be reached for {method}: {reason}; check the network and the API \
address"
)]
Unreachable {
method: String,
reason: String,
},
#[error("Telegram's answer to {method} could not be read: {reason}")]
InvalidResponse {
method: String,
reason: String,
},
}
impl TelegramError {
pub fn code(&self) -> &'static str {
match self {
Self::Unauthorized => "surface.telegram.unauthorized",
Self::Conflict => "surface.telegram.conflict",
Self::RateLimited { .. } => "surface.telegram.rate_limited",
Self::Refused { .. } => "surface.telegram.refused",
Self::Unreachable { .. } => "surface.telegram.unreachable",
Self::InvalidResponse { .. } => "surface.telegram.invalid_response",
}
}
}
impl From<TelegramError> for AdkError {
fn from(error: TelegramError) -> Self {
let category = match &error {
TelegramError::Unauthorized => ErrorCategory::Unauthorized,
TelegramError::Conflict => ErrorCategory::Conflict,
TelegramError::RateLimited { .. } => ErrorCategory::RateLimited,
TelegramError::Refused { code: 403, .. } => ErrorCategory::Forbidden,
TelegramError::Refused { code: 400, .. } => ErrorCategory::InvalidInput,
TelegramError::Refused { .. } | TelegramError::Unreachable { .. } => {
ErrorCategory::Unavailable
}
TelegramError::InvalidResponse { .. } => ErrorCategory::Internal,
};
AdkError::new(ErrorComponent::Server, category, error.code(), error.to_string())
.with_provider("telegram")
}
}
impl From<TelegramError> for KernelError {
fn from(error: TelegramError) -> Self {
Self::Core(error.into())
}
}
pub struct TelegramAdapterBuilder {
token: String,
api_base: String,
poll_timeout: Duration,
offset: Option<FixedOffset>,
approvals: Option<Arc<dyn ApprovalService>>,
answers: Option<Arc<dyn AnswerLog>>,
audit: Option<AuditTrail>,
card_hints: Vec<Arc<dyn crate::hints::CardHints>>,
artifacts: Option<Arc<dyn adk_artifact::ArtifactService>>,
}
impl fmt::Debug for TelegramAdapterBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TelegramAdapterBuilder")
.field("api_base", &self.api_base)
.field("poll_timeout", &self.poll_timeout)
.finish_non_exhaustive()
}
}
impl TelegramAdapterBuilder {
#[must_use]
pub fn api_base(mut self, url: impl Into<String>) -> Self {
self.api_base = url.into();
self
}
#[must_use]
pub fn poll_timeout(mut self, timeout: Duration) -> Self {
self.poll_timeout = timeout.max(Duration::from_secs(1));
self
}
#[must_use]
pub fn utc_offset(mut self, offset: FixedOffset) -> Self {
self.offset = Some(offset);
self
}
#[must_use]
pub fn approvals(mut self, approvals: Arc<dyn ApprovalService>) -> Self {
self.approvals = Some(approvals);
self
}
#[must_use]
pub fn answer_log(mut self, log: Arc<dyn AnswerLog>) -> Self {
self.answers = Some(log);
self
}
#[must_use]
pub fn audit(mut self, trail: AuditTrail) -> Self {
self.audit = Some(trail);
self
}
#[must_use]
pub fn card_hints(mut self, hints: Arc<dyn crate::hints::CardHints>) -> Self {
self.card_hints.push(hints);
self
}
#[must_use]
pub fn artifacts(mut self, artifacts: Arc<dyn adk_artifact::ArtifactService>) -> Self {
self.artifacts = Some(artifacts);
self
}
pub fn build(self) -> Result<TelegramAdapter> {
let api = BotApi::new(&self.api_base, &self.token).map_err(SurfaceError::Invalid)?;
Ok(TelegramAdapter {
inner: Arc::new(Inner {
api,
poll_timeout: self.poll_timeout,
offset: self.offset,
approvals: self.approvals,
answers: self.answers,
audit: self.audit,
card_hints: self.card_hints,
artifacts: self.artifacts,
}),
})
}
}
#[derive(Clone)]
pub struct TelegramAdapter {
inner: Arc<Inner>,
}
struct Inner {
api: BotApi,
poll_timeout: Duration,
offset: Option<FixedOffset>,
approvals: Option<Arc<dyn ApprovalService>>,
answers: Option<Arc<dyn AnswerLog>>,
audit: Option<AuditTrail>,
card_hints: Vec<Arc<dyn crate::hints::CardHints>>,
artifacts: Option<Arc<dyn adk_artifact::ArtifactService>>,
}
impl fmt::Debug for TelegramAdapter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TelegramAdapter")
.field("channel", &TELEGRAM_CHANNEL)
.field("poll_timeout", &self.inner.poll_timeout)
.finish_non_exhaustive()
}
}
impl TelegramAdapter {
pub fn builder(token: impl Into<String>) -> TelegramAdapterBuilder {
TelegramAdapterBuilder {
token: token.into(),
api_base: DEFAULT_API_BASE.to_string(),
poll_timeout: DEFAULT_POLL_TIMEOUT,
offset: None,
approvals: None,
answers: None,
audit: None,
card_hints: Vec::new(),
artifacts: None,
}
}
pub fn inbound(&self, update: &Value) -> Option<ChannelInbound> {
wire::parse(update).inbound
}
pub fn start(&self, gateway: ChannelGateway) -> TelegramPolling {
let adapter = self.clone();
let task = tokio::spawn(async move { adapter.poll(&gateway).await });
TelegramPolling { task: Some(task) }
}
async fn poll(&self, gateway: &ChannelGateway) -> std::result::Result<(), TelegramError> {
let commands =
json!({ "commands": [{ "command": "stop", "description": words::STOP_ALL }] });
match self.inner.api.call("setMyCommands", &commands, REQUEST_TIMEOUT).await {
Err(TelegramError::Unauthorized) => return Err(TelegramError::Unauthorized),
Err(error) => tracing::warn!(error = %error, "the bot's commands could not be listed"),
Ok(_) => {}
}
let mut offset: Option<i64> = None;
let mut backoff = MIN_BACKOFF;
let mut conflicted = false;
let mut reads = Reads::default();
loop {
let mut request = json!({
"timeout": self.inner.poll_timeout.as_secs(),
"allowed_updates": ["message", "callback_query"],
});
if let Some(offset) = offset {
request["offset"] = json!(offset);
}
let timeout = self.inner.poll_timeout + REQUEST_TIMEOUT;
let updates = match self.inner.api.call("getUpdates", &request, timeout).await {
Ok(Value::Array(updates)) => {
backoff = MIN_BACKOFF;
conflicted = false;
updates
}
Ok(_) => {
tracing::warn!("telegram answered getUpdates without a list; retrying");
tokio::time::sleep(backoff).await;
backoff = (backoff * 2).min(MAX_BACKOFF);
continue;
}
Err(TelegramError::Unauthorized) => return Err(TelegramError::Unauthorized),
Err(TelegramError::RateLimited { retry_after, .. }) => {
tokio::time::sleep(Duration::from_secs(retry_after.max(1))).await;
continue;
}
Err(error) => {
if matches!(error, TelegramError::Conflict) && !conflicted {
conflicted = true;
tracing::error!(error = %error, "another process reads this bot's updates");
} else {
tracing::warn!(error = %error, "reading telegram updates failed; retrying");
}
tokio::time::sleep(backoff).await;
backoff = (backoff * 2).min(MAX_BACKOFF);
continue;
}
};
let wait = self.take(gateway, &updates, &mut reads).await;
if let Some(next) = reads.acknowledged(&updates) {
offset = Some(next);
}
if let Some(wait) = wait {
tokio::time::sleep(wait).await;
}
}
}
async fn take(
&self,
gateway: &ChannelGateway,
updates: &[Value],
reads: &mut Reads,
) -> Option<Duration> {
let mut batch = Vec::new();
for update in updates {
let Some(id) = update.get("update_id").and_then(Value::as_i64) else { continue };
if reads.handled.contains(&id) {
continue;
}
let parsed = wire::parse(update);
let paired = match &parsed.inbound {
Some(inbound) => is_paired(gateway, &inbound.account).await,
None => false,
};
batch.push((id, parsed, paired));
}
batch.sort_by_key(|(_, _, paired)| !*paired);
let mut held: HashSet<String> = HashSet::new();
let mut wait: Option<Duration> = None;
for (id, parsed, paired) in batch {
let account = parsed.inbound.as_ref().map(|inbound| inbound.account.clone());
if account.as_ref().is_some_and(|account| held.contains(account)) {
continue;
}
let Err(error) = self.handle(gateway, &parsed, paired).await else {
reads.done(id);
continue;
};
let attempt = reads.failed(id);
if paired && may_clear(&error) && attempt < UPDATE_ATTEMPTS {
tracing::warn!(update.id = id, error = %error, attempt, "the gateway could not take a telegram update; reading it again");
let delay = MIN_BACKOFF * 2u32.pow(attempt - 1);
wait = Some(wait.map_or(delay, |wait| wait.min(delay)));
held.extend(account);
continue;
}
tracing::warn!(update.id = id, error = %error, attempt, "the gateway could not take a telegram update; dropping it");
reads.done(id);
if paired {
self.not_taken(&parsed).await;
}
}
wait
}
async fn handle(
&self,
gateway: &ChannelGateway,
parsed: &Parsed,
paired: bool,
) -> adk_kernel::Result<()> {
let Some(mut inbound) = parsed.inbound.clone() else {
if let Some(press) = &parsed.press {
self.acknowledge(press).await;
}
return Ok(());
};
if paired
&& let Some(photo) = &parsed.photo
&& let Some(attachment) = self.inner.api.download(photo).await
{
inbound = inbound.with_attachments([attachment]);
}
let press = parsed.press.as_ref();
let card = match (&inbound.body, press) {
(InboundBody::Answer { decision, .. }, Some(press)) => Some(PressedCard {
message: press.card.as_ref().map(|(_, message)| *message),
decision: decision.clone(),
}),
_ => None,
};
let handling = Arc::new(Handling {
thread: inbound.thread.clone(),
account: inbound.account.clone(),
paired,
bindings: Arc::clone(gateway.bindings()),
press: card,
});
let outcome = HANDLING.scope(handling, gateway.receive(inbound)).await;
let Some(press) = press else { return outcome.map(drop) };
self.acknowledge(press).await;
if matches!(
outcome?,
InboundOutcome::Decided { .. }
| InboundOutcome::AlreadyDecided { .. }
| InboundOutcome::DecisionChanged { .. }
| InboundOutcome::DecisionRefused { .. }
) {
self.clear_buttons(press).await;
}
Ok(())
}
async fn not_taken(&self, parsed: &Parsed) {
let Some(inbound) = &parsed.inbound else { return };
let (text, reply_to) = match &parsed.press {
Some(press) => (wire::ANSWER_NOT_TAKEN, press.card.as_ref().map(|(_, id)| *id)),
None => (wire::MESSAGE_NOT_TAKEN, inbound.message_id.parse().ok()),
};
let message = Outgoing::plain(text.to_string());
if let Err(error) = self.send(&inbound.thread, message, reply_to).await {
tracing::debug!(error = %error, "a person could not be told their update was not taken");
}
}
async fn acknowledge(&self, press: &Press) {
let body = json!({ "callback_query_id": press.callback_id });
if let Err(error) = self.inner.api.call("answerCallbackQuery", &body, REQUEST_TIMEOUT).await
{
tracing::debug!(error = %error, "a pressed button could not be acknowledged");
}
}
async fn clear_buttons(&self, press: &Press) {
let Some((chat, message)) = &press.card else { return };
let body = json!({
"chat_id": chat_id(chat),
"message_id": message,
"reply_markup": { "inline_keyboard": [] },
});
if let Err(error) =
self.inner.api.call("editMessageReplyMarkup", &body, REQUEST_TIMEOUT).await
{
tracing::debug!(error = %error, "an answered card's buttons could not be removed");
}
}
async fn record_answer(
&self,
bindings: &dyn ChannelBindingStore,
account: &str,
decision: &str,
answer: ChannelAnswer,
) {
let answer = match answer {
ChannelAnswer::AllowOnce => Answer::AllowOnce,
ChannelAnswer::Deny => Answer::Deny,
_ => return,
};
let id = ChannelBinding::id_for(TELEGRAM_CHANNEL, account);
let binding = match bindings.get_binding(&id).await {
Ok(Some(binding)) => binding,
Ok(None) => return,
Err(error) => {
tracing::warn!(error = %error, "a telegram answer could not be recorded");
return;
}
};
let record = AnswerRecord {
approval_id: decision.to_string(),
by: SubjectRef::human(binding.user_id),
via: Via {
surface: SurfaceKind::Chat,
origin: Origin::Chat { channel: TELEGRAM.into() },
},
answer,
at: Utc::now(),
};
if let Some(log) = &self.inner.answers
&& let Err(error) = log.record(&record).await
{
tracing::warn!(error = %error, "a telegram answer could not be kept in the answer log");
}
let request = match (&self.inner.audit, &self.inner.approvals) {
(Some(_), Some(approvals)) => approvals.get(decision).await.ok().flatten(),
_ => None,
};
let title = match &request {
Some(request) => crate::hints::named(&self.inner.card_hints, request).await,
None => None,
};
if let Some(trail) = &self.inner.audit
&& let Err(error) = trail.record(answer_record(&record, request.as_ref(), title)).await
{
tracing::warn!(error = %error, "a telegram answer's audit record could not be written");
}
}
async fn send(
&self,
thread: &str,
message: Outgoing,
reply_to: Option<i64>,
) -> adk_kernel::Result<()> {
let mut body = json!({
"chat_id": chat_id(thread),
"text": message.text,
"link_preview_options": { "is_disabled": true },
});
if message.html {
body["parse_mode"] = json!("HTML");
}
if let Some(keyboard) = message.keyboard {
body["reply_markup"] = keyboard;
}
if let Some(id) = reply_to {
body["reply_parameters"] =
json!({ "message_id": id, "allow_sending_without_reply": true });
}
let patient = HANDLING
.try_with(|handling| handling.paired || handling.thread != thread)
.unwrap_or(true);
if patient {
self.inner.api.call("sendMessage", &body, REQUEST_TIMEOUT).await?;
} else {
self.inner.api.call_once("sendMessage", &body, REQUEST_TIMEOUT).await?;
}
Ok(())
}
}
fn chat_id(thread: &str) -> Value {
thread.parse::<i64>().map_or_else(|_| json!(thread), |id| json!(id))
}
fn answer_record(
record: &AnswerRecord,
request: Option<&ApprovalRequest>,
title: Option<String>,
) -> AuditRecordDraft {
let decision = match record.answer {
Answer::Deny => AuditDecision::Rejected,
Answer::AllowOnce | Answer::AlwaysAllow | Answer::Edit => AuditDecision::Approved,
};
let mut draft = AuditRecordDraft::new(AuditRecordKind::Approval, SURFACE_AUDIT_DECIDE)
.actor(AuditActor::subject(record.by.clone()))
.ext("surface", serde_json::to_value(record.via.surface).unwrap_or(Value::Null))
.ext("origin", serde_json::to_value(&record.via.origin).unwrap_or(Value::Null))
.ext("approvalId", json!(record.approval_id))
.ext("answer", serde_json::to_value(record.answer).unwrap_or(Value::Null))
.ext("outcome", json!("decided"))
.decision(decision);
if let Some(request) = request {
draft = draft.ext("tool", json!(request.tool_name));
if let Some(acting) = &request.acting {
draft = draft.ext("actingAgent", json!(acting.agent.id.to_string()));
}
if let Some(title) = title {
draft = draft.ext("title", json!(title)).ext("summary", json!(request.summary));
}
}
draft
}
#[async_trait]
impl ChannelSink for TelegramAdapter {
fn channel(&self) -> &str {
TELEGRAM_CHANNEL
}
async fn send_message(&self, thread: &str, text: &str) -> adk_kernel::Result<()> {
for chunk in wire::plain_chunks(text) {
self.send(thread, Outgoing::plain(chunk), None).await?;
}
Ok(())
}
async fn send_decision(&self, thread: &str, card: &DecisionCard) -> adk_kernel::Result<()> {
let request = match &self.inner.approvals {
Some(approvals) => approvals.get(&card.decision).await.unwrap_or_else(|error| {
tracing::warn!(error = %error, "a card's decision could not be read; headed by its summary");
None
}),
None => None,
};
let mut heading = wire::heading(card, request.as_ref());
let mut card = card.clone();
if let Some(request) = request.as_ref().filter(|request| request.id == card.decision) {
let mut headed = false;
for hints in &self.inner.card_hints {
let Some(hint) = hints.hint(request).await else { continue };
if let Some(chat) = hint.chat_heading.filter(|_| !headed) {
heading.title = chat;
headed = true;
}
if hint.money == Some(true) && !card.adds_agent {
card.answers.clear();
}
}
let artifacts = self.inner.artifacts.as_deref();
if let Some(image) =
wire::chat_images(request, artifacts, &mut card, &mut heading).await
{
let sent =
self.inner.api.send_photo(&chat_id(thread), &image, REQUEST_TIMEOUT).await;
if let Err(error) = sent {
tracing::warn!(error = %error, "a card's image could not be sent; the card links to the home");
card.answers.retain(|answer| *answer != ChannelAnswer::AllowOnce);
let line = format!(
"{} {}",
crate::words::SHOW_THE_IMAGE_IN_THE_HOME,
crate::evidence::short_digest(request.evidence[0].digest())
);
heading.detail = Some(match heading.detail.take() {
Some(detail) => format!("{detail}\n{line}"),
None => line,
});
}
}
}
self.send(thread, wire::card(&card, &heading, self.inner.offset), None).await
}
async fn send_stopped(&self, thread: &str, notice: &StopNotice) -> adk_kernel::Result<()> {
self.send(thread, wire::stopped(notice), None).await
}
async fn send_notice(&self, thread: &str, notice: &ChannelNotice) -> adk_kernel::Result<()> {
let handling =
HANDLING.try_with(Arc::clone).ok().filter(|handling| handling.thread == thread);
let press = handling.as_ref().and_then(|handling| handling.press.as_ref());
if let (Some(handling), Some(press), ChannelNotice::Decided { answer, .. }) =
(&handling, press, notice)
{
let bindings = handling.bindings.as_ref();
self.record_answer(bindings, &handling.account, &press.decision, *answer).await;
}
let reply_to = press.and_then(|press| press.message);
let message = wire::notice(notice, self.inner.offset, Utc::now(), reply_to.is_some());
self.send(thread, message, reply_to).await
}
}
#[derive(Debug)]
pub struct TelegramPolling {
task: Option<JoinHandle<std::result::Result<(), TelegramError>>>,
}
impl TelegramPolling {
pub fn stop(&self) {
if let Some(task) = &self.task {
task.abort();
}
}
pub fn is_finished(&self) -> bool {
self.task.as_ref().is_none_or(JoinHandle::is_finished)
}
pub async fn join(mut self) -> std::result::Result<(), TelegramError> {
let Some(task) = self.task.take() else { return Ok(()) };
match task.await {
Ok(result) => result,
Err(error) if error.is_panic() => std::panic::resume_unwind(error.into_panic()),
Err(_) => Ok(()),
}
}
}
impl Drop for TelegramPolling {
fn drop(&mut self) {
self.stop();
}
}
#[cfg(test)]
mod tests {
use adk_core::audit_log::AuditRecordDraft;
use super::*;
use crate::answers::answer_of;
#[test]
fn the_answer_record_is_read_back_as_given_in_telegram() {
for answer in [Answer::AllowOnce, Answer::Deny] {
let given = AnswerRecord {
approval_id: "apr_1".into(),
by: SubjectRef::human("ana"),
via: Via {
surface: SurfaceKind::Chat,
origin: Origin::Chat { channel: TELEGRAM.into() },
},
answer,
at: Utc::now(),
};
let draft: AuditRecordDraft = answer_record(&given, None, None);
let record = draft.into_record("replica-1", 0, given.at, None);
let read = answer_of(&record, "apr_1").expect("the record is an answer");
assert_eq!(read, given);
assert_eq!(read.via.phrase(), "in Telegram");
assert!(answer_of(&record, "apr_2").is_none());
}
}
#[test]
fn errors_say_what_to_do_and_keep_their_category() {
let error: AdkError = TelegramError::Unauthorized.into();
assert_eq!(error.code, "surface.telegram.unauthorized");
assert_eq!(error.category, ErrorCategory::Unauthorized);
let blocked = TelegramError::Refused {
method: "sendMessage".into(),
code: 403,
description: "Forbidden: bot was blocked by the user".into(),
};
assert_eq!(AdkError::from(blocked).category, ErrorCategory::Forbidden);
let limited = TelegramError::RateLimited { method: "sendMessage".into(), retry_after: 90 };
assert!(AdkError::from(limited).is_retryable());
}
#[test]
fn the_builder_refuses_a_bad_token_or_address_without_echoing_the_token() {
let error = TelegramAdapter::builder("123:secret")
.api_base("http://example.com")
.build()
.unwrap_err();
assert_eq!(error.code(), "surface.invalid");
assert!(!error.to_string().contains("secret"), "{error}");
assert!(TelegramAdapter::builder("").build().is_err());
let adapter = TelegramAdapter::builder("123:secret").build().unwrap();
assert!(!format!("{adapter:?}").contains("secret"));
assert_eq!(adapter.channel(), "telegram");
}
}