0

我构建了一个生产应用程序,它使用 Twilio Programmable Chat 来实现其功能之一。我突然想到,该应用程序每天都会创建大量的聊天频道,并且无法自动使它们过期。Twilio 将您限制为 1,000 个聊天频道(我相信),如果我不使用某种每晚运行的预定作业清理它们,很快就会达到限制。

因此,理想的解决方案是使用 node.js 和某种调度程序来检索我之前创建的所有旧聊天频道,并将它们全部删除以进行维护。

4

1 回答 1

1

这是我写的每晚凌晨 2 点运行并删除之前创建的所有旧聊天频道的代码。我使用 node-cron 来处理调度,其余部分使用 node.js。我希望它可以帮助任何有类似需求的人。我还在这里为该项目创建了一个公共 github 存储库。

// **************************************************************
//This script handles deleting old Twilio Chat channels.It should be run as a scheduled job every night during off hours 
// **************************************************************
// **************************************************************

// Use express for listener only
const express = require("express");
app = express();

// We use node-cron to run this script every day at 2 AM
const cron = require("node-cron");

// Twilio authentication keys and values - be sure to replace with your account SID and Keys from the Twilio console at https://www.twilio.com/console and https://www.twilio.com/console/chat/dashboard
const twilioAccountSid = 'AC52419cd4407b77c253fff2eda1c56503'; //ACCOUNT SID from Twilio Console
const twilioChatSService = 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; //Chat Service SID from Twilio Chat Console
const theToken = `XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`; //AUTH TOKEN from Twilio Console

// Run daily at 2 AM
cron.schedule("00 02 * * *", function () {
    console.log("---------------------");
    console.log("Running Cron Job");

    // Retrieve all chat channels we created since we last checked
    const client = require('twilio')(twilioAccountSid, theToken);

    client.chat.services(twilioChatSService)
        .channels
        .list({ limit: 1000 })
        .then(channels => {
            channels.forEach(c => {
                // Remove each channel one by one
                client.chat.services(twilioChatSService)
                    .channels(c.sid)
                    .remove();

                console.log(`removed - ${c.sid}`);
            })
        });

    console.log(`Finished fetching chat channels`);
});

console.log(`Waiting until 2AM each day to delete all old chat channels`);
app.listen("3128");

https://github.com/kboice23/Twilio-Scheduled-Chat-Channel-Cleanup

于 2020-05-12T20:36:42.220 回答