You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js Telegram Bot出现ReferenceError: Markup未定义错误及功能需求

解决Telegraf Bot中Markup未定义的错误

问题场景

你需要实现Telegram Bot收到文本消息后,自动回复带描述的图片,并附带可跳转指定网站的内联按钮,但运行代码时控制台抛出Markup is not defined的引用错误。

原代码

const { Telegraf, Extra } = require("telegraf");
const bot = new Telegraf('my bot token');
bot.on('text', async (ctx) => {
  const message = `Test Message`;

  const imageUrl = 'https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.bbc.com%2Fnews%2Fworld-us-canada-37493165&psig=AOvVaw0d_XITsiMbIX2n-18x9DGF&ust=1693310036962000&source=images&cd=vfe&opi=89978449&ved=0CBAQjRxqFwoTCMjv8sul_4ADFQAAAAAdAAAAABAE';
  const caption = message;
  const urlButton = Markup.inlineKeyboard([
    Markup.urlButton('Example Button', 'www.google.com'),
  ]);
});

bot.launch();
console.log('Bot Online!')

错误信息

/home/runner/chatgpt-bot-telegram/index.js:38
  const urlButton = Markup.inlineKeyboard([
                    ^

ReferenceError: Markup is not defined
    at /home/runner/chatgpt-bot-telegram/index.js:38:21
    at /home/runner/chatgpt-bot-telegram/node_modules/telegraf/lib/composer.js:167:111
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async execute (/home/runner/chatgpt-bot-telegram/node_modules/telegraf/lib/composer.js:485:17)
    at async /home/runner/chatgpt-bot-telegram/node_modules/telegraf/lib/composer.js:486:21
    at async execute (/home/runner/chatgpt-bot-telegram/node_modules/telegraf/lib/composer.js:485:17)

Node.js v18.12.1
repl process died unexpectedly: exit status 1

修复方案

  1. 导入Markup模块:原代码仅导入了Telegraf和Extra,未导入Markup,需要在require语句中补充。
  2. 补充消息发送逻辑:原代码仅定义了按钮,但未调用发送图片的方法,需添加ctx.replyWithPhoto完成消息推送。
  3. 修正URL格式:内联按钮的跳转URL需包含完整协议(如https://),否则无法正常跳转。

修复后的完整代码

const { Telegraf, Markup } = require("telegraf");
const bot = new Telegraf('my bot token');

bot.on('text', async (ctx) => {
  const message = `Test Message`;
  const imageUrl = 'https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.bbc.com%2Fnews%2Fworld-us-canada-37493165&psig=AOvVaw0d_XITsiMbIX2n-18x9DGF&ust=1693310036962000&source=images&cd=vfe&opi=89978449&ved=0CBAQjRxqFwoTCMjv8sul_4ADFQAAAAAdAAAAABAE';
  const caption = message;

  // 创建内联按钮组
  const inlineKeyboard = Markup.inlineKeyboard([
    Markup.urlButton('Example Button', 'https://www.google.com'),
  ]);

  // 发送带图片、描述和内联按钮的消息
  await ctx.replyWithPhoto(imageUrl, {
    caption: caption,
    ...inlineKeyboard
  });
});

bot.launch();
console.log('Bot Online!')

内容的提问来源于stack exchange,提问作者Darwin Danish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 01:11:25