Node.js Telegram Bot:入群欢迎向规则接受回调传参 规避并发冲突
Node.js Telegram Bot 入群欢迎功能开发问题
已实现的功能链路
开发者基于Node.js开发Telegram Bot的新用户入群自动欢迎功能,完整流程为:
- 新用户加入群聊时触发
Welcome(e)处理函数,函数内执行以下操作:- 打印入群日志
- 构建带两类按钮的inlineKeyboard组件:规则接受回调按钮、规则跳转链接按钮
- 对新入群用户设置临时发言权限限制,禁止其发送消息、媒体内容及其他互动内容
- 向群内推送入群欢迎提示消息,消息回复关联新用户的入群通知
对应实现代码如下:
function Welcome(e) { console.log("Neuer Member"); console.log(e); // Das ist der, der joint let markup = Extra.markup( Markup.inlineKeyboard([ Markup.callbackButton('I read the rules and accept them!', 'AcceptRules'), Markup.urlButton('Read the rules here', 'https://t.me/MyBot') ]) ); bot.telegram.restrictChatMember(e.chat.id, e.from.id, { can_send_messages: false, can_send_media_messages: false, can_send_other_messages: false }); e.reply( `Welcome to the chat @${e.message.from.username}, please make sure to read the rules https://t.me/MyBot\n\nYou will be able to chat in here once you read them :3\n\n If you have trouble you can use this button right here to accept AFTER you read them ;3`, markup, Extra.inReplyTo(e.update.message.message_id) ) } - 用户点击欢迎消息上的
AcceptRules回调按钮时,触发预先绑定的bot.action('AcceptRules', e)处理逻辑,核心流程为:- 构建仅带规则跳转链接的键盘组件
- 调用权限放开方法解除用户的临时发言限制
- 将原欢迎消息内容更新为规则阅读完成的感谢提示
对应实现代码如下:
bot.action('AcceptRules', e => { let markup = Extra.markup( Markup.inlineKeyboard([ Markup.urlButton('Read the rules here', 'https://t.me/VenWaifuBot') ]) ); // 放开用户发言权限 allow(e); e.editMessageText( `✅Thank you ${e.update.callback_query.from.first_name} for reading the rules! I hope you have fun here ;3\n\nYou can always read the rules here, they will be updates from time to time`, markup ); console.warn(e); });
当前待解决的核心问题
Welcome处理函数中获取的新入群用户标识属于函数局部变量,无法直接传递到后续触发的AcceptRules回调处理函数中- 若采用临时全局变量存储用户信息,多用户并发入群场景下会出现数据被覆盖干扰的并发问题
- 若采用数组存储用户信息的方案存在逻辑冗余,需要找到可靠的实现方案,确保只有对应入群的用户才能触发和自己关联的规则接受按钮逻辑
内容的提问来源于stack exchange,提问作者Ven
相关产品推荐
相关产品推荐

