如何使用node-telegram-bot获取Telegram聊天记录?
获取Telegram机器人与用户的历史消息方案
首先明确:bot.getChat(chatId) 仅用于获取聊天的基础信息(如用户昵称、聊天类型),不返回任何消息记录,这就是你调用后只得到用户信息的原因。下面是几种可行的解决方案:
方案1:实时存储收到的消息(最推荐)
Telegram Bot API本身没有提供直接获取历史消息的接口,所以最可靠的方式是在机器人运行时,将每一条收到的消息实时存储到本地文件、数据库(如MongoDB、SQLite)中,后续需要时直接读取存储的数据。
示例代码(本地文件存储):
const TelegramBot = require('node-telegram-bot-api'); require('dotenv').config(); const fs = require('fs').promises; const path = require('path'); const TOKEN = process.env.TOKEN; const bot = new TelegramBot(TOKEN, { polling: true }); const MESSAGE_STORE_PATH = path.join(__dirname, 'message-history.json'); // 初始化存储文件 async function initStore() { try { await fs.access(MESSAGE_STORE_PATH); } catch { await fs.writeFile(MESSAGE_STORE_PATH, JSON.stringify([])); } } // 存储消息 async function saveMessage(message) { const history = JSON.parse(await fs.readFile(MESSAGE_STORE_PATH, 'utf8')); history.push({ chatId: message.chat.id, userId: message.from.id, text: message.text, timestamp: message.date, messageId: message.message_id }); await fs.writeFile(MESSAGE_STORE_PATH, JSON.stringify(history, null, 2)); } // 监听所有收到的消息 bot.on('message', async (msg) => { await saveMessage(msg); // 你的其他业务逻辑 }); // 启动时初始化存储 initStore();
方案2:用getUpdates回溯近期消息
如果机器人刚上线,或者之前没存储消息,可以调用getUpdates方法获取Telegram服务器保存的近期更新(通常保留24小时内的消息)。注意:该方法只能获取未被机器人处理过的更新,或者通过设置offset参数来拉取更早的记录。
示例代码:
const TelegramBot = require('node-telegram-bot-api'); require('dotenv').config(); const TOKEN = process.env.TOKEN; const bot = new TelegramBot(TOKEN, { polling: false }); // 先关闭自动polling async function fetchRecentMessages(chatId) { let offset = 0; let allMessages = []; while (true) { const updates = await bot.getUpdates({ offset, limit: 100, timeout: 30 }); if (updates.length === 0) break; // 筛选目标聊天的消息 const chatMessages = updates .filter(update => update.message?.chat.id === chatId) .map(update => update.message); allMessages.push(...chatMessages); offset = updates[updates.length - 1].update_id + 1; } console.log('近期消息记录:', allMessages); return allMessages; } // 调用示例,替换为你的chatId fetchRecentMessages(123456789);
方案3:使用MTProto库(适用于需要获取更早历史的场景)
如果需要获取机器人运行前的历史消息,只能通过Telegram的MTProto协议实现。可以使用封装好的库(如gram-js),比原生Core API更容易上手,但需要创建Telegram应用并获取API ID/Hash。
示例思路(gram-js):
const { TelegramClient } = require('telegram'); const { StringSession } = require('telegram/sessions'); require('dotenv').config(); const apiId = parseInt(process.env.TELEGRAM_API_ID); const apiHash = process.env.TELEGRAM_API_HASH; const stringSession = new StringSession(''); // 首次登录后会生成会话字符串 async function fetchChatHistory(chatId) { const client = new TelegramClient(stringSession, apiId, apiHash, { connectionRetries: 5, }); await client.start({ phoneNumber: async () => prompt('输入你的手机号:'), password: async () => prompt('输入密码(如果有):'), phoneCode: async () => prompt('输入收到的验证码:'), onError: (err) => console.log(err), }); // 获取聊天历史,limit控制获取数量 const messages = await client.getMessages(chatId, { limit: 100 }); console.log('历史消息:', messages.map(msg => msg.text)); // 保存会话字符串,下次登录无需重复验证 console.log('会话字符串:', client.session.save()); await client.disconnect(); } // 调用示例,chatId可以是用户名、手机号或数字ID fetchChatHistory('@yourBotUsername');
内容的提问来源于stack exchange,提问作者Dummy Cron
相关产品推荐
相关产品推荐

