-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
190 lines (136 loc) · 5.95 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
console.log("Hello from Indexjs");
const express = require("express");
const body_parser = require("body-parser");
const axios = require("axios");
const fs = require("fs");
const s3 = require("./s3"); //Adding the aws s3 connection file.
require('dotenv').config();
const sharp = require('sharp');
const app = express().use(body_parser.json());
const token = process.env.TOKEN;
const mytoken = process.env.MYTOKEN;
//Remove "8080 ||" if you're hosting it in heroku or elsewhere
app.listen(8080 || process.env.PORT, () => {
console.log("Website is Running");
});
//To Verify if through GET is working - Needed for FB to verify if /webhook works
app.get("/webhook", (req, res) => {
let mode = req.query["hub.mode"];
let challange = req.query["hub.challenge"];
let token = req.query["hub.verify_token"];
if (mode && token) {
if (mode === "subscribe" && token === mytoken) {
res.status(200).send(challange);
} else {
res.status(403);
}
}
});
// webhook through POST
app.post("/webhook", (req, res) => {
let body_content = req.body;
// console.log(JSON.stringify(body_content, null, 2));
//Conditional statement to check if the body_content (the request body) contains an object property.
if (body_content.object) {
console.log("Body has an Object and is Inside it");
//Getting the Whatsapp senders ID
let wappid = body_content.entry[0].changes[0].value.contacts[0].wa_id;
let messages = body_content.entry[0].changes[0].value.messages;
// Iterate through messages array
for (let i = 0; i < messages.length; i++) {
let message = messages[i];
// Check if the message type is "image"
if (message.type === "image") {
let imageInfo = message.image;
// Accessing the type of media send and image id
let mime_type = imageInfo.mime_type;
let id = imageInfo.id;
console.log("mime_type:", mime_type);
console.log("id:", id);
//sending a request to GraphAPI with Image Id and Whatsapp Sender ID
sendGetRequest(id, wappid)
}
//Check if the message type is "Video"
else if (message.type === "video") {
let imageInfo = message.video;
let mime_type = imageInfo.mime_type;
let id = imageInfo.id;
console.log("mime_type:", mime_type);
console.log("id:", id);
//sending a request to GraphAPI with Video Id and Whatsapp Sender ID
sendGetRequest(id, wappid)
}
}
res.sendStatus(200);
} else {
res.sendStatus(404);
}
});
async function sendGetRequest(id, wappid) {
newurl = "https://graph.facebook.com/v18.0/" + id;
try {
const response = await axios.get(newurl, {
headers: {
"Authorization": "Bearer " + token // Add your Token to the header of the API request
}
})
// console.log(response) if you want to see the response you get.
if (response.data && response.data.url) {
//Get the Image Url
const mediaURL = response.data.url;
//Get the Image type, need it for saving in AWS S3
const mediaMimeType = response.data.mime_type;
console.log(" Response from Graph V.18 - image: " + mediaURL);
console.log(" Mime type: " + mediaMimeType);
sendImgDownload(mediaURL, mediaMimeType, wappid, id);
} else {
console.log("Unexpected response format:", response.data);
}
} catch (error) {
console.error('Error saving image from sendgetrequest:', error.message);
}
}
async function sendImgDownload(mediaURL, mediaMimeType, wappid, id) {
filename = `WA_${id}`;
let data = '';
try {
const response = await axios.get(mediaURL, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': mediaMimeType,
},
responseType: 'arraybuffer', // This is important for binary data
});
// Check if the response contains data
if (response.data) {
// Splitting the mimetype to save in AWS
if (mediaMimeType.startsWith("image/")) {
file_extension = filename + "." + mediaMimeType.split('/')[1]
typeoffile = mediaMimeType.split('/')[0]
somedata = Buffer.from(response.data, 'binary')
// Save the binary data to a variable
//Sending it to aws
sendtoaws(file_extension, mediaMimeType, somedata, wappid, typeoffile);
await fs.writeFileSync(file_extension, Buffer.from(response.data, 'binary'));
console.log(`Media saved to ${file_extension} successfully.`);
} else if (mediaMimeType.startsWith("video/")) {
file_extension = filename + "." + mediaMimeType.split('/')[1]
typeoffile = mediaMimeType.split('/')[0]
somedata = Buffer.from(response.data, 'binary')
// Save the binary data to a file
sendtoaws(file_extension, mediaMimeType, somedata, wappid, typeoffile);
await fs.writeFileSync(file_extension, Buffer.from(response.data, 'binary'));
console.log(`Media saved to ${file_extension} successfully.`);
}
} else {
console.error('Empty response data received.');
}
} catch (error) {
console.error('Error sending to AWS:', error.message);
}
}
async function sendtoaws(file_extension, mediaMimeType, somedata, wappid, typeoffile) {
//Uploading stuff to the S3 bucket
await s3.upload(file_extension, mediaMimeType, somedata, wappid, typeoffile);
console.log("Image uploaded to AWS S3 successfully");
}