Telegram Bot AI Integration Troubleshooting Journal
- Published on
- Authors
- Name
- Jerry
Purpose
Integrating Google’s generative AI—Gemini—into a Telegram Bot.
Implementation Steps
1. Create a Telegram Bot
- Create a new bot in Telegram’s BotFather.
- Set the bot’s commands (commands can accept parameters while being called).
2. Obtain a Gemini API Key
- Create an API key on the Google AI platform.
- The Gemini 1.5 Flash model supports up to 15 queries per minute.
3. Connect Home Assistant (HA) + Nabu Casa
Telegram Bot needs to communicate with Home Assistant, with two available methods:
Method 1: Polling
- Sends requests continuously to achieve real-time communication.
- May result in duplicate messages due to network issues.
- No need to expose public IP or configure HTTPS.
- Telegram discourages this method due to frequent server queries.
Method 2: Webhook (Recommended)
- When the bot receives a new command, it sends a request to HA.
- Requires public access, usually needing:
- Static public IP or dynamic DNS.
- A valid SSL certificate.
- Since I subscribe to Nabu Casa cloud service, this solves the public access issue conveniently.
Home Assistant Configuration
configuration.yaml
1. Configure telegram_bot:
- platform: webhooks
api_key: !secret telegram_bot_api_key
allowed_chat_ids:
- !secret personal_id
- !secret group_id
trusted_networks:
- 149.154.160.0/20 # Telegram server IP
- 91.108.4.0/22 # Telegram server IP
- 127.0.0.1 # Required for Nabu Casa
rest_command
2. Add ask_gemini:
url: !secret gemini_flash_url
method: post
payload: '{"contents":[{"parts":[{"text":"{{ prompt }}"}]}]}'
content_type: 'application/json'
3. Set up Automation
alias: telegram command /gemini
description: 'Handle /gemini command'
triggers:
- platform: event
event_type: telegram_command
event_data:
command: /gemini
- platform: event
event_type: telegram_command
event_data:
command: /gemini@my_telegram_bot
conditions: []
actions:
- service: rest_command.ask_gemini
data:
prompt: "{% for word in trigger.event.data['args'] %}{{ word }} {% endfor %}"
response_variable: gemini_response
- if:
- condition: template
value_template: "{{ gemini_response['status'] == 200 }}"
then:
- service: telegram_bot.send_message
data:
message: >
{{
gemini_response['content']['candidates'][0]['content']['parts'][0]['text']
}}
target:
- "{{ trigger.event.data['chat_id'] }}"
parse_mode: plain_text
mode: single
Troubleshooting Notes
trusted_networks
** must include **127.0.0.1
- When using Nabu Casa, requests arrive at HA as
127.0.0.1
. - The default IP whitelist does not include
127.0.0.1
, which can cause Webhook to reject valid Telegram messages. - HA now follows Telegram’s recommendation of embedding a random **32-character **
secret_token
in the Webhook URL, minimizing security risks.
- When using Nabu Casa, requests arrive at HA as
YAML configurations for ****
telegram_bot
****** API Key and Chat ID should be quoted**- Prevents parsing errors.
Restart HA after modifying
telegram_bot
section in YAML configurations- Simply reloading YAML files will not apply changes.
Automation triggers should support both command formats
/gemini
(used in private chat or direct calls)./gemini@my_telegram_bot
(in group chats, Telegram appends the bot ID).- If the bot ID is missing in group chats, the command may not trigger automation.
Check Webhook status
curl https://api.telegram.org/bot{{bot_token}}/getWebhookInfo
Webhook prevents usage of ****
getUpdates
****** API**- Webhook and
getUpdates
API are mutually exclusive. - To use
getUpdates
(e.g., retrievingchat_id
), first delete the Webhook:curl https://api.telegram.org/bot{{bot_token}}/deleteWebhook
- Webhook will automatically rebind after HA restarts.
- Webhook and
Gemini API response structure
- Currently extracting responses using
gemini_response['content']['candidates'][0]['content']['parts'][0]['text']
. - This structure is based on observed test data and may change in future updates.
- Currently extracting responses using
📌 If you’re also experimenting with Telegram Bot + AI, let’s connect! 😊
目的
在 Telegram Bot 中集成 Google 的生成式 AI——Gemini。
实现步骤
1. 创建 Telegram Bot
- 在 Telegram 的 BotFather 中创建一个新的机器人。
- 设置机器人的指令(command),命令在使用时可以携带参数。
2. 获取 Gemini API Key
- 在 Google AI Studio 创建 API Key。
- Gemini 1.5 Flash 模型最高支持每分钟 15 次问答。
3. 连接 Home Assistant(HA)+ Nabu Casa
Telegram Bot 需要与 Home Assistant 进行通信,有两种方式可选:
方式 1:Polling(轮询)
- 通过不断发送请求实现实时通信。
- 可能因网络问题导致重复接收/发送相同的信息。
- 无需暴露公网 IP 和端口,也不需要额外的 HTTPS 配置。
- 由于会频繁查询 Telegram 服务器,官方并不推荐。
方式 2:Webhook(推荐)
- 机器人有新命令时,会向 HA 发送网络请求。
- 需要公网访问权限,通常需要:
- 配置静态公网 IP,或使用动态 DNS。
- 安装有效的 SSL 证书。
- 由于我订阅了 Nabu Casa 云服务,可以方便地解决公网访问问题。
配置 Home Assistant
configuration.yaml
1. 配置 telegram_bot:
- platform: webhooks
api_key: !secret telegram_bot_api_key
allowed_chat_ids:
- !secret personal_id
- !secret group_id
trusted_networks:
- 149.154.160.0/20 # Telegram 服务器 IP
- 91.108.4.0/22 # Telegram 服务器 IP
- 127.0.0.1 # 由于使用 Nabu Casa,需要加入此项
rest_command
2. 添加 ask_gemini:
url: !secret gemini_flash_url
method: post
payload: '{"contents":[{"parts":[{"text":"{{ prompt }}"}]}]}'
content_type: 'application/json'
3. 设置自动化
alias: telegram command /gemini
description: '处理 /gemini 命令'
triggers:
- platform: event
event_type: telegram_command
event_data:
command: /gemini
- platform: event
event_type: telegram_command
event_data:
command: /gemini@my_telegram_bot
conditions: []
actions:
- service: rest_command.ask_gemini
data:
prompt: "{% for word in trigger.event.data['args'] %}{{ word }} {% endfor %}"
response_variable: gemini_response
- if:
- condition: template
value_template: "{{ gemini_response['status'] == 200 }}"
then:
- service: telegram_bot.send_message
data:
message: >
{{
gemini_response['content']['candidates'][0]['content']['parts'][0]['text']
}}
target:
- "{{ trigger.event.data['chat_id'] }}"
parse_mode: plain_text
mode: single
踩坑记录
trusted_networks
需要包含127.0.0.1
- 使用 Nabu Casa 时,请求会以
127.0.0.1
形式到达 HA。 - 默认的 IP 白名单不包含
127.0.0.1
,会导致 Webhook 拒绝合法的 Telegram 消息。 - HA代码已遵循 Telegram 官方推荐的 Webhook URL 随机 32 位
secret_token
机制,因此即使加入127.0.0.1
到白名单,安全风险仍然较低。
- 使用 Nabu Casa 时,请求会以
YAML 配置的
telegram_bot
API Key 和 Chat ID 需要用引号包裹- 避免解析错误。
在 YAML 文件 更改
telegram_bot
配置后必须重启 HA- 仅重新加载 YAML 配置无法生效。
自动化触发需要同时支持两种命令格式
/gemini
(私聊或直接调用)。/gemini@my_telegram_bot
(群聊中默认会附加 Bot ID)。- 若未处理群聊格式,命令可能无法触发自动化。
获取 Webhook 状态的方法
curl https://api.telegram.org/bot{{bot_token}}/getWebhookInfo
Webhook 绑定后,无法使用
getUpdates
API- Webhook 与
getUpdates
API 互斥。 - 若需要
getUpdates
(如查询chat_id
),需先解绑 Webhook:curl https://api.telegram.org/bot{{bot_token}}/deleteWebhook
- Webhook 会在重启 HA 后重新绑定。
- Webhook 与
隐患:Gemini API 返回数据结构
- 目前使用
gemini_response['content']['candidates'][0]['content']['parts'][0]['text']
获取回复。 - 但未深入研究 Gemini API 文档,数据结构可能有变动风险。
- 目前使用
📌 如果你也在折腾 Telegram Bot + AI,欢迎交流! 😊