all repos — kokyo @ d3e94c1b0d41b8bf8530ecb6d38c41166dc8f01f

Chatbot and CLI tool for Swiss public transports

bots/telegram.ts (view raw)

 1import { Telegram, getUpdates } from "@gramio/wrappergram";
 2import { findStopByName } from "@api/locationInformationRequest.ts";
 3import { InlineKeyboard } from "@gramio/keyboards";
 4import { getNextDepartures } from "@api/stopEvent.ts";
 5import logger from "@lib/logger.ts";
 6
 7const telegram = new Telegram(Deno.env.get("TELEGRAM_TOKEN") as string);
 8
 9const formatContent = (content: string) =>
10  content
11    .replaceAll("-", "\\-")
12    .replaceAll(".", "\\.")
13    .replaceAll("(", "\\(")
14    .replaceAll(")", "\\)");
15
16for await (const update of getUpdates(telegram)) {
17  console.log(update);
18
19  // On new message
20  if (update.message) {
21    if (!update.message?.from) {
22      console.error("No 'from' in message");
23      continue;
24    }
25
26    logger.info(
27      `New message from ${update.message.from.username}: ${update.message.text}`
28    );
29
30    telegram.api.setMyCommands({
31      commands: [
32        { command: "aide", description: "Explique comment utiliser le bot" },
33      ],
34    });
35
36    if (update.message.text === "/aide") {
37      telegram.api.sendMessage({
38        chat_id: update.message.from.id,
39        text: `Hey ! Je suis un bot qui te permet d'obtenir rapidement des informations sur les transports en commun dans toute la Suisse.
40Entre le nom d'un arrêt et laisse-toi guider !
41
42> Ce bot est en cours de développement actif. Les fonctionnalités sont pour le moment limitées.
43
44/aide - Affiche ce message`,
45      });
46    } else {
47      const stopLists = await findStopByName(update.message.text);
48      let keyboard = new InlineKeyboard();
49      for (const stop of stopLists)
50        keyboard = keyboard
51          .text(stop.name, {
52            stopName: stop.name?.slice(0, 20),
53            stopRef: stop.stopRef,
54          })
55          .row();
56
57      const response = await telegram.api.sendMessage({
58        chat_id: update.message.from.id,
59        text: "Quel arrêt correspond ?",
60        reply_markup: keyboard,
61      });
62      console.log(response, keyboard);
63    }
64  }
65
66  // On keyboard event (callback query)
67  else if (update.callback_query) {
68    const payload = JSON.parse(update.callback_query.data);
69
70    logger.info(
71      `New request from ${update.callback_query.from.username}: ${payload.stopName} (${payload.stopRef})`
72    );
73
74    if (payload?.stopRef) {
75      const nextDepartures = await getNextDepartures(payload.stopRef);
76      const text = formatContent(`Prochains départs depuis *${
77        payload.stopName
78      }*:\n
79${nextDepartures
80  .map(
81    item =>
82      `*${item.departure}*    _${item.departureIn} min_   *${item.serviceName}*  ${item.serviceTypeIcon}    ${item.to}`
83  )
84  .join("\n")}`);
85      const response = await telegram.api.sendMessage({
86        chat_id: update.callback_query.from.id,
87        parse_mode: "MarkdownV2",
88        text,
89      });
90      console.log(response);
91    }
92  }
93}