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

ReactJS引入node-telegram-bot-api报错:Uncaught TypeError: split读取错误

解决React应用中引入node-telegram-bot-api报错的问题

问题原因

node-telegram-bot-api是专为Node.js后端环境开发的库,它依赖Node.js的内置模块(比如http、process等),但React应用运行在浏览器环境中,浏览器不支持这些Node.js专属模块,因此直接导入就会触发运行时错误。

解决办法

1. 将机器人逻辑部署到后端(推荐方案)

把Telegram机器人的代码放在Node.js后端服务中(比如用Express搭建简单服务),React前端仅通过调用后端API来与机器人交互。

后端代码示例:

const TelegramBot = require('node-telegram-bot-api');
const express = require('express');
const app = express();
app.use(express.json());

// 初始化Telegram机器人
const token = '你的机器人token';
const bot = new TelegramBot(token, { polling: true });

// 监听机器人消息
bot.on('message', (msg) => {
  const chatId = msg.chat.id;
  bot.sendMessage(chatId, '收到你的消息了');
});

// 暴露API供前端调用
app.post('/api/send-telegram-message', (req, res) => {
  const { chatId, text } = req.body;
  bot.sendMessage(chatId, text)
    .then(() => res.json({ success: true }))
    .catch(err => res.status(500).json({ error: err.message }));
});

app.listen(3001, () => console.log('后端服务运行在3001端口'));

React前端调用示例:

const sendTelegramMessage = async () => {
  try {
    await fetch('http://localhost:3001/api/send-telegram-message', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ chatId: '目标聊天ID', text: '来自React的测试消息' })
    });
    console.log('消息发送成功');
  } catch (err) {
    console.error('发送失败:', err);
  }
};

2. 前端直接调用Telegram官方API(仅测试场景)

如果只是临时测试,不想搭建后端,可以直接调用Telegram的HTTP API,但生产环境绝对禁止这么做——机器人token会暴露在前端代码中,任何人都能获取并操控你的机器人。

代码示例:

const TELEGRAM_API = `https://api.telegram.org/bot${你的机器人token}/sendMessage`;

const sendMessage = async (chatId, text) => {
  try {
    const response = await fetch(TELEGRAM_API, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ chat_id: chatId, text })
    });
    const result = await response.json();
    console.log('发送结果:', result);
  } catch (err) {
    console.error('请求出错:', err);
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 22:35:15