@@ -224,63 +224,43 @@ export class DifyService {
224224 headers: {
225225 Authorization: `Bearer ${dify.apiKey}`,
226226 },
227- responseType: 'stream',
228227 });
229228
230229 let conversationId;
231230 let answer = '';
232231
233- const stream = response.data;
234- const reader = new Readable().wrap(stream);
232+ const data = response.data.replaceAll('data: ', '');
235233
236- reader.on('data', (chunk) => {
237- const data = chunk.toString().replace(/data:\s*/g, '');
234+ const events = data.split('\n').filter((line) => line.trim() !== '');
238235
239- if (data.trim() === '' || !data.startsWith('{')) {
240- return;
241- }
242-
243- try {
244- const events = data.split('\n').filter((line) => line.trim() !== '');
236+ for (const eventString of events) {
237+ if (eventString.trim().startsWith('{')) {
238+ const event = JSON.parse(eventString);
245239
246- for (const eventString of events) {
247- if (eventString.trim().startsWith('{')) {
248- const event = JSON.parse(eventString);
249-
250- if (event?.event === 'agent_message') {
251- console.log('event:', event);
252- conversationId = conversationId ?? event?.conversation_id;
253- answer += event?.answer;
254- }
255- }
240+ if (event?.event === 'agent_message') {
241+ console.log('event:', event);
242+ conversationId = conversationId ?? event?.conversation_id;
243+ answer += event?.answer;
256244 }
257- } catch (error) {
258- console.error('Error parsing stream data:', error);
259245 }
260- });
261-
262- reader.on('end', async () => {
263- if (instance.integration === Integration.WHATSAPP_BAILEYS)
264- await instance.client.sendPresenceUpdate('paused', remoteJid);
246+ }
265247
266- const message = answer;
248+ if (instance.integration === Integration.WHATSAPP_BAILEYS)
249+ await instance.client.sendPresenceUpdate('paused', remoteJid);
267250
268- await this.sendMessageWhatsApp(instance, remoteJid, message, settings) ;
251+ const message = answer ;
269252
270- await this.prismaRepository.integrationSession.update({
271- where: {
272- id: session.id,
273- },
274- data: {
275- status: 'opened',
276- awaitUser: true,
277- sessionId: conversationId,
278- },
279- });
280- });
253+ await this.sendMessageWhatsApp(instance, remoteJid, message, settings);
281254
282- reader.on('error', (error) => {
283- console.error('Error reading stream:', error);
255+ await this.prismaRepository.integrationSession.update({
256+ where: {
257+ id: session.id,
258+ },
259+ data: {
260+ status: 'opened',
261+ awaitUser: true,
262+ sessionId: conversationId,
263+ },
284264 });
285265
286266 return;
0 commit comments