I'm developing a telegram chatbot using SendPulse API and Node.js that automatically replies after receiving a specific incoming message. But the issue I'm facing is that after receiving the incoming message through webhook it continuously sends the text message instead of just sending it once.
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}`))
OUTPUT:
[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}
Note: I have to call setAccessToken as the authorization token expires every hour in SendPulse.