Here is the code I wrote to run every night at 2AM and delete all of the old chat channels created previously. I used node-cron to handle the scheduling and node.js for the rest. I hope it helps anyone who has a similar need. I also created a public github repo for the project here.
// **************************************************************
//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