1mod api;
4pub(super) mod wire;
5
6use std::collections::{BTreeSet, HashMap, HashSet};
7use std::fmt;
8use std::sync::Arc;
9use std::time::Duration;
10
11use adk_core::audit_log::{
12 AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind, AuditTrail,
13};
14use adk_core::principal::SubjectRef;
15use adk_core::{AdkError, ApprovalRequest, ApprovalService, ErrorCategory, ErrorComponent};
16use adk_kernel::KernelError;
17use adk_kernel::channels::{
18 ChannelAnswer, ChannelBinding, ChannelBindingStore, ChannelGateway, ChannelInbound,
19 ChannelNotice, ChannelSink, DecisionCard, InboundBody, InboundOutcome, StopNotice,
20};
21use async_trait::async_trait;
22use chrono::{FixedOffset, Utc};
23use serde_json::{Value, json};
24use tokio::task::JoinHandle;
25
26use crate::answers::{AnswerLog, AnswerRecord, SURFACE_AUDIT_DECIDE};
27use crate::error::{Result, SurfaceError};
28use crate::origin::{Origin, SurfaceKind, Via};
29use crate::rules::Answer;
30use crate::words;
31use api::BotApi;
32use wire::{Outgoing, Parsed, Press};
33
34pub const TELEGRAM_CHANNEL: &str = "telegram";
37
38pub const TELEGRAM: &str = "Telegram";
40
41const DEFAULT_API_BASE: &str = "https://api.telegram.org";
42const DEFAULT_POLL_TIMEOUT: Duration = Duration::from_secs(25);
44const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
46const MIN_BACKOFF: Duration = Duration::from_secs(1);
47const MAX_BACKOFF: Duration = Duration::from_secs(60);
48const UPDATE_ATTEMPTS: u32 = 5;
51
52tokio::task_local! {
53 static HANDLING: Arc<Handling>;
55}
56
57struct Handling {
59 thread: String,
61 account: String,
63 paired: bool,
66 bindings: Arc<dyn ChannelBindingStore>,
68 press: Option<PressedCard>,
70}
71
72struct PressedCard {
74 message: Option<i64>,
76 decision: String,
78}
79
80#[derive(Default)]
82struct Reads {
83 handled: BTreeSet<i64>,
85 failures: HashMap<i64, u32>,
87}
88
89impl Reads {
90 fn done(&mut self, id: i64) {
92 self.handled.insert(id);
93 self.failures.remove(&id);
94 }
95
96 fn failed(&mut self, id: i64) -> u32 {
98 let failures = self.failures.entry(id).or_default();
99 *failures += 1;
100 *failures
101 }
102
103 fn acknowledged(&mut self, updates: &[Value]) -> Option<i64> {
105 let mut ids: Vec<i64> =
106 updates.iter().filter_map(|update| update.get("update_id")?.as_i64()).collect();
107 ids.sort_unstable();
108 let mut next = None;
109 for id in ids {
110 if !self.handled.remove(&id) {
111 break;
112 }
113 next = Some(id + 1);
114 }
115 next
116 }
117}
118
119fn may_clear(error: &KernelError) -> bool {
122 if matches!(error, KernelError::Frozen { .. }) {
123 return false;
124 }
125 match error.category() {
126 ErrorCategory::Unavailable | ErrorCategory::Timeout | ErrorCategory::RateLimited => true,
127 ErrorCategory::InvalidInput
128 | ErrorCategory::Unauthorized
129 | ErrorCategory::Forbidden
130 | ErrorCategory::NotFound
131 | ErrorCategory::Cancelled
132 | ErrorCategory::Internal
133 | ErrorCategory::Unsupported
134 | ErrorCategory::ResourceExhausted
135 | ErrorCategory::Conflict => false,
136 }
137}
138
139async fn is_paired(gateway: &ChannelGateway, account: &str) -> bool {
142 let id = ChannelBinding::id_for(TELEGRAM_CHANNEL, account);
143 match gateway.bindings().get_binding(&id).await {
144 Ok(binding) => binding.is_some_and(|binding| binding.is_active()),
145 Err(error) => {
146 tracing::debug!(error = %error, "a telegram account's pairing could not be read");
147 true
148 }
149 }
150}
151
152#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
167#[non_exhaustive]
168pub enum TelegramError {
169 #[error(
171 "Telegram refused the bot token: check TELEGRAM_BOT_TOKEN, or ask @BotFather for a new one"
172 )]
173 Unauthorized,
174 #[error(
176 "another process reads this bot's updates, or the bot has a webhook: stop the other \
177 process or delete the webhook (`deleteWebhook`); the adapter keeps trying"
178 )]
179 Conflict,
180 #[error("Telegram asked to wait {retry_after} s before {method}: the bot is sending too much")]
182 RateLimited {
183 method: String,
185 retry_after: u64,
187 },
188 #[error("Telegram refused {method} ({code}): {description}")]
190 Refused {
191 method: String,
193 code: i64,
195 description: String,
197 },
198 #[error(
200 "Telegram could not be reached for {method}: {reason}; check the network and the API \
201 address"
202 )]
203 Unreachable {
204 method: String,
206 reason: String,
208 },
209 #[error("Telegram's answer to {method} could not be read: {reason}")]
211 InvalidResponse {
212 method: String,
214 reason: String,
216 },
217}
218
219impl TelegramError {
220 pub fn code(&self) -> &'static str {
223 match self {
224 Self::Unauthorized => "surface.telegram.unauthorized",
225 Self::Conflict => "surface.telegram.conflict",
226 Self::RateLimited { .. } => "surface.telegram.rate_limited",
227 Self::Refused { .. } => "surface.telegram.refused",
228 Self::Unreachable { .. } => "surface.telegram.unreachable",
229 Self::InvalidResponse { .. } => "surface.telegram.invalid_response",
230 }
231 }
232}
233
234impl From<TelegramError> for AdkError {
235 fn from(error: TelegramError) -> Self {
236 let category = match &error {
237 TelegramError::Unauthorized => ErrorCategory::Unauthorized,
238 TelegramError::Conflict => ErrorCategory::Conflict,
239 TelegramError::RateLimited { .. } => ErrorCategory::RateLimited,
240 TelegramError::Refused { code: 403, .. } => ErrorCategory::Forbidden,
241 TelegramError::Refused { code: 400, .. } => ErrorCategory::InvalidInput,
242 TelegramError::Refused { .. } | TelegramError::Unreachable { .. } => {
243 ErrorCategory::Unavailable
244 }
245 TelegramError::InvalidResponse { .. } => ErrorCategory::Internal,
246 };
247 AdkError::new(ErrorComponent::Server, category, error.code(), error.to_string())
248 .with_provider("telegram")
249 }
250}
251
252impl From<TelegramError> for KernelError {
253 fn from(error: TelegramError) -> Self {
254 Self::Core(error.into())
255 }
256}
257
258pub struct TelegramAdapterBuilder {
260 token: String,
261 api_base: String,
262 poll_timeout: Duration,
263 offset: Option<FixedOffset>,
264 approvals: Option<Arc<dyn ApprovalService>>,
265 answers: Option<Arc<dyn AnswerLog>>,
266 audit: Option<AuditTrail>,
267 card_hints: Vec<Arc<dyn crate::hints::CardHints>>,
268 artifacts: Option<Arc<dyn adk_artifact::ArtifactService>>,
269}
270
271impl fmt::Debug for TelegramAdapterBuilder {
272 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273 f.debug_struct("TelegramAdapterBuilder")
274 .field("api_base", &self.api_base)
275 .field("poll_timeout", &self.poll_timeout)
276 .finish_non_exhaustive()
277 }
278}
279
280impl TelegramAdapterBuilder {
281 #[must_use]
285 pub fn api_base(mut self, url: impl Into<String>) -> Self {
286 self.api_base = url.into();
287 self
288 }
289
290 #[must_use]
292 pub fn poll_timeout(mut self, timeout: Duration) -> Self {
293 self.poll_timeout = timeout.max(Duration::from_secs(1));
294 self
295 }
296
297 #[must_use]
302 pub fn utc_offset(mut self, offset: FixedOffset) -> Self {
303 self.offset = Some(offset);
304 self
305 }
306
307 #[must_use]
312 pub fn approvals(mut self, approvals: Arc<dyn ApprovalService>) -> Self {
313 self.approvals = Some(approvals);
314 self
315 }
316
317 #[must_use]
321 pub fn answer_log(mut self, log: Arc<dyn AnswerLog>) -> Self {
322 self.answers = Some(log);
323 self
324 }
325
326 #[must_use]
330 pub fn audit(mut self, trail: AuditTrail) -> Self {
331 self.audit = Some(trail);
332 self
333 }
334
335 #[must_use]
360 pub fn card_hints(mut self, hints: Arc<dyn crate::hints::CardHints>) -> Self {
361 self.card_hints.push(hints);
362 self
363 }
364
365 #[must_use]
371 pub fn artifacts(mut self, artifacts: Arc<dyn adk_artifact::ArtifactService>) -> Self {
372 self.artifacts = Some(artifacts);
373 self
374 }
375
376 pub fn build(self) -> Result<TelegramAdapter> {
383 let api = BotApi::new(&self.api_base, &self.token).map_err(SurfaceError::Invalid)?;
384 Ok(TelegramAdapter {
385 inner: Arc::new(Inner {
386 api,
387 poll_timeout: self.poll_timeout,
388 offset: self.offset,
389 approvals: self.approvals,
390 answers: self.answers,
391 audit: self.audit,
392 card_hints: self.card_hints,
393 artifacts: self.artifacts,
394 }),
395 })
396 }
397}
398
399#[derive(Clone)]
435pub struct TelegramAdapter {
436 inner: Arc<Inner>,
437}
438
439struct Inner {
440 api: BotApi,
441 poll_timeout: Duration,
442 offset: Option<FixedOffset>,
443 approvals: Option<Arc<dyn ApprovalService>>,
444 answers: Option<Arc<dyn AnswerLog>>,
445 audit: Option<AuditTrail>,
446 card_hints: Vec<Arc<dyn crate::hints::CardHints>>,
447 artifacts: Option<Arc<dyn adk_artifact::ArtifactService>>,
448}
449
450impl fmt::Debug for TelegramAdapter {
451 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
452 f.debug_struct("TelegramAdapter")
453 .field("channel", &TELEGRAM_CHANNEL)
454 .field("poll_timeout", &self.inner.poll_timeout)
455 .finish_non_exhaustive()
456 }
457}
458
459impl TelegramAdapter {
460 pub fn builder(token: impl Into<String>) -> TelegramAdapterBuilder {
462 TelegramAdapterBuilder {
463 token: token.into(),
464 api_base: DEFAULT_API_BASE.to_string(),
465 poll_timeout: DEFAULT_POLL_TIMEOUT,
466 offset: None,
467 approvals: None,
468 answers: None,
469 audit: None,
470 card_hints: Vec::new(),
471 artifacts: None,
472 }
473 }
474
475 pub fn inbound(&self, update: &Value) -> Option<ChannelInbound> {
500 wire::parse(update).inbound
501 }
502
503 pub fn start(&self, gateway: ChannelGateway) -> TelegramPolling {
522 let adapter = self.clone();
523 let task = tokio::spawn(async move { adapter.poll(&gateway).await });
524 TelegramPolling { task: Some(task) }
525 }
526
527 async fn poll(&self, gateway: &ChannelGateway) -> std::result::Result<(), TelegramError> {
528 let commands =
529 json!({ "commands": [{ "command": "stop", "description": words::STOP_ALL }] });
530 match self.inner.api.call("setMyCommands", &commands, REQUEST_TIMEOUT).await {
531 Err(TelegramError::Unauthorized) => return Err(TelegramError::Unauthorized),
532 Err(error) => tracing::warn!(error = %error, "the bot's commands could not be listed"),
533 Ok(_) => {}
534 }
535 let mut offset: Option<i64> = None;
536 let mut backoff = MIN_BACKOFF;
537 let mut conflicted = false;
538 let mut reads = Reads::default();
539 loop {
540 let mut request = json!({
541 "timeout": self.inner.poll_timeout.as_secs(),
542 "allowed_updates": ["message", "callback_query"],
543 });
544 if let Some(offset) = offset {
545 request["offset"] = json!(offset);
546 }
547 let timeout = self.inner.poll_timeout + REQUEST_TIMEOUT;
548 let updates = match self.inner.api.call("getUpdates", &request, timeout).await {
549 Ok(Value::Array(updates)) => {
550 backoff = MIN_BACKOFF;
551 conflicted = false;
552 updates
553 }
554 Ok(_) => {
555 tracing::warn!("telegram answered getUpdates without a list; retrying");
556 tokio::time::sleep(backoff).await;
557 backoff = (backoff * 2).min(MAX_BACKOFF);
558 continue;
559 }
560 Err(TelegramError::Unauthorized) => return Err(TelegramError::Unauthorized),
561 Err(TelegramError::RateLimited { retry_after, .. }) => {
562 tokio::time::sleep(Duration::from_secs(retry_after.max(1))).await;
563 continue;
564 }
565 Err(error) => {
566 if matches!(error, TelegramError::Conflict) && !conflicted {
568 conflicted = true;
569 tracing::error!(error = %error, "another process reads this bot's updates");
570 } else {
571 tracing::warn!(error = %error, "reading telegram updates failed; retrying");
572 }
573 tokio::time::sleep(backoff).await;
574 backoff = (backoff * 2).min(MAX_BACKOFF);
575 continue;
576 }
577 };
578 let wait = self.take(gateway, &updates, &mut reads).await;
579 if let Some(next) = reads.acknowledged(&updates) {
580 offset = Some(next);
581 }
582 if let Some(wait) = wait {
583 tokio::time::sleep(wait).await;
584 }
585 }
586 }
587
588 async fn take(
591 &self,
592 gateway: &ChannelGateway,
593 updates: &[Value],
594 reads: &mut Reads,
595 ) -> Option<Duration> {
596 let mut batch = Vec::new();
597 for update in updates {
598 let Some(id) = update.get("update_id").and_then(Value::as_i64) else { continue };
600 if reads.handled.contains(&id) {
601 continue;
602 }
603 let parsed = wire::parse(update);
604 let paired = match &parsed.inbound {
605 Some(inbound) => is_paired(gateway, &inbound.account).await,
606 None => false,
607 };
608 batch.push((id, parsed, paired));
609 }
610 batch.sort_by_key(|(_, _, paired)| !*paired);
612 let mut held: HashSet<String> = HashSet::new();
613 let mut wait: Option<Duration> = None;
614 for (id, parsed, paired) in batch {
615 let account = parsed.inbound.as_ref().map(|inbound| inbound.account.clone());
616 if account.as_ref().is_some_and(|account| held.contains(account)) {
617 continue;
618 }
619 let Err(error) = self.handle(gateway, &parsed, paired).await else {
620 reads.done(id);
621 continue;
622 };
623 let attempt = reads.failed(id);
624 if paired && may_clear(&error) && attempt < UPDATE_ATTEMPTS {
625 tracing::warn!(update.id = id, error = %error, attempt, "the gateway could not take a telegram update; reading it again");
626 let delay = MIN_BACKOFF * 2u32.pow(attempt - 1);
627 wait = Some(wait.map_or(delay, |wait| wait.min(delay)));
628 held.extend(account);
629 continue;
630 }
631 tracing::warn!(update.id = id, error = %error, attempt, "the gateway could not take a telegram update; dropping it");
632 reads.done(id);
633 if paired {
634 self.not_taken(&parsed).await;
635 }
636 }
637 wait
638 }
639
640 async fn handle(
644 &self,
645 gateway: &ChannelGateway,
646 parsed: &Parsed,
647 paired: bool,
648 ) -> adk_kernel::Result<()> {
649 let Some(mut inbound) = parsed.inbound.clone() else {
650 if let Some(press) = &parsed.press {
652 self.acknowledge(press).await;
653 }
654 return Ok(());
655 };
656 if paired
659 && let Some(photo) = &parsed.photo
660 && let Some(attachment) = self.inner.api.download(photo).await
661 {
662 inbound = inbound.with_attachments([attachment]);
663 }
664 let press = parsed.press.as_ref();
665 let card = match (&inbound.body, press) {
666 (InboundBody::Answer { decision, .. }, Some(press)) => Some(PressedCard {
667 message: press.card.as_ref().map(|(_, message)| *message),
668 decision: decision.clone(),
669 }),
670 _ => None,
671 };
672 let handling = Arc::new(Handling {
673 thread: inbound.thread.clone(),
674 account: inbound.account.clone(),
675 paired,
676 bindings: Arc::clone(gateway.bindings()),
677 press: card,
678 });
679 let outcome = HANDLING.scope(handling, gateway.receive(inbound)).await;
680 let Some(press) = press else { return outcome.map(drop) };
681 self.acknowledge(press).await;
682 if matches!(
683 outcome?,
684 InboundOutcome::Decided { .. }
685 | InboundOutcome::AlreadyDecided { .. }
686 | InboundOutcome::DecisionChanged { .. }
687 | InboundOutcome::DecisionRefused { .. }
688 ) {
689 self.clear_buttons(press).await;
690 }
691 Ok(())
692 }
693
694 async fn not_taken(&self, parsed: &Parsed) {
697 let Some(inbound) = &parsed.inbound else { return };
698 let (text, reply_to) = match &parsed.press {
699 Some(press) => (wire::ANSWER_NOT_TAKEN, press.card.as_ref().map(|(_, id)| *id)),
700 None => (wire::MESSAGE_NOT_TAKEN, inbound.message_id.parse().ok()),
701 };
702 let message = Outgoing::plain(text.to_string());
703 if let Err(error) = self.send(&inbound.thread, message, reply_to).await {
704 tracing::debug!(error = %error, "a person could not be told their update was not taken");
705 }
706 }
707
708 async fn acknowledge(&self, press: &Press) {
710 let body = json!({ "callback_query_id": press.callback_id });
711 if let Err(error) = self.inner.api.call("answerCallbackQuery", &body, REQUEST_TIMEOUT).await
712 {
713 tracing::debug!(error = %error, "a pressed button could not be acknowledged");
714 }
715 }
716
717 async fn clear_buttons(&self, press: &Press) {
719 let Some((chat, message)) = &press.card else { return };
720 let body = json!({
721 "chat_id": chat_id(chat),
722 "message_id": message,
723 "reply_markup": { "inline_keyboard": [] },
724 });
725 if let Err(error) =
726 self.inner.api.call("editMessageReplyMarkup", &body, REQUEST_TIMEOUT).await
727 {
728 tracing::debug!(error = %error, "an answered card's buttons could not be removed");
729 }
730 }
731
732 async fn record_answer(
734 &self,
735 bindings: &dyn ChannelBindingStore,
736 account: &str,
737 decision: &str,
738 answer: ChannelAnswer,
739 ) {
740 let answer = match answer {
741 ChannelAnswer::AllowOnce => Answer::AllowOnce,
742 ChannelAnswer::Deny => Answer::Deny,
743 _ => return,
744 };
745 let id = ChannelBinding::id_for(TELEGRAM_CHANNEL, account);
746 let binding = match bindings.get_binding(&id).await {
747 Ok(Some(binding)) => binding,
748 Ok(None) => return,
749 Err(error) => {
750 tracing::warn!(error = %error, "a telegram answer could not be recorded");
751 return;
752 }
753 };
754 let record = AnswerRecord {
755 approval_id: decision.to_string(),
756 by: SubjectRef::human(binding.user_id),
757 via: Via {
758 surface: SurfaceKind::Chat,
759 origin: Origin::Chat { channel: TELEGRAM.into() },
760 },
761 answer,
762 at: Utc::now(),
763 };
764 if let Some(log) = &self.inner.answers
765 && let Err(error) = log.record(&record).await
766 {
767 tracing::warn!(error = %error, "a telegram answer could not be kept in the answer log");
768 }
769 let request = match (&self.inner.audit, &self.inner.approvals) {
771 (Some(_), Some(approvals)) => approvals.get(decision).await.ok().flatten(),
772 _ => None,
773 };
774 let title = match &request {
775 Some(request) => crate::hints::named(&self.inner.card_hints, request).await,
776 None => None,
777 };
778 if let Some(trail) = &self.inner.audit
779 && let Err(error) = trail.record(answer_record(&record, request.as_ref(), title)).await
780 {
781 tracing::warn!(error = %error, "a telegram answer's audit record could not be written");
782 }
783 }
784
785 async fn send(
786 &self,
787 thread: &str,
788 message: Outgoing,
789 reply_to: Option<i64>,
790 ) -> adk_kernel::Result<()> {
791 let mut body = json!({
792 "chat_id": chat_id(thread),
793 "text": message.text,
794 "link_preview_options": { "is_disabled": true },
795 });
796 if message.html {
797 body["parse_mode"] = json!("HTML");
798 }
799 if let Some(keyboard) = message.keyboard {
800 body["reply_markup"] = keyboard;
801 }
802 if let Some(id) = reply_to {
803 body["reply_parameters"] =
804 json!({ "message_id": id, "allow_sending_without_reply": true });
805 }
806 let patient = HANDLING
809 .try_with(|handling| handling.paired || handling.thread != thread)
810 .unwrap_or(true);
811 if patient {
812 self.inner.api.call("sendMessage", &body, REQUEST_TIMEOUT).await?;
813 } else {
814 self.inner.api.call_once("sendMessage", &body, REQUEST_TIMEOUT).await?;
815 }
816 Ok(())
817 }
818}
819
820fn chat_id(thread: &str) -> Value {
822 thread.parse::<i64>().map_or_else(|_| json!(thread), |id| json!(id))
823}
824
825fn answer_record(
828 record: &AnswerRecord,
829 request: Option<&ApprovalRequest>,
830 title: Option<String>,
831) -> AuditRecordDraft {
832 let decision = match record.answer {
833 Answer::Deny => AuditDecision::Rejected,
834 Answer::AllowOnce | Answer::AlwaysAllow | Answer::Edit => AuditDecision::Approved,
835 };
836 let mut draft = AuditRecordDraft::new(AuditRecordKind::Approval, SURFACE_AUDIT_DECIDE)
837 .actor(AuditActor::subject(record.by.clone()))
838 .ext("surface", serde_json::to_value(record.via.surface).unwrap_or(Value::Null))
839 .ext("origin", serde_json::to_value(&record.via.origin).unwrap_or(Value::Null))
840 .ext("approvalId", json!(record.approval_id))
841 .ext("answer", serde_json::to_value(record.answer).unwrap_or(Value::Null))
842 .ext("outcome", json!("decided"))
843 .decision(decision);
844 if let Some(request) = request {
845 draft = draft.ext("tool", json!(request.tool_name));
846 if let Some(acting) = &request.acting {
847 draft = draft.ext("actingAgent", json!(acting.agent.id.to_string()));
848 }
849 if let Some(title) = title {
851 draft = draft.ext("title", json!(title)).ext("summary", json!(request.summary));
852 }
853 }
854 draft
855}
856
857#[async_trait]
858impl ChannelSink for TelegramAdapter {
859 fn channel(&self) -> &str {
860 TELEGRAM_CHANNEL
861 }
862
863 async fn send_message(&self, thread: &str, text: &str) -> adk_kernel::Result<()> {
864 for chunk in wire::plain_chunks(text) {
865 self.send(thread, Outgoing::plain(chunk), None).await?;
866 }
867 Ok(())
868 }
869
870 async fn send_decision(&self, thread: &str, card: &DecisionCard) -> adk_kernel::Result<()> {
871 let request = match &self.inner.approvals {
872 Some(approvals) => approvals.get(&card.decision).await.unwrap_or_else(|error| {
873 tracing::warn!(error = %error, "a card's decision could not be read; headed by its summary");
874 None
875 }),
876 None => None,
877 };
878 let mut heading = wire::heading(card, request.as_ref());
879 let mut card = card.clone();
880 if let Some(request) = request.as_ref().filter(|request| request.id == card.decision) {
883 let mut headed = false;
884 for hints in &self.inner.card_hints {
885 let Some(hint) = hints.hint(request).await else { continue };
886 if let Some(chat) = hint.chat_heading.filter(|_| !headed) {
887 heading.title = chat;
888 headed = true;
889 }
890 if hint.money == Some(true) && !card.adds_agent {
891 card.answers.clear();
892 }
893 }
894 let artifacts = self.inner.artifacts.as_deref();
897 if let Some(image) =
898 wire::chat_images(request, artifacts, &mut card, &mut heading).await
899 {
900 let sent =
901 self.inner.api.send_photo(&chat_id(thread), &image, REQUEST_TIMEOUT).await;
902 if let Err(error) = sent {
903 tracing::warn!(error = %error, "a card's image could not be sent; the card links to the home");
904 card.answers.retain(|answer| *answer != ChannelAnswer::AllowOnce);
905 let line = format!(
906 "{} {}",
907 crate::words::SHOW_THE_IMAGE_IN_THE_HOME,
908 crate::evidence::short_digest(request.evidence[0].digest())
909 );
910 heading.detail = Some(match heading.detail.take() {
911 Some(detail) => format!("{detail}\n{line}"),
912 None => line,
913 });
914 }
915 }
916 }
917 self.send(thread, wire::card(&card, &heading, self.inner.offset), None).await
918 }
919
920 async fn send_stopped(&self, thread: &str, notice: &StopNotice) -> adk_kernel::Result<()> {
921 self.send(thread, wire::stopped(notice), None).await
922 }
923
924 async fn send_notice(&self, thread: &str, notice: &ChannelNotice) -> adk_kernel::Result<()> {
930 let handling =
931 HANDLING.try_with(Arc::clone).ok().filter(|handling| handling.thread == thread);
932 let press = handling.as_ref().and_then(|handling| handling.press.as_ref());
933 if let (Some(handling), Some(press), ChannelNotice::Decided { answer, .. }) =
934 (&handling, press, notice)
935 {
936 let bindings = handling.bindings.as_ref();
937 self.record_answer(bindings, &handling.account, &press.decision, *answer).await;
938 }
939 let reply_to = press.and_then(|press| press.message);
940 let message = wire::notice(notice, self.inner.offset, Utc::now(), reply_to.is_some());
941 self.send(thread, message, reply_to).await
942 }
943}
944
945#[derive(Debug)]
957pub struct TelegramPolling {
958 task: Option<JoinHandle<std::result::Result<(), TelegramError>>>,
959}
960
961impl TelegramPolling {
962 pub fn stop(&self) {
965 if let Some(task) = &self.task {
966 task.abort();
967 }
968 }
969
970 pub fn is_finished(&self) -> bool {
972 self.task.as_ref().is_none_or(JoinHandle::is_finished)
973 }
974
975 pub async fn join(mut self) -> std::result::Result<(), TelegramError> {
982 let Some(task) = self.task.take() else { return Ok(()) };
983 match task.await {
984 Ok(result) => result,
985 Err(error) if error.is_panic() => std::panic::resume_unwind(error.into_panic()),
986 Err(_) => Ok(()),
987 }
988 }
989}
990
991impl Drop for TelegramPolling {
992 fn drop(&mut self) {
993 self.stop();
994 }
995}
996
997#[cfg(test)]
998mod tests {
999 use adk_core::audit_log::AuditRecordDraft;
1000
1001 use super::*;
1002 use crate::answers::answer_of;
1003
1004 #[test]
1006 fn the_answer_record_is_read_back_as_given_in_telegram() {
1007 for answer in [Answer::AllowOnce, Answer::Deny] {
1008 let given = AnswerRecord {
1009 approval_id: "apr_1".into(),
1010 by: SubjectRef::human("ana"),
1011 via: Via {
1012 surface: SurfaceKind::Chat,
1013 origin: Origin::Chat { channel: TELEGRAM.into() },
1014 },
1015 answer,
1016 at: Utc::now(),
1017 };
1018 let draft: AuditRecordDraft = answer_record(&given, None, None);
1019 let record = draft.into_record("replica-1", 0, given.at, None);
1020 let read = answer_of(&record, "apr_1").expect("the record is an answer");
1021 assert_eq!(read, given);
1022 assert_eq!(read.via.phrase(), "in Telegram");
1023 assert!(answer_of(&record, "apr_2").is_none());
1024 }
1025 }
1026
1027 #[test]
1028 fn errors_say_what_to_do_and_keep_their_category() {
1029 let error: AdkError = TelegramError::Unauthorized.into();
1030 assert_eq!(error.code, "surface.telegram.unauthorized");
1031 assert_eq!(error.category, ErrorCategory::Unauthorized);
1032 let blocked = TelegramError::Refused {
1033 method: "sendMessage".into(),
1034 code: 403,
1035 description: "Forbidden: bot was blocked by the user".into(),
1036 };
1037 assert_eq!(AdkError::from(blocked).category, ErrorCategory::Forbidden);
1038 let limited = TelegramError::RateLimited { method: "sendMessage".into(), retry_after: 90 };
1039 assert!(AdkError::from(limited).is_retryable());
1040 }
1041
1042 #[test]
1043 fn the_builder_refuses_a_bad_token_or_address_without_echoing_the_token() {
1044 let error = TelegramAdapter::builder("123:secret")
1045 .api_base("http://example.com")
1046 .build()
1047 .unwrap_err();
1048 assert_eq!(error.code(), "surface.invalid");
1049 assert!(!error.to_string().contains("secret"), "{error}");
1050 assert!(TelegramAdapter::builder("").build().is_err());
1051 let adapter = TelegramAdapter::builder("123:secret").build().unwrap();
1052 assert!(!format!("{adapter:?}").contains("secret"));
1053 assert_eq!(adapter.channel(), "telegram");
1054 }
1055}