如何在Dialogflow ES构建的Telegram聊天机器人中获取用户first_name
从Dialogflow ES的Telegram payload中提取用户first_name的正确方法
你之前的路径错误导致无法提取到Telegram用户的first_name,正确的提取路径是agent.originalRequest.payload.from.first_name。
Telegram与Dialogflow集成时,用户身份信息会直接封装在agent.originalRequest.payload对象下,而非嵌套在data.message层级中。
修改后的完整代码
'use strict'; const functions = require('firebase-functions'); const {WebhookClient} = require('dialogflow-fulfillment'); const admin = require ('firebase-admin'); admin.initializeApp(); admin.auth(); const db = admin.firestore(); // 补充缺失的makeid函数实现 function makeid(length) { let result = ''; const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const charactersLength = characters.length; let counter = 0; while (counter < length) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); counter += 1; } return result; } exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => { const agent = new WebhookClient({ request, response }); function welcome(agent) { agent.add(`Hi! Do you want to create an account?`); } function createUser(agent) { agent.add(`Thank you! You have successfully created your account`); let uid = makeid(28); let email = agent.parameters.email; let password = agent.parameters.user_password; // 正确提取Telegram用户first_name,同时保留参数作为 fallback let display_name = agent.originalRequest.payload?.from?.first_name || agent.parameters.display_name; admin.auth().createUser({uid: uid, email: email, password: password}); db.collection('users').doc(uid).set({ uid: uid, display_name: display_name, }); } function fallback(agent) { agent.add(`I didn't understand`); agent.add(`I'm sorry, can you try again?`); } let intentMap = new Map(); intentMap.set('Welcome Intent', welcome); intentMap.set('account.creation', createUser); intentMap.set('Default Fallback Intent', fallback); agent.handleRequest(intentMap); });
关键说明
- 使用
agent.originalRequest.payload.from.first_name直接获取Telegram用户的名字 - 加入可选链操作符
?.防止因payload结构异常导致代码崩溃 - 保留
agent.parameters.display_name作为备选,确保在无法获取payload信息时仍有可用值 - 补充了代码中缺失的
makeid函数实现,避免运行报错
内容的提问来源于stack exchange,提问作者Yury_X
相关产品推荐
相关产品推荐

