如何在express服务器中只执行一次代码?



我正在使用SendPulse API和Node.js开发一个电报聊天机器人,在收到特定的传入消息后自动回复。但我面临的问题是,通过webhook接收到传入消息后,它会不断发送文本消息,而不是只发送一次。

functions.js

var request = require('request');
require('dotenv').config("./env")
async function setAccessToken() {

var options = {
'method': 'POST',
'url': 'https://api.sendpulse.com/oauth/access_token',
'headers': {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"grant_type": "client_credentials",
'client_id': process.env.client_id,
'client_secret': process.env.client_secret,
})
};
request(options, function (error, response) {
if (error)
throw new Error(error);
body = JSON.parse(response.body)
process.env.token = body.access_token
});
}
const sendText = async (contact_id) => {
var options = {
'method': 'POST',
'url': 'https://api.sendpulse.com/telegram/contacts/send',
'headers': {
'client_id': process.env.client_id,
'client_secret': process.env.client_secret,
'Authorization': `Bearer ${process.env.token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
"contact_id": contact_id,
"message": {
"type": "text",
"text": "Hello from other side"
}
})
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body)
});
}
module.exports = {
sendText,
setAccessToken
}

index.js

require('dotenv').config()
const express = require("express")
const TA = require("./functions")
const app = express()
app.use(express.json())
app.post("/telegram", async (req, res) => {
if (req.body[0].contact.last_message === "Hello") {
contact_id = req.body[0].contact.id
await TA.sendText(contact_id)
}
})
nodeCron.schedule("*/1 * * * *", () => {
console.log("Setting access token")
TA.setAccessToken()

// res.sendStatus(200);
//res.end()
return res.status(200);
});
Port = process.env.PORT
app.listen(Port, () => console.log(`Listening to port ${Port}`))

输出:

[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
Listening to port 3000
{"success":true,"data":true}
{"success":true,"data":true}
{"success":true,"data":true}
{"success":true,"data":true}
{"success":true,"data":true}
{"success":true,"data":true}

注意:我必须调用setAccessToken作为授权令牌在SendPulse中每小时过期。

尝试运行send text后将此添加到末尾的res.status(200)。我猜它会重复自己,因为你没有回应任何事情。

最新更新