Last active
October 17, 2024 11:26
-
-
Save DennyLoko/0e8957c5fcd9572927a1f6b901e444fe to your computer and use it in GitHub Desktop.
Chatwoot contacts cleaner
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ACCOUNT_ID = 11; // ID da conta | |
const USER_TOKEN = ''; // Token de usuário | |
const API_URL = ''; // URL do Chatwoot | |
async function getContacts(page = 1) { | |
const query = new URLSearchParams({ | |
page, | |
}); | |
const response = await fetch( | |
`${API_URL}/api/v1/accounts/${ACCOUNT_ID}/contacts?${query}`, | |
{ | |
method: 'GET', | |
headers: { | |
'Content-Type': 'application/json', | |
api_access_token: USER_TOKEN, | |
}, | |
} | |
); | |
return response.json(); | |
} | |
async function getAllContacts() { | |
const allContacts = []; | |
let currentPage = 1; | |
do { | |
console.log(`Fetching page ${currentPage}`); | |
const { payload, meta } = await getContacts(currentPage++); | |
allContacts.push(...payload); | |
if (allContacts.length >= meta.count) { | |
break; | |
} | |
} while (true); | |
return allContacts; | |
} | |
async function deleteContact(contact) { | |
console.log(`Deleting contact ${contact.name} (${contact.id})`); | |
const response = await fetch( | |
`${API_URL}/api/v1/accounts/${ACCOUNT_ID}/contacts/${contact.id}`, | |
{ | |
method: 'DELETE', | |
headers: { | |
'Content-Type': 'application/json', | |
api_access_token: USER_TOKEN, | |
}, | |
} | |
); | |
return response; | |
} | |
async function filterContacts(contacts) { | |
const contactsToKeep = ['+123456']; // Coloque todos números de contatos que deseja manter | |
return contacts.filter(contact => | |
contactsToKeep.includes(contact.phone_number) | |
); | |
} | |
async function main() { | |
const contacts = await getAllContacts(); | |
const contactsToKeep = await filterContacts(contacts); | |
for (const contact of contacts) { | |
if (!contactsToKeep.includes(contact)) { | |
await deleteContact(contact); | |
} | |
} | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment