Tous les chapitres

Canaux (téléphone)Chapitre 9 · 25 min de lecture

Piloter l'agent depuis Telegram

Un bot Telegram officiel, en long polling (sans URL publique) ou en webhook, et un cœur de messagerie partagé.

Pourquoi commencer par Telegram

Telegram a une API de bots officielle et gratuite. Tu écris à ton bot depuis ton téléphone, il appelle ton agent, il te répond. C'est le canal le plus simple, à faire en premier.

CanalAPI officielleParticularitéChapitre
TelegramOuiPolling ou webhookcelui-ci
SignalNon (outil communautaire)Connexion permanente à signal-cli9
Slack, WhatsApp, iMessage…Selon le serviceVia le Chat SDK de Vercel, ou un canal écrit sur le même modèle14

L'architecture : un cœur, plusieurs canaux

Chaque canal ne fait que trois choses : recevoir (texte ou audio), appeler le cœur, renvoyer la réponse. Toute la logique (commandes, historique, voix, rapports) vit dans un seul fichier.

agent-example/src/channels/core.ts

import { buildAgent } from "../agent/build";
import { getAgentConfig } from "../config";
import { isDatabaseConfigured } from "../lib/db";
import { logEvent, shortHash } from "../lib/log";
import { rateLimit } from "../lib/ratelimit";
import { mediaTypeFor, type Attachment } from "../lib/attachment";
import { createAvatarVideo, waitForVideo } from "../lib/heygen-video";
import { listWorkspace, readWorkspaceFile, workspaceRoot } from "../lib/workspace";
import { toSpokenScript } from "../lib/spoken";
import { summarizeConversation } from "../lib/summary";
import { appendHistory, clearHistory, compactHistory, getReport, latestReport, listReports, loadHistory } from "../lib/store";
import { speak, transcribeAudio, type Speech } from "../lib/voice";

export type Channel = "telegram" | "signal" | "web";

export type Incoming = {
  channel: Channel;
  chatId: string;
  text?: string;
  audio?: Uint8Array;
};

export type Reply = {
  /** What the bot understood, when the input was a voice message. */
  heard?: string;
  text: string;
  voice?: Speech;
  /** A file from the workspace, requested with /fichier. */
  file?: Attachment;
  video?: Attachment;
  /** Work that finishes later (a video render): the channel sends it when it resolves. Never rejects. */
  deferred?: Promise<Reply>;
};

const HELP = `Commandes :
/rapport <sujet> : rédige et enregistre un rapport écrit
/rapports : liste tes derniers rapports
/voix [numéro] : lit un rapport à voix haute (le dernier par défaut, sinon la dernière réponse)
/video [numéro] : fabrique une vidéo avec avatar à partir d'un rapport (si activé)
/fichiers : liste les fichiers créés par l'agent
/fichier <chemin> : t'envoie un de ces fichiers
/reset : efface la conversation
/aide : cette aide
Envoie aussi un message vocal : il sera transcrit.`;

/**
 * One entry point for every channel: Telegram, Signal, and whatever you add next.
 * It adds what every channel needs and none should reimplement: a rate limit,
 * a safety net around failures, and one log line per request.
 */
export async function handleIncoming(input: Incoming): Promise<Reply> {
  const chat = shortHash(`${input.channel}:${input.chatId}`);
  const limit = rateLimit(`${input.channel}:${input.chatId}`, Number(process.env.RATE_LIMIT_PER_MINUTE ?? 8));
  if (!limit.ok) {
    logEvent({ event: "rate_limited", channel: input.channel, chat });
    return { text: `Trop de messages d'affilée. Réessaie dans ${limit.retryAfterSec} s.` };
  }

  const started = Date.now();
  try {
    const reply = await processIncoming(input, chat);
    logEvent({ event: "reply", channel: input.channel, chat, ms: Date.now() - started });
    return reply;
  } catch (error) {
    // The user must never be left in silence, and must never see internals (keys, SQL, stack traces).
    logEvent({ event: "error", channel: input.channel, chat, ms: Date.now() - started, message: String(error) });
    return { text: "Une erreur est survenue de mon côté. Réessaie dans un instant ; si ça persiste, regarde les logs." };
  }
}

async function processIncoming(input: Incoming, chat: string): Promise<Reply> {
  const chatKey = `${input.channel}:${input.chatId}`;
  const { id: namespace } = getAgentConfig();

  let text = input.text?.trim() ?? "";
  let heard: string | undefined;
  if (!text && input.audio) {
    text = (await transcribeAudio(input.audio)).trim();
    if (!text) return { text: "Je n'ai rien compris à ce message vocal. Peux-tu réessayer ?" };
    heard = text;
  }
  if (!text) return { text: HELP };

  const [command, ...rest] = text.split(/\s+/);
  const argument = rest.join(" ").trim();

  switch (command.toLowerCase()) {
    case "/aide":
    case "/start":
    case "/help":
      return { text: HELP };

    case "/reset":
      await clearHistory(chatKey);
      return { text: "Conversation effacée." };

    case "/fichiers": {
      if (!getAgentConfig().workspace) return { text: "Cet agent n'a pas d'espace de travail." };
      const files = await listWorkspace(workspaceRoot(namespace));
      if (files.length === 0) return { text: "Aucun fichier pour l'instant." };
      return { text: files.map((f) => `${f.path} (${f.bytes} o)`).join("\n") + "\n\n/fichier <chemin> pour en recevoir un." };
    }

    case "/fichier": {
      if (!getAgentConfig().workspace) return { text: "Cet agent n'a pas d'espace de travail." };
      if (!argument) return { text: "Utilisation : /fichier <chemin>. /fichiers pour la liste." };
      try {
        const data = await readWorkspaceFile(workspaceRoot(namespace), argument);
        const filename = argument.split("/").pop() ?? "fichier";
        return { text: `Voici ${argument}.`, file: { data, filename, mediaType: mediaTypeFor(filename) } };
      } catch {
        return { text: "Fichier introuvable. /fichiers pour la liste." };
      }
    }

    case "/rapports": {
      if (!isDatabaseConfigured()) return { text: "Les rapports demandent une base de données." };
      const reports = await listReports(namespace);
      if (reports.length === 0) return { text: "Aucun rapport pour l'instant. Essaie /rapport <sujet>." };
      return { text: reports.map((r) => `#${r.id} · ${r.title}`).join("\n") + "\n\n/voix <numéro> pour en écouter un." };
    }

    case "/voix": {
      const source = await pickSource(namespace, chatKey, argument);
      if (typeof source !== "string") return source;
      return { text: "Voici la version audio.", voice: await speak(await toSpokenScript(source)) };
    }

    case "/video": {
      if (input.channel === "web") return { text: "/video est disponible sur Telegram et Signal." };
      // Opt-in, because every render spends HeyGen credits.
      if (process.env.HEYGEN_VIDEO_ENABLED !== "true") {
        return { text: "Les vidéos sont désactivées. Active-les avec HEYGEN_VIDEO_ENABLED=true : chaque rendu consomme des crédits HeyGen." };
      }
      if (!process.env.HEYGEN_API_KEY || !process.env.HEYGEN_AVATAR_ID) {
        return { text: "Il manque HEYGEN_API_KEY ou HEYGEN_AVATAR_ID." };
      }
      const quota = rateLimit(`video:${chatKey}`, Number(process.env.HEYGEN_VIDEO_PER_DAY ?? 3), 24 * 3_600_000);
      if (!quota.ok) return { text: `Limite de vidéos par jour atteinte. Réessaie dans environ ${Math.ceil(quota.retryAfterSec / 3600)} h.` };

      const source = await pickSource(namespace, chatKey, argument);
      if (typeof source !== "string") return source;
      const videoId = await createAvatarVideo(await toSpokenScript(source));
      logEvent({ event: "video_started", chat, videoId });
      return { text: "Rendu lancé. Je t'envoie la vidéo dès qu'elle est prête (quelques minutes).", deferred: renderVideo(videoId, chat) };
    }

    case "/rapport":
      text = argument
        ? `Write a complete, well-structured report in Markdown about: ${argument}. Use recall for any project context. When it is finished, save it with saveReport, then reply with the report.`
        : "Write a complete, well-structured report in Markdown on the current state of our work, based on this conversation and your memory. When it is finished, save it with saveReport, then reply with the report.";
      break;
  }

  const history = await loadHistory(chatKey);
  const started = Date.now();
  const result = await buildAgent().generate({
    messages: [...history, { role: "user", content: text }],
    // A stuck model or tool must not hold the request forever.
    timeout: { totalMs: Number(process.env.AGENT_TIMEOUT_MS ?? 240_000) },
  });
  const answer = result.text.trim() || "(pas de réponse)";

  // Cost visibility: which tools ran, how many steps, how many tokens.
  logEvent({
    event: "agent_run",
    chat,
    steps: result.steps.length,
    tools: result.steps.flatMap((step) => step.toolCalls.map((call) => call.toolName)),
    inputTokens: result.totalUsage.inputTokens,
    outputTokens: result.totalUsage.outputTokens,
    ms: Date.now() - started,
  });

  // Store the user's words, not the long internal /rapport instruction.
  await appendHistory(
    chatKey,
    { role: "user", content: heard ?? input.text ?? text },
    { role: "assistant", content: answer },
  );
  // Off the critical path: the user already has their answer.
  compactHistory(chatKey, summarizeConversation, {
    threshold: Number(process.env.HISTORY_COMPACT_AT ?? 40),
  }).catch((error) => logEvent({ event: "compaction_error", message: String(error) }));
  return { heard, text: answer };
}

/** Which text to read aloud or film: a report by number, the latest report, or the last answer. */
async function pickSource(namespace: string, chatKey: string, argument: string): Promise<string | Reply> {
  let source: string | undefined;
  if (isDatabaseConfigured()) {
    const wanted = Number.parseInt(argument.replace("#", ""), 10);
    if (argument && Number.isNaN(wanted)) return { text: "Utilisation : ajoute le numéro du rapport, ou rien pour le dernier." };
    const report = argument ? await getReport(namespace, wanted) : await latestReport(namespace);
    if (argument && !report) return { text: `Rapport #${wanted} introuvable. /rapports pour la liste.` };
    source = report?.body;
  }
  source ??= [...(await loadHistory(chatKey))].reverse().find((m) => m.role === "assistant")?.content;
  return source ?? { text: "Rien à lire pour l'instant. Demande d'abord un /rapport." };
}

/** Telegram bots can upload files up to 50 MB; stay below. Above that we hand over the (expiring) link. */
const MAX_VIDEO_BYTES = 45 * 1024 * 1024;

async function renderVideo(videoId: string, chat: string): Promise<Reply> {
  try {
    const url = await waitForVideo(videoId);
    const response = await fetch(url);
    if (!response.ok) throw new Error(`download failed (${response.status})`);
    const data = new Uint8Array(await response.arrayBuffer());
    logEvent({ event: "video_ready", chat, videoId, bytes: data.length });
    if (data.length > MAX_VIDEO_BYTES) {
      return { text: `La vidéo est prête mais trop lourde pour être envoyée ici. Lien temporaire : ${url}` };
    }
    return { text: "Voici ta vidéo.", video: { data, filename: "rapport.mp4", mediaType: "video/mp4" } };
  } catch (error) {
    logEvent({ event: "video_error", chat, videoId, message: String(error) });
    return { text: "Le rendu vidéo a échoué. Regarde les logs ; aucun crédit n'est garanti remboursé, vérifie ton compte HeyGen." };
  }
}

À retenir :

  • Un seul point d'entrée (handleIncoming) : ajouter un canal ne demande aucune modification de l'agent.
  • L'historique est en base (table chat_history), pour qu'un redémarrage ou un autre conteneur ne fasse pas perdre la conversation. Sans base, l'agent répond sans historique.
  • /rapport et /voix sont traitées ici ; elles sont détaillées aux chapitres 12 et 13.

Créer le bot

  1. Dans Telegram, ouvre la conversation avec @BotFather, envoie /newbot, choisis un nom et un identifiant se terminant par bot.
  2. BotFather te donne un jeton. Traite-le comme un mot de passe.
  3. Mets-le dans agent-example/.env : TELEGRAM_BOT_TOKEN=...

Deux modes de réception

agent-example/src/channels/telegram.ts

import { allowed } from "../lib/allowlist";
import {
  deleteWebhook,
  downloadFile,
  getUpdates,
  sendAudio,
  sendDocument,
  sendText,
  sendTyping,
  sendVideo,
  setWebhook,
  type TelegramMessage,
  type TelegramUpdate,
} from "../lib/telegram";
import { handleIncoming } from "./core";

export const telegramEnabled = () => Boolean(process.env.TELEGRAM_BOT_TOKEN);

/** One incoming Telegram message, whichever way it reached us (polling or webhook). */
export async function processTelegramMessage(message: TelegramMessage) {
  const chatId = message.chat.id;

  if (!allowed("TELEGRAM_ALLOWED_CHAT_IDS", chatId)) {
    // Help the owner find their id during setup; reveal nothing else.
    if (message.chat.type === "private") {
      await sendText(chatId, `Accès refusé. Ton identifiant de chat est ${chatId} : ajoute-le à TELEGRAM_ALLOWED_CHAT_IDS.`);
    }
    return;
  }

  await sendTyping(chatId);
  const fileId = message.voice?.file_id ?? message.audio?.file_id;
  const reply = await handleIncoming({
    channel: "telegram",
    chatId: String(chatId),
    text: message.text,
    audio: fileId ? await downloadFile(fileId) : undefined,
  });

  if (reply.heard) await sendText(chatId, `🎙 ${reply.heard}`);
  await sendText(chatId, reply.text);
  if (reply.voice) await sendAudio(chatId, reply.voice.data, reply.voice.filename, reply.voice.mediaType);
  if (reply.file) await sendDocument(chatId, reply.file.data, reply.file.filename, reply.file.mediaType);

  // A video render takes minutes: the first reply has gone out, this one follows when it is ready.
  if (reply.deferred) {
    const later = await reply.deferred;
    await sendText(chatId, later.text);
    if (later.video) await sendVideo(chatId, later.video.data, later.video.filename, later.video.mediaType);
  }
}

/** Webhook mode: Telegram calls us. Returns false when the secret is wrong. */
export function handleTelegramWebhook(secretHeader: string | undefined, update: TelegramUpdate): boolean {
  const secret = process.env.TELEGRAM_WEBHOOK_SECRET;
  if (!secret || secretHeader !== secret) return false;
  if (update.message) {
    // Do not make Telegram wait: it re-sends slow webhooks. Work continues in this long-lived process.
    processTelegramMessage(update.message).catch((error) => console.error("telegram handler failed", error));
  }
  return true;
}

/**
 * Starts the Telegram channel.
 *  - PUBLIC_URL set  -> webhook mode (registers https://PUBLIC_URL/channels/telegram)
 *  - otherwise       -> long polling (works behind a home router, on a laptop, anywhere)
 */
export async function startTelegram() {
  const publicUrl = process.env.PUBLIC_URL;
  if (publicUrl) {
    const secret = process.env.TELEGRAM_WEBHOOK_SECRET;
    if (!secret) throw new Error("TELEGRAM_WEBHOOK_SECRET is required when PUBLIC_URL is set");
    await setWebhook(`${publicUrl.replace(/\/$/, "")}/channels/telegram`, secret);
    console.log("telegram: webhook mode");
    return;
  }

  await deleteWebhook(); // polling and webhook are mutually exclusive
  console.log("telegram: polling mode");
  let offset = 0;
  for (;;) {
    try {
      const updates = await getUpdates(offset, AbortSignal.timeout(65_000));
      for (const update of updates) {
        offset = update.update_id + 1;
        if (update.message) {
          processTelegramMessage(update.message).catch((error) => console.error("telegram handler failed", error));
        }
      }
    } catch (error) {
      console.error("telegram polling error, retrying in 5 s", error);
      await new Promise((resolve) => setTimeout(resolve, 5000));
    }
  }
}
ModeActivationAvantagesInconvénients
Long polling (défaut)PUBLIC_URL videAucune URL publique, aucun certificat : marche sur un portable, derrière une box, sur un Raspberry PiIl faut un processus qui tourne en permanence
WebhookPUBLIC_URL=https://agent.exemple.com + TELEGRAM_WEBHOOK_SECRETTelegram appelle ton serveur ; compatible avec les hébergeurs qui endorment les conteneurs inactifsIl faut une URL HTTPS publique

Deux détails importants :

  • Les deux modes sont exclusifs chez Telegram : le démarrage supprime l'ancien webhook avant de passer en polling.
  • En webhook, Telegram ré-envoie un appel trop lent. Le code répond tout de suite et continue le travail ensuite.

Les protections

  1. Liste blanche de chats : n'importe qui peut écrire à ton bot si son nom est connu. Seuls les identifiants listés dans TELEGRAM_ALLOWED_CHAT_IDS sont servis ; liste vide = personne.
  2. Secret de webhook : Telegram renvoie la valeur donnée à setWebhook dans l'en-tête x-telegram-bot-api-secret-token. Sans elle, n'importe qui pourrait se faire passer pour Telegram.

agent-example/src/lib/allowlist.ts

/** Comma-separated env list -> set. An empty or missing list allows NO ONE. */
export function allowed(envName: string, value: string | number): boolean {
  const list = (process.env[envName] ?? "")
    .split(",")
    .map((s) => s.trim())
    .filter(Boolean);
  return list.includes(String(value));
}

Le client Telegram

agent-example/src/lib/telegram.ts

const api = (method: string) => `https://api.telegram.org/bot${process.env.TELEGRAM_BOT_TOKEN}/${method}`;

async function call<T>(method: string, body: Record<string, unknown> | FormData): Promise<T> {
  const response = await fetch(api(method), {
    method: "POST",
    ...(body instanceof FormData
      ? { body }
      : { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }),
  });
  const json = (await response.json()) as { ok: boolean; result: T; description?: string };
  if (!json.ok) throw new Error(`Telegram ${method}: ${json.description ?? response.status}`);
  return json.result;
}

/** Telegram limits a message to 4096 characters. Cut on a paragraph or line break when possible. */
export function splitMessage(text: string, max = 4000): string[] {
  const parts: string[] = [];
  let rest = text;
  while (rest.length > max) {
    let cut = rest.lastIndexOf("\n\n", max);
    if (cut < max / 2) cut = rest.lastIndexOf("\n", max);
    if (cut < max / 2) cut = max;
    parts.push(rest.slice(0, cut).trimEnd());
    rest = rest.slice(cut).trimStart();
  }
  if (rest) parts.push(rest);
  return parts;
}

export async function sendText(chatId: number | string, text: string) {
  for (const part of splitMessage(text)) {
    await call("sendMessage", { chat_id: chatId, text: part });
  }
}

export const sendTyping = (chatId: number | string) =>
  call("sendChatAction", { chat_id: chatId, action: "typing" }).catch(() => undefined);

export async function sendAudio(chatId: number | string, data: Uint8Array, filename: string, mediaType: string) {
  const form = new FormData();
  form.set("chat_id", String(chatId));
  form.set("audio", new Blob([data as BlobPart], { type: mediaType }), filename);
  await call("sendAudio", form);
}

export async function sendDocument(chatId: number | string, data: Uint8Array, filename: string, mediaType: string) {
  const form = new FormData();
  form.set("chat_id", String(chatId));
  form.set("document", new Blob([data as BlobPart], { type: mediaType }), filename);
  await call("sendDocument", form);
}

export async function sendVideo(chatId: number | string, data: Uint8Array, filename: string, mediaType: string) {
  const form = new FormData();
  form.set("chat_id", String(chatId));
  form.set("video", new Blob([data as BlobPart], { type: mediaType }), filename);
  await call("sendVideo", form);
}

/** Download a voice note or audio file the user sent. */
export async function downloadFile(fileId: string): Promise<Uint8Array> {
  const file = await call<{ file_path?: string }>("getFile", { file_id: fileId });
  if (!file.file_path) throw new Error("Telegram returned no file_path");
  const response = await fetch(`https://api.telegram.org/file/bot${process.env.TELEGRAM_BOT_TOKEN}/${file.file_path}`);
  if (!response.ok) throw new Error(`Telegram file download failed (${response.status})`);
  return new Uint8Array(await response.arrayBuffer());
}

export type TelegramMessage = {
  chat: { id: number; type: string };
  text?: string;
  voice?: { file_id: string };
  audio?: { file_id: string };
};
export type TelegramUpdate = { update_id: number; message?: TelegramMessage };

/** Long polling: works anywhere, no public URL needed. */
export const getUpdates = (offset: number, signal: AbortSignal) =>
  fetch(api("getUpdates"), {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ offset, timeout: 50, allowed_updates: ["message"] }),
    signal,
  }).then(async (r) => {
    const json = (await r.json()) as { ok: boolean; result: TelegramUpdate[]; description?: string };
    if (!json.ok) throw new Error(`Telegram getUpdates: ${json.description ?? r.status}`);
    return json.result;
  });

export const deleteWebhook = () => call("deleteWebhook", {});

export const setWebhook = (url: string, secret: string) =>
  call("setWebhook", { url, secret_token: secret, allowed_updates: ["message"] });

Quelques méthodes de l'API Bot suffisent : sendMessage, sendChatAction, sendAudio, getFile, getUpdates, setWebhook. Telegram limite un message à 4096 caractères ; splitMessage découpe proprement les longs rapports.

Autoriser ton chat

  1. Lance l'agent (npm run dev) et écris n'importe quoi à ton bot. Il répond : « Accès refusé. Ton identifiant de chat est 123456789 ».
  2. Ajoute-le dans agent-example/.env : TELEGRAM_ALLOWED_CHAT_IDS=123456789 (plusieurs : séparés par des virgules), puis relance.

Point de contrôle

Depuis ton téléphone, envoie « Salut, que sais-tu de mon projet ? » : l'agent répond. Envoie /aide : la liste des commandes s'affiche. Depuis un autre compte Telegram : refus.