You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.5 KiB
TypeScript

import { execute } from '../../database/db'; // Corrected import path
import axios from 'axios';
import dotenv from 'dotenv';
dotenv.config();
const API_URL = process.env.API_URL;
const INSTANCE_NAME = process.env.INSTANCE_NAME;
const API_KEY = process.env.API_KEY;
if (!API_URL || !INSTANCE_NAME || !API_KEY) {
throw new Error('Required environment variables are not defined.');
}
// Fetch all groups and identify the community and linked groups
export async function fetchGroups(communityId: string): Promise<Set<string>> {
const linkedGroups = new Set<string>();
try {
const response = await axios.get(`${API_URL}/group/fetchAllGroups/${INSTANCE_NAME}?getParticipants=false`, {
headers: {
apikey: API_KEY,
},
});
if (Array.isArray(response.data)) {
for (const group of response.data) {
if (group.id === communityId) {
console.log(`Community ID: ${communityId}`);
} else if (group.linkedParent === communityId) {
linkedGroups.add(group.id);
console.log(`Linked Group ID: ${group.id}`);
// Save the group to the database
execute(
'INSERT OR REPLACE INTO groups (id, name, linked_parent) VALUES (?, ?, ?)',
[group.id, group.subject || 'Unnamed Group', group.linkedParent] // Provide a default name if missing
);
}
}
} else {
console.error('Unexpected response format:', response.data);
}
} catch (error) {
console.error('Error fetching groups:', error.response ? error.response.data : error.message);
}
return linkedGroups;
}
// Configure the webhook in Evolution API
export async function configureWebhook(webhookUrl: string) {
try {
const response = await axios.post(
`${API_URL}/webhook/set/${INSTANCE_NAME}`,
{
webhook: {
url: webhookUrl,
enabled: true,
webhook_by_events: true,
webhook_base64: true,
events: [
'MESSAGES_UPSERT', // New or updated messages
'GROUPS_UPSERT', // New or updated groups
'GROUP_PARTICIPANTS_UPDATE', // Group participant changes
'GROUP_UPDATE', // Group metadata changes (optional)
],
},
},
{
headers: {
'Content-Type': 'application/json',
apikey: API_KEY,
},
}
);
console.log('Webhook configured successfully:', response.data);
} catch (error) {
console.error('Error configuring webhook:', error.response ? error.response.data : error.message);
}
}