如何仅在Express服务器中执行一次代码?

发布于 2025-02-01 10:02:25 字数 2685 浏览 2 评论 0原文

我正在使用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中到期。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

り繁华旳梦境 2025-02-08 10:02:25

在运行后,尝试将文本添加到End res.status(200)。我想这是重复的,因为您没有做出任何回应。

Try after running send text add this to the end res.status(200). I am guess it repeats itself because your not responding with anything.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文