以下の内容はhttps://shuzo-kino.hateblo.jp/entry/2025/06/13/211546より取得しました。


n8n + Telegram botで簡易な対話UIをつくる その2:メッセージ多重読みの防止

実際のところ

全体図


各ノード

execノード

今回はpodmanでn8nのインスタンスを作っているので、内部のtmpに保存するようにします

cat /tmp/last_update_id 2>/dev/null || echo 0
HTTP Requestノード

前の処理で入手したlast_update_id をoffsetとして設定
これにより多重読み込みを防止できます

https://api.telegram.org/bot{{YOUR_APP_TOKEN}}/getUpdates?offset={{ $json["stdout"].trim() }}
IFノード
{{ $json.result[0].message.text }}

が存在、かつ

{{ $json.result[0].message.text  == '/hi'}}
Code in Javascript

ある意味今回の肝
last_update_id をここで更新する

const items = $input.all();
const response = items[0]?.json || {};

if (!response.ok || !Array.isArray(response.result)) {
  return [];
}

const updates = response.result;

// 何も来てなければ終了
if (updates.length === 0) {
  return [];
}

// いま来ている update_id の最大値 + 1 を次回 offset として使う
const nextOffset = Math.max(...updates.map(u => u.update_id || 0)) + 1;

// 各 update を1アイテムとして返しつつ、nextOffset を一緒に持たせる
return updates.map(u => ({
  json: {
    ...u,
    nextOffset,
  },
}));
Execノード(二個目)

IFノードが正常に動いたときの奴
ここではじめてlast_update_idを更新する

echo "{{ $json.nextOffset }}" > /tmp/last_update_id
Telegram send a text messageノード

返ってくるJSONがメッセージパースを一個分だけ含むので、メッセージIDの取得の部分は以下のように

{{$json.message.chat.id}}



以上の内容はhttps://shuzo-kino.hateblo.jp/entry/2025/06/13/211546より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14