跳转至私聊时如何保存Telegram群组Chat ID?
问题:Telegram机器人无法通过Session保存群组Chat ID用于后续发布活动
我正在开发一款Telegram机器人,功能是让用户在私聊中完成活动内容编辑,之后发布到触发操作的对应群组。流程为:用户在群组内触发机器人,机器人展示按钮引导用户跳转至私聊,此时需要保存该群组的Chat ID,用于后续发布活动。我尝试用Session实现,但没能成功,相关代码如下:
群组内触发的/event命令
bot.command('event', checkIfGroup, checkIfAdmin, async (ctx) => { ctx.session.groupId = ctx.chat.id; const message = await ctx.reply('Welcome!', { reply_markup: { inline_keyboard: [ [{ text: 'Start', url: 'https://t.me/bot_name?start=true' }] ] } }); });
私聊中的/start命令
bot.command('start', checkIfPrivate, async (ctx) => { await ctx.reply('...'); await ctx.reply('Write the event name:'); });
消息处理逻辑
bot.on('message', checkIfPrivate, async (ctx) => { const builder = ctx.session.builder; ... builder.setTitle(text); ... const script = builder.formatEvent(); await ctx.reply(script, { parse_mode: 'MarkdownV2', link_preview_options: { is_disabled: true }, reply_markup: { inline_keyboard: [ [ { text: 'Publish', callback_data: 'publish' }, { text: 'Cancel', callback_data: 'cancel' } ] ] } }); }
发布回调逻辑
bot.callbackQuery('publish', async (ctx) => { if (!ctx.callbackQuery.message?.chat.id) { return; } const chatId = ctx.session.groupId; const builder = ctx.session.builder; const script = builder.formatEvent(); const photoId = builder.getPhotoId(); const message = await ctx.api.sendMessage(chatId, script, { parse_mode: 'MarkdownV2', link_preview_options: { is_disabled: true } }); ... });
问题原因
Telegraf的Session默认基于Chat ID存储,群组对话的Session和私聊对话的Session是完全独立的存储实例。你在群组里设置的ctx.session.groupId仅存在于群组的Session中,跳转至私聊后,无法从私聊的Session中读取到该值。
解决方案
将群组Chat ID作为参数附加到跳转链接的start命令中,在私聊的/start命令里解析参数并保存到私聊的Session中。
修改后的代码:
1. 群组内/event命令
bot.command('event', checkIfGroup, checkIfAdmin, async (ctx) => { // 将群组ID作为参数传入start链接 const startUrl = `https://t.me/bot_name?start=${ctx.chat.id}`; const message = await ctx.reply('Welcome!', { reply_markup: { inline_keyboard: [ [{ text: 'Start', url: startUrl }] ] } }); });
2. 私聊中的/start命令
bot.command('start', checkIfPrivate, async (ctx) => { // 解析start命令后的参数(即群组ID) const groupId = ctx.message.text.split(' ')[1]; if (groupId) { // 将群组ID保存到私聊的Session中 ctx.session.groupId = groupId; } await ctx.reply('...'); await ctx.reply('Write the event name:'); });
3. 发布回调逻辑(补充校验)
bot.callbackQuery('publish', async (ctx) => { if (!ctx.callbackQuery.message?.chat.id) { return; } const chatId = ctx.session.groupId; if (!chatId) { return ctx.reply('未找到目标群组,请先在群组内触发活动编辑'); } const builder = ctx.session.builder; const script = builder.formatEvent(); const photoId = builder.getPhotoId(); try { await ctx.api.sendMessage(chatId, script, { parse_mode: 'MarkdownV2', link_preview_options: { is_disabled: true } }); await ctx.reply('活动已成功发布到目标群组'); } catch (err) { await ctx.reply('发布失败,请检查机器人是否在目标群组中且有权限发送消息'); } });
内容的提问来源于stack exchange,提问作者NiceToMytyuk
相关产品推荐
相关产品推荐

