node.js - TypeError:无法读取未定义的属性“聊天”
问题描述
我在为 Telegram bot 编写的 Expressjs 代码上收到此错误 我使用 Nginx 在 CloudVps 上托管此代码 我将其用于 Telegram Bot API webhook
它是一个 Telegram 聊天机器人,当用户输入匹配时会设置一些自动回复,它会发送自动回复。
来自日志文件的错误
TypeError: Cannot read property 'chat' of undefined
at app.post (/var/www/hellobot/index.js:22:37)
at Layer.handle [as handle_request] (/var/www/hellobot/node_modules/express/lib/router/layer.js:95:5)
at next (/var/www/hellobot/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/var/www/hellobot/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/var/www/hellobot/node_modules/express/lib/router/layer.js:95:5)
at /var/www/hellobot/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/var/www/hellobot/node_modules/express/lib/router/index.js:335:12)
at next (/var/www/hellobot/node_modules/express/lib/router/index.js:275:10)
at /var/www/hellobot/node_modules/body-parser/lib/read.js:130:5
at invokeCallback (/var/www/hellobot/node_modules/raw-body/index.js:224:16)
这是我的代码
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
app.post('/', (req, res, next) => {
var Content = require('./blogposts.json');
var random = Content.blogtext[Math.floor(Math.random() * Content.blogtext.length)];
const chatId = req.body.message.chat.id;
const sentMessage = req.body.message.text || req.body.message.sticker.file_id;
if (sentMessage.match(/start/gi)) {
axios.post(`${url}${apiToken}/sendMessage`, {
chat_id: chatId,
text: 'Hello I am Bot',
})
.then((response) => {
next();
res.status(200).send(response);
return res.end();
}).catch((error) => {
res.send(error);
});
} else if (sentMessage.match(/posts/gi)) {
axios.post(`${url}${apiToken}/sendMessage`, {
chat_id: chatId,
text: random.blogtext,
})
.then((response) => {
next();
res.status(200).send(response);
}).catch((error) => {
res.send(error);
});
} else {
axios.post(`${url}${apiToken}/sendMessage`, {
chat_id: chatId,
text: 'Sorry answer not found',
})
.then((response) => {
res.status(200).send(response);
}).catch((error) => {
res.send(error);
});
}
});
解决方案
推荐阅读
- php - 使用 While/Foreach 插入
- python - Pandas groupby 将自定义功能应用于每个组
- php - 致命错误:未捕获的 TypeError:无法访问字符串上类型字符串的偏移量
- html - css和html没有连接
- java - 使用 Junit5 和 Mockito 比较 2 个 Json 字符串
- java - 用不同数量的字符串词解析行
- python - 基于 Mozilla Authentication 使用 python 发出 API 请求
- javascript - 有什么方法可以正确显示 IDN?
- c - 如何将指针传递给函数并在那里创建一个以指针为起始地址的矩阵?
- javascript - 如何让不和谐机器人在它所在的服务器中发送消息?