ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

telegram - SKILL

telegram - SKILL name: telegramdescription: Integracao completa com Telegram Bot API. Setup com BotFather, mensagens, webhooks, inline keyboards, grupos, canais. Boilerplates Node.js e Python.risk: criticalsource: communitydate_added: ‘2026-03-06’author: renattags:messagingtelegrambotswebhookstools:claude-codeantigravitycursorgemini-clicodex-cliTelegram Bot API - 专业集成概述与 Telegram Bot API 的完整集成。使用 BotFather 设置、消息、webhook、内联键盘、群组、频道。提供 Node.js 和 Python 样板代码。何时使用此技能当用户提到telegram或相关主题时当用户提到bot telegram或相关主题时当用户提到telegram bot或相关主题时当用户提到api telegram或相关主题时当用户提到chatbot telegram或相关主题时当用户提到mensagem telegram或相关主题时何时不使用此技能任务与 telegram 无关时更简单、更具体的工具可以处理该请求时用户需要无领域专长的通用帮助时工作原理使用官方 Bot API 在 Telegram 上实现专业机器人的技能。支持 Node.js/TypeScript 和 Python。概述Telegram Bot API 允许创建通过消息、命令、内联键盘、支付等与用户交互的机器人。机器人由 BotFather 创建并通过唯一令牌进行认证。Base URL:https://api.telegram.org/botTOKEN/METHOD_NAMEHTTP 方法:GET 和 POST参数格式:query string、application/x-www-form-urlencoded、application/json、multipart/form-data上传文件限制:下载 50MB上传 20MB通过 multipart通过 URL 50MBWebhook 支持的端口:443、80、88、8443前置条件:Telegram 账户通过 BotFather 创建的机器人提供令牌令牌格式123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11如果用户还没有创建机器人请指导他们在 Telegram 中与 BotFather 对话并发送/newbot。决策树用户需要创建机器人吗 ├── 是 → 下方使用 BotFather 设置部分 └── 否 → 使用什么语言 ├── Node.js/TypeScript └── Python → 想做什么 ├── 发送消息 → 消息类型部分 ├── 接收消息 → 接收更新部分 ├── 交互式键盘 → 键盘部分 ├── 管理群组/频道 → references/chat-management.md ├── Webhook 设置 → references/webhook-setup.md ├── 内联模式 → references/advanced-features.md ├── 支付 → references/advanced-features.md ├── AI 客服机器人 → AI 自动化部分 └── 完整 API 参考 → references/api-reference.md要用现成样板从零开始项目python scripts/setup_project.py--languagenodejs--path./meu-bot-telegram## 或python scripts/setup_project.py--languagepython--path./meu-bot-telegram要测试机器人令牌是否有效python scripts/test_bot.py--tokenSEU_TOKEN要发送测试消息python scripts/send_message.py--tokenSEU_TOKEN--chat-idCHAT_ID--textHello!使用 BotFather 设置打开 Telegram 并搜索 BotFather发送/newbot选择显示名称例如“我的超棒机器人”选择用户名必须以bot结尾例如meu_incrivel_botBotFather 返回令牌 - 安全保存BotFather 的实用命令/setdescription- 机器人描述/setabouttext- 机器人关于文本/setuserpic- 个人资料照片/setcommands- 命令列表/mybots- 管理现有机器人/setinline- 启用内联模式/setprivacy- 群组中的隐私模式环境变量TELEGRAM_BOT_TOKEN123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11Node.Js/TypeScript// Instalar: npm install telegraf dotenv// Para TypeScript: npm install -D typescriptimport{Telegraf}fromtelegraf;importdotenvfromdotenv;dotenv.config();constbotnewTelegraf(process.env.TELEGRAM_BOT_TOKEN!);bot.start((ctx){ctx.reply(Ola! Eu sou seu bot. Como posso ajudar?);});bot.on(text,(ctx){if(!ctx.message.text.startsWith(/)){ctx.reply(Voce disse:${ctx.message.text});}});bot.launch();Python## Instalar: Pip Install Python-Telegram-Bot Python-Dotenvimportosfromdotenvimportload_dotenvfromtelegramimportUpdatefromtelegram.extimportApplication,CommandHandler,MessageHandler,filters,ContextTypes load_dotenv()asyncdefstart(update:Update,context:ContextTypes.DEFAULT_TYPE):awaitupdate.message.reply_text(Ola! Eu sou seu bot. Como posso ajudar?)asyncdefecho(update:Update,context:ContextTypes.DEFAULT_TYPE):awaitupdate.message.reply_text(fVoce disse:{update.message.text})appApplication.builder().token(os.getenv(TELEGRAM_BOT_TOKEN)).build()app.add_handler(CommandHandler(start,start))app.add_handler(MessageHandler(filters.TEXT~filters.COMMAND,echo))app.run_polling()不使用库纯 HTTPimportrequests TOKENSEU_TOKENBASEfhttps://api.telegram.org/bot{TOKEN}## Verificar Botrrequests.get(f{BASE}/getMe)print(r.json())## Enviar Mensagemrrequests.post(f{BASE}/sendMessage,json{chat_id:CHAT_ID,text:Hello from pure HTTP!,parse_mode:HTML})print(r.json())消息类型Telegram 支持多种内容类型。所有方法都接受chat_id、reply_parameters用于回复、reply_markup用于键盘、disable_notification和protect_content。HTML推荐await bot.send_message(chat_idchat_id,text“Negrito,italico,codigo, link”,parse_mode“HTML”)MarkdownV2转义特殊字符_ * [ ] ( ) ~ # - | { } . !await bot.send_message(chat_idchat_id,text“Negrito,italico,codigo, link”,parse_mode“MarkdownV2”)## 照片按 URL、File_Id 或上传 await bot.send_photo(chat_id, photohttps://example.com/img.jpg, captionLegenda aqui) ## 文档 await bot.send_document(chat_id, documentopen(relatorio.pdf, rb), captionRelatorio mensal) ## 视频 await bot.send_video(chat_id, videohttps://example.com/video.mp4, captionAssista!) ## 音频 await bot.send_audio(chat_id, audioopen(musica.mp3, rb), titleMinha Musica) ## 语音带 Opus 的 Ogg await bot.send_voice(chat_id, voiceopen(audio.ogg, rb)) ## 位置 await bot.send_location(chat_id, latitude-23.5505, longitude-46.6333) ## 联系人 await bot.send_contact(chat_id, phone_number5511999999999, first_nameJoao) ## 投票 await bot.send_poll( chat_id, questionQual sua cor favorita?, options[Azul, Verde, Vermelho], is_anonymousFalse ) ## 媒体组 await bot.send_media_group(chat_id, media[ InputMediaPhoto(url1, captionFoto 1), InputMediaPhoto(url2), InputMediaVideo(url3) ]) ## 聊天动作打字、上传照片等 await bot.send_chat_action(chat_id, actiontyping)Node.Js 等效实现// Fotobot.sendPhoto(chatId,https://example.com/img.jpg,{caption:Legenda});// Documentobot.sendDocument(chatId,fs.createReadStream(relatorio.pdf),{caption:Relatorio});// Localizacaobot.sendLocation(chatId,-23.5505,-46.6333);// Enquetebot.sendPoll(chatId,Qual sua cor favorita?,[Azul,Verde,Vermelho]);内联键盘消息内的按钮fromtelegramimportInlineKeyboardButton,InlineKeyboardMarkup keyboardInlineKeyboardMarkup([[InlineKeyboardButton(Opcao A,callback_dataopt_a),InlineKeyboardButton(Opcao B,callback_dataopt_b)],[InlineKeyboardButton(Abrir Site,urlhttps://example.com)],[InlineKeyboardButton(Compartilhar,switch_inline_querytexto)]])awaitbot.send_message(chat_id,Escolha uma opcao:,reply_markupkeyboard)## Handler De Callbackasyncdefbutton_callback(update:Update,context:ContextTypes.DEFAULT_TYPE):queryupdate.callback_queryawaitquery.answer()# Importante: sempre responder o callbackawaitquery.edit_message_text(fVoce escolheu:{query.data})app.add_handler(CallbackQueryHandler(button_callback))回复键盘自定义键盘fromtelegramimportReplyKeyboardMarkup,KeyboardButton keyboardReplyKeyboardMarkup([[KeyboardButton(Enviar Localizacao,request_locationTrue)],[KeyboardButton(Enviar Contato,request_contactTrue)],[Opcao 1,Opcao 2]],resize_keyboardTrue,one_time_keyboardTrue)awaitbot.send_message(chat_id,Escolha:,reply_markupkeyboard)移除键盘fromtelegramimportReplyKeyboardRemoveawaitbot.send_message(chat_id,Teclado removido,reply_markupReplyKeyboardRemove())接收更新有两种接收更新的方式长轮询Long Polling和Webhooks。长轮询开发更简单适合开发。机器人定期向 Telegram 服务器发起请求。## Python-Telegram-Bot 已自动处理app.run_polling(allowed_updatesUpdate.ALL_TYPES)// Telegraf com pollingconstbotnewTelegraf(token);bot.launch();Webhooks生产对于生产环境webhook 更高效。Telegram 通过 POST 将更新发送到你的 HTTPS URL。阅读references/webhook-setup.md获取使用 Express、Flask、ngrok 和部署的完整配置。快速设置## Flask WebhookfromflaskimportFlask,requestimportrequests appFlask(__name__)TOKENSEU_TOKENBASEfhttps://api.telegram.org/bot{TOKEN}app.route(/webhook,methods[POST])defwebhook():updaterequest.get_json()ifmessageinupdateandtextinupdate[message]:chat_idupdate[message][chat][id]textupdate[message][text]requests.post(f{BASE}/sendMessage,json{chat_id:chat_id,text:fRecebi:{text}})returnOK,200## Registrar Webhookrequests.post(f{BASE}/setWebhook,json{url:https://seu-dominio.com/webhook,allowed_updates:[message,callback_query],secret_token:seu_secret_seguro_aqui})机器人命令注册命令以显示在 Telegram 菜单中fromtelegramimportBotCommandawaitbot.set_my_commands([BotCommand(start,Iniciar o bot),BotCommand(help,Ver comandos disponiveis),BotCommand(settings,Configuracoes),BotCommand(status,Ver status do servico),])通过 HTTPcurl-XPOSThttps://api.telegram.org/bot$TOKEN/setMyCommands\-HContent-Type: application/json\-d{commands:[{command:start,description:Iniciar o bot},{command:help,description:Ajuda}]}使用 AI 自动化AI 客服机器人Claude、GPT 等的模式fromtelegramimportUpdatefromtelegram.extimportApplication,MessageHandler,filters,ContextTypesimportanthropic# ou openaiclientanthropic.Anthropic()user_conversations{}# chat_id - messages historyasyncdefai_response(update:Update,context:ContextTypes.DEFAULT_TYPE):chat_idupdate.message.chat_id user_textupdate.message.text# Indicar que esta digitandoawaitcontext.bot.send_chat_action(chat_id,typing)# Manter historicoifchat_idnotinuser_conversations:user_conversations[chat_id][]user_conversations[chat_id].append({role:user,content:user_text})# Chamar IAresponseclient.messages.create(modelclaude-sonnet-4-20250514,max_tokens1024,systemVoce e um assistente prestativo. Responda em portugues.,messagesuser_conversations[chat_id])replyresponse.content[0].text user_conversations[chat_id].append({role:assistant,content:reply})# Limitar historico (ultimas 20 mensagens)iflen(user_conversations[chat_id])20:user_conversations[chat_id]user_conversations[chat_id][-20:]awaitupdate.message.reply_text(reply)appApplication.builder().token(TOKEN).build()app.add_handler(MessageHandler(filters.TEXT~filters.COMMAND,ai_response))app.run_polling()编辑文本await bot.edit_message_text(chat_idchat_id,message_idmsg.message_id,text“Texto atualizado!”,parse_mode“HTML”)编辑标记按钮await bot.edit_message_reply_markup(chat_idchat_id,message_idmsg.message_id,reply_markupnew_keyboard)删除消息await bot.delete_message(chat_idchat_id, message_idmsg.message_id)转发消息await bot.forward_message(chat_iddest_chat_id,from_chat_idsource_chat_id,message_idmsg.message_id)--- ## 错误处理 python from telegram.error import TelegramError, BadRequest, TimedOut, NetworkError async def safe_send(bot, chat_id, text, **kwargs): Envio com retry e tratamento de erros. max_retries 3 for attempt in range(max_retries): try: return await bot.send_message(chat_id, text, **kwargs) except TimedOut: if attempt max_retries - 1: await asyncio.sleep(2 ** attempt) continue raise except BadRequest as e: if chat not found in str(e).lower(): print(fChat {chat_id} nao encontrado) return None raise except NetworkError: if attempt max_retries - 1: await asyncio.sleep(2 ** attempt) continue raise速率限制私聊消息~30 条/秒群组消息每群组 ~20 条/分钟整体广播总计 ~30 条/秒批量通知在发送之间使用asyncio.sleep(0.05)以避免触发风控如果收到 429 错误请求过多请遵循返回的retry_after。文件参考主题文件Webhook 设置references/webhook-setup.md聊天管理references/chat-management.md高级功能references/advanced-features.md完整 API 参考references/api-reference.mdNode.js 样板assets/boilerplate/nodejs/Python 样板assets/boilerplate/python/负载示例assets/examples/最佳实践提供关于项目和需求的清晰、具体的上下文在应用到生产代码之前审查所有建议与其他互补技能结合以获得全面分析常见陷阱将此技能用于其领域专长之外的任务在不理解你的具体上下文的情况下应用建议未提供足够的项目上下文以进行准确分析相关技能instagram- 用于增强分析的互补技能social-orchestrator- 用于增强分析的互补技能whatsapp-cloud-api- 用于增强分析的互补技能局限性仅在任务明确匹配上述范围时使用此技能。不要将输出视为环境特定验证、测试或专家审查的替代品。如果缺少所需的输入、权限、安全边界或成功标准请停下来询问澄清。
返回列表