Skip to content

Commit d404812

Browse files
committed
add send message to bot for messenger
1 parent 60b4be5 commit d404812

File tree

5 files changed

+74
-23
lines changed

5 files changed

+74
-23
lines changed
Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { BOT_URL } from "@/config";
1+
import { BOT_ENDPOINT, PUBLIC_DOMAIN } from "@/config";
22
import axios from "axios";
33

44
export class BaseChannel {
@@ -14,40 +14,43 @@ export class BaseChannel {
1414
this.channelType = channelType;
1515
}
1616

17-
public async postMessageToBot({ userId, data }) {
17+
public async postMessageToBot({ userId, message = '', data }) {
18+
const uid = this.initConversationId(userId);
1819
try {
19-
const uId = this.initConversationId(userId);
20-
await axios({
20+
const postMsg = await axios({
2121
method: 'POST',
22-
url: BOT_URL,
22+
url: BOT_ENDPOINT,
2323
data: {
2424
conversation: {
25-
id: uId,
25+
id: uid,
2626
},
2727
from: {
2828
id: userId,
2929
},
3030
recipient: {
3131
id: this.contactId,
3232
},
33-
type: 'event',
34-
name: 'payload',
35-
data,
36-
id: uId,
33+
data: data || false,
34+
text: message,
35+
type: 'message',
36+
id: uid,
3737
channelId: this.channelType,
38-
serviceUrl: 'http://localhost:3000/api',
38+
serviceUrl: PUBLIC_DOMAIN,
3939
},
4040
})
41+
if (postMsg.data.success) {
42+
console.log(
43+
`[${this.channelType} - ${this.contactName} ${this.contactId}] - [Conversation ID: ${uid}] - [Send message to bot - Message: ${message}] - [Data: ${data}]`
44+
)
45+
}
4146
} catch (error) {
42-
console.log(`Can not send data to bot!`, userId);
43-
console.log(error.message);
47+
console.log(
48+
`[${this.channelType} - ${this.contactName} ${this.contactId}] - [Conversation ID: ${uid}] - [Can not send message to bot - Message: ${message}] - [Error: ${error.message}]`
49+
);
4450
}
4551
}
4652

47-
initConversationId(useId: string) {
48-
return this.contactId + '-' + useId
53+
initConversationId(userId: string) {
54+
return this.contactId + '-' + userId
4955
}
50-
51-
// public async verifyWebhook(req: Request, res: Response) {
52-
// };
5356
}

server/src/channels/messenger.channel.ts

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { Helper } from "@/utils/helper";
12
import { Request, Response } from "express";
23
import { BaseChannel } from "./base.channel";
34

@@ -7,7 +8,6 @@ export class MessengerChannel extends BaseChannel {
78
messengerPostURL: string;
89
credentials: string;
910

10-
1111
constructor(id: string, contactId: string, contactName: string, channelType: string, credentials: string) {
1212
super(id, contactId, contactName, channelType);
1313

@@ -36,11 +36,40 @@ export class MessengerChannel extends BaseChannel {
3636
return challenge;
3737
} else {
3838
console.error(`Verification channel ${this.channelType} - ${this.contactName} ${this.contactId} failed!`);
39-
return null;
39+
return;
4040
}
4141
}
4242

4343
public async prepareMessage(req: Request, res: Response) {
44+
const { object, entry } = req.body;
45+
46+
if (object != 'page' || !Array.isArray(entry)) return;
47+
48+
entry.forEach(pageEntry => {
49+
if (!Array.isArray(pageEntry.messaging)) return;
50+
51+
pageEntry.messaging.forEach(async (messagingEvent) => {
52+
if (messagingEvent.messaging_customer_information)
53+
return this.sendAddressToBot({
54+
userId: messagingEvent.sender.id,
55+
address: messagingEvent.messaging_customer_information.screens[0].responses,
56+
});
57+
58+
if (!messagingEvent.message && !messagingEvent.postback) return;
59+
60+
const senderId = messagingEvent.sender.id;
61+
const messageText = messagingEvent.message && messagingEvent.message.text;
62+
const payload = messagingEvent.postback && messagingEvent.postback.payload;
63+
const quick_reply = messagingEvent.message && messagingEvent.message.quick_reply;
64+
65+
if (senderId == this.contactId) return; //Agent replied to user => skip
66+
67+
return this.postMessageToBot({ userId: senderId, message: messageText || payload, data: null });
68+
});
69+
});
70+
}
4471

72+
sendAddressToBot({ userId, address }) {
73+
return this.postMessageToBot({ userId, message: 'ADDRESS', data: { USER_INFORMATION: Helper.arrayToObj(address) } });
4574
}
4675
}

server/src/config/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,5 +28,5 @@ export const {
2828
FIREBASE_UNIVERSE_DOMAIN,
2929
FIREBASE_DATABASE_URL,
3030
PUBLIC_DOMAIN,
31-
BOT_URL,
31+
BOT_ENDPOINT,
3232
} = process.env;

server/src/utils/helper.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,12 @@ export class Helper {
55
if (!date) return null;
66
return moment(date).format('DD/MM/YYYY HH:mm:ss');
77
}
8-
}
98

9+
public static arrayToObj(arr) {
10+
const obj = {};
11+
arr.forEach((item) => {
12+
obj[item.key] = item.value;
13+
});
14+
return obj;
15+
}
16+
}

server/src/utils/logger.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1+
import { LOG_DIR } from '@config';
12
import { existsSync, mkdirSync } from 'node:fs';
23
import { join } from 'node:path';
34
import winston from 'winston';
45
import WinstonDaily from 'winston-daily-rotate-file';
5-
import { LOG_DIR } from '@config';
66

77
const colorizer = winston.format.colorize({
88
colors: {
@@ -68,6 +68,18 @@ logger.add(
6868
})
6969
);
7070

71+
['log', 'error', 'warn', 'info'].forEach((method) => {
72+
const originalMethod = console[method];
73+
console[method] = function () {
74+
const modifiedArgs = Array.from(arguments).map((arg) => (typeof arg === 'object' ? JSON.stringify(arg) : arg));
75+
originalMethod.call(console, ...modifiedArgs);
76+
console[method] = function () {
77+
if (method === 'log') return logger.info.apply(logger, arguments);
78+
return logger[method].apply(logger, arguments);
79+
};
80+
};
81+
});
82+
7183
const stream = {
7284
write: (message: string) => {
7385
logger.info(message.substring(0, message.lastIndexOf('\n')));

0 commit comments

Comments
 (0)