@tiledesk/tiledesk-whatsapp-connector 0.1.23 → 0.1.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -7,6 +7,8 @@ const handlebars = require('handlebars');
7
7
  const fs = require('fs');
8
8
  const path = require('path');
9
9
  const pjson = require('./package.json');
10
+ const { v4: uuidv4 } = require('uuid');
11
+ const cors = require('cors');
10
12
 
11
13
  // tiledesk clients
12
14
  const { TiledeskClient } = require('@tiledesk/tiledesk-client');
@@ -15,25 +17,34 @@ const { TiledeskSubscriptionClient } = require('./tiledesk/TiledeskSubscriptionC
15
17
  const { TiledeskWhatsapp } = require('./tiledesk/TiledeskWhatsapp');
16
18
  const { TiledeskChannel } = require('./tiledesk/TiledeskChannel');
17
19
  const { TiledeskAppsClient } = require('./tiledesk/TiledeskAppsClient');
20
+ const { MessageHandler } = require('./tiledesk/MessageHandler');
18
21
 
19
22
  // mongo
20
23
  const { KVBaseMongo } = require('@tiledesk/tiledesk-kvbasemongo');
21
24
  const kvbase_collection = 'kvstore';
25
+ const db = new KVBaseMongo(kvbase_collection);
26
+
27
+ // redis
28
+ var redis = require('redis')
29
+ var redis_client;
22
30
 
23
31
  router.use(bodyParser.json());
24
32
  router.use(bodyParser.urlencoded({ extended: true }));
25
33
  router.use(express.static(path.join(__dirname, 'template')));
34
+ router.use(cors());
26
35
 
27
- var API_URL = null;
28
- var GRAPH_URL = null;
29
- var BASE_URL = null;
30
- var APPS_API_URL = null;
31
- var log = false;
36
+ let API_URL = null;
37
+ let GRAPH_URL = null;
38
+ let BASE_URL = null;
39
+ let APPS_API_URL = null;
40
+ let REDIS_HOST = null;
41
+ let REDIS_PORT = null;
42
+ let REDIS_PASSWORD = null;
43
+ let log = false;
32
44
 
33
- const db = new KVBaseMongo(kvbase_collection);
34
45
 
35
46
  router.get('/', async (req, res) => {
36
- res.send('Home works!')
47
+ res.send('Welcome to Tiledesk-WhatsApp Business connector!')
37
48
  })
38
49
 
39
50
  router.get('/detail', async (req, res) => {
@@ -175,14 +186,13 @@ router.get('/configure', async (req, res) => {
175
186
  projectId = req.query.project_id;
176
187
  token = req.query.token;
177
188
 
178
- let CONTENT_KEY = "whatsapp-" + projectId;
189
+ let proxy_url = BASE_URL + "/webhook/" + projectId;
179
190
 
191
+ let CONTENT_KEY = "whatsapp-" + projectId;
192
+
180
193
  let settings = await db.get(CONTENT_KEY);
181
194
  console.log("[KVDB] settings: ", settings);
182
195
 
183
- let proxy_url = BASE_URL + "/webhook/" + projectId;
184
- console.log("proxy_url: ", proxy_url);
185
-
186
196
  if (settings) {
187
197
 
188
198
  readHTMLFile('/configure.html', (err, html) => {
@@ -424,14 +434,13 @@ router.post('/disconnect', async (req, res) => {
424
434
  })
425
435
 
426
436
  router.post('/tiledesk', async (req, res) => {
427
-
428
437
  console.log("\n/tiledesk")
429
438
  //if (log) {
430
439
  //console.log("/tiledesk ---> tiledeskChannelMessage: " + JSON.stringify(req.body.payload));
431
440
  //}
432
441
 
433
442
  var tiledeskChannelMessage = req.body.payload;
434
- //console.log("(TILEDESK) Payload: ", JSON.stringify(req.body.payload));
443
+ console.log("(TILEDESK) Payload: ", JSON.stringify(req.body.payload));
435
444
 
436
445
  var projectId = req.body.payload.id_project;
437
446
  console.log("(TILEDESK) PROJECT ID: ", projectId);
@@ -444,9 +453,15 @@ router.post('/tiledesk', async (req, res) => {
444
453
  var text = req.body.payload.text;
445
454
  console.log("(TILEDESK) TEXT: ", text);
446
455
 
447
- var attributes = req.body.payload.attributes;
456
+ let attributes = req.body.payload.attributes;
457
+ console.log("(TILEDESK) ATTRIBUTES: ", JSON.stringify(attributes, null, 2))
448
458
  if (log) {
449
- console.log("(TILEDESK) ATTRIBUTES: ", attributes)
459
+ }
460
+
461
+ let commands;
462
+ if (attributes && attributes.commands) {
463
+ commands = attributes.commands;
464
+ console.log("commands: ", JSON.stringify(commands, null, 2));
450
465
  }
451
466
 
452
467
  var sender_id = req.body.payload.sender;
@@ -467,7 +482,12 @@ router.post('/tiledesk', async (req, res) => {
467
482
  return res.send(200);
468
483
  }
469
484
 
470
- console.log("/tiledesk ---> tiledeskChannelMessage: " + JSON.stringify(req.body.payload));
485
+ // Redirect for testing bots
486
+ //if (text.startsWith("#td")) {
487
+ // return res.redirect('/testitout');
488
+ //}
489
+
490
+ //console.log("/tiledesk ---> tiledeskChannelMessage: " + JSON.stringify(req.body.payload));
471
491
 
472
492
  let recipient_id = tiledeskChannelMessage.recipient;
473
493
  console.log("(Tiledesk) Recipient_id: ", recipient_id);
@@ -482,10 +502,134 @@ router.post('/tiledesk', async (req, res) => {
482
502
  let phone_number_id = recipient_id.substring(recipient_id.lastIndexOf("wab-") + 4, recipient_id.lastIndexOf("-"));
483
503
  console.log("(Tiledesk) phone_number_id: ", phone_number_id)
484
504
 
505
+ console.log("-----> (Tiledesk) ANSWER: ", tiledeskChannelMessage.answer)
506
+
507
+ const messageHandler = new MessageHandler({ tiledeskChannelMessage: tiledeskChannelMessage });
485
508
  const tlr = new TiledeskWhatsappTranslator();
486
509
 
510
+ if (commands) {
511
+ const that = this;
512
+ let i = 0;
513
+ async function execute(command) {
514
+ // message
515
+ console.log/("----> next command: ", command);
516
+ if (command.type === "message") {
517
+ let tiledeskCommandMessage = await messageHandler.generateMessageObject(command);
518
+ console.log("message generated!\ntiledeskCommandMessage: ", tiledeskCommandMessage)
519
+
520
+ let whatsappJsonMessage = await tlr.toWhatsapp(tiledeskCommandMessage, whatsapp_receiver);
521
+ console.log('\x1b[34m%s\x1b[0m', 'whatsappJsonMessage', whatsappJsonMessage)
522
+
523
+
524
+ if (whatsappJsonMessage) {
525
+ const twClient = new TiledeskWhatsapp({ token: settings.wab_token, GRAPH_URL: GRAPH_URL });
526
+ twClient.sendMessage(phone_number_id, whatsappJsonMessage).then((response) => {
527
+ //console.log("Send message response: ", response.status, response.statusText);
528
+ i += 1;
529
+ if (i < commands.length) {
530
+ execute(commands[i]);
531
+ } else {
532
+ console.log("End of commands")
533
+ }
534
+ }).catch((err) => {
535
+ console.error("ERROR Send message: ", err);
536
+ })
537
+ } else {
538
+ console.error("Whatsapp Json Message is undefined!")
539
+ }
540
+
541
+ }
542
+
543
+ //wait
544
+ if (command.type === "wait") {
545
+ setTimeout(() => {
546
+ console.log("wait for " + command.time + " s")
547
+ i += 1;
548
+ if (i < commands.length) {
549
+ execute(commands[i]);
550
+ } else {
551
+ console.log("End of commands")
552
+ }
553
+ }, command.time)
554
+ }
555
+ }
556
+ execute(commands[0]);
557
+ }
558
+
559
+ else if (tiledeskChannelMessage.text) {
560
+
561
+ console.log("tiledeskChannelMessage.text: ", tiledeskChannelMessage.text)
562
+
563
+ let whatsappJsonMessage = await tlr.toWhatsapp(tiledeskChannelMessage, whatsapp_receiver);
564
+ console.log('\x1b[34m%s\x1b[0m', 'whatsappJsonMessage', whatsappJsonMessage)
565
+ //console.log("whatsappJsonMessage: ", whatsappJsonMessage);
566
+
567
+ if (whatsappJsonMessage) {
568
+ const twClient = new TiledeskWhatsapp({ token: settings.wab_token, GRAPH_URL: GRAPH_URL });
569
+
570
+ twClient.sendMessage(phone_number_id, whatsappJsonMessage).then((response) => {
571
+ console.log("Send message response: ", response.status, response.statusText);
572
+ }).catch((err) => {
573
+ console.error("ERROR Send message: ", err);
574
+ })
575
+
576
+ /*
577
+ sendMessage(phone_number_id, whatsappJsonMessage, wab_token).then((response) => {
578
+ console.log("sendMessage() response: ", response);
579
+ }).catch((err) => {
580
+ console.log("ERROR sendMessage(): ", err);
581
+ })
582
+ */
583
+ } else {
584
+ console.error("Whatsapp Json Message is undefined!")
585
+ }
586
+
587
+ } else {
588
+ console.log("no command, no text --> skip")
589
+ }
590
+
591
+
592
+
593
+
594
+ /*
595
+ if (commands) {
596
+ commands.forEach( async (command) => {
597
+ console.log("\ncommand: ", command);
598
+ if (command.type === "message") {
599
+ let tiledeskCommandMessage = await messageHandler.generateMessageObject(command);
600
+ console.log("message generated!\ntiledeskCommandMessage: ", tiledeskCommandMessage)
601
+
602
+ let whatsappJsonMessage = await tlr.toWhatsapp(tiledeskCommandMessage, whatsapp_receiver);
603
+ console.log('\x1b[34m%s\x1b[0m', 'whatsappJsonMessage', whatsappJsonMessage)
604
+
605
+
606
+ if (whatsappJsonMessage) {
607
+ const twClient = new TiledeskWhatsapp({ token: settings.wab_token, GRAPH_URL: GRAPH_URL });
608
+ twClient.sendMessage(phone_number_id, whatsappJsonMessage).then((response) => {
609
+ console.log("Send message response: ", response.status, response.statusText);
610
+ }).catch((err) => {
611
+ console.error("ERROR Send message: ", err);
612
+ })
613
+ } else {
614
+ console.error("Whatsapp Json Message is undefined!")
615
+ }
616
+
617
+ }
618
+ if (command.type === "wait") {
619
+ setTimeout(() => {
620
+ console.log("wait for " + command.time + " s")
621
+ console.log("Next command")
622
+ }, command.time)
623
+ }
624
+ })
625
+ }
626
+ */
627
+ //new_tiledesk_message = addCommandmessage(commands[0]);
628
+
629
+ /*
487
630
  let whatsappJsonMessage = await tlr.toWhatsapp(tiledeskChannelMessage, whatsapp_receiver);
488
- console.log("whatsappJsonMessage: ", whatsappJsonMessage);
631
+ console.log('\x1b[34m%s\x1b[0m', 'whatsappJsonMessage', whatsappJsonMessage)
632
+ //console.log("whatsappJsonMessage: ", whatsappJsonMessage);
489
633
 
490
634
  if (whatsappJsonMessage) {
491
635
  const twClient = new TiledeskWhatsapp({ token: settings.wab_token, GRAPH_URL: GRAPH_URL });
@@ -503,9 +647,12 @@ router.post('/tiledesk', async (req, res) => {
503
647
  console.log("ERROR sendMessage(): ", err);
504
648
  })
505
649
  */
650
+
651
+ /*
506
652
  } else {
507
653
  console.error("Whatsapp Json Message is undefined!")
508
654
  }
655
+ */
509
656
  // richiamo toWhatsapp;
510
657
  // sendMessage
511
658
  //callSendAPI(project_id, phone_number_id, to, payload);
@@ -515,6 +662,7 @@ router.post('/tiledesk', async (req, res) => {
515
662
  // Endpoint for Whatsapp Business
516
663
  // Accepts POST requests at /webhook endpoint
517
664
  router.post("/webhook/:project_id", async (req, res) => {
665
+
518
666
  // Parse the request body from the POST
519
667
  let body = req.body;
520
668
  let projectId = req.params.project_id;
@@ -542,6 +690,9 @@ router.post("/webhook/:project_id", async (req, res) => {
542
690
  //let originalWhatsappMessage = req.body;
543
691
  let whatsappChannelMessage = req.body.entry[0].changes[0].value.messages[0];
544
692
 
693
+ if (whatsappChannelMessage.text && whatsappChannelMessage.text.body.startsWith("#td")) {
694
+ return res.redirect(307, '/testitout/' + projectId);
695
+ }
545
696
 
546
697
  let firstname = req.body.entry[0].changes[0].value.contacts[0].profile.name;
547
698
  console.log("(WAB) firstname: ", firstname)
@@ -581,7 +732,6 @@ router.post("/webhook/:project_id", async (req, res) => {
581
732
  else if (whatsappChannelMessage.type == 'interactive') {
582
733
  console.log("message type interactive")
583
734
  tiledeskJsonMessage = tlr.toTiledesk(whatsappChannelMessage, firstname);
584
-
585
735
  }
586
736
  else if ((whatsappChannelMessage.type == 'image') || (whatsappChannelMessage.type == 'video') || (whatsappChannelMessage.type == 'document')) {
587
737
  let media;
@@ -720,12 +870,108 @@ router.get("/webhook/:project_id", async (req, res) => {
720
870
 
721
871
  });
722
872
 
873
+ function getRandomName() {
874
+
875
+ let hexString = uuidv4();
876
+ console.log("hex: ", hexString);
877
+
878
+ // remove decoration
879
+ hexString = hexString.replace(/-/g, '');
880
+
881
+ let base64String = Buffer.from(hexString, 'hex').toString('base64')
882
+ console.log("base64: ", base64String);
883
+
884
+ return base64String;
885
+ }
886
+
887
+
888
+ router.post("/newtest", async (req, res) => {
889
+ //bottest:bot_id:code
890
+ console.log("/newtest body: ", JSON.stringify(req.body, null, 2));
891
+ let project_id = req.body.project_id;
892
+ let bot_id = req.body.bot_id;
893
+
894
+ let info = {
895
+ project_id: project_id,
896
+ bot_id: bot_id
897
+ }
898
+
899
+ //let short_uid = getRandomName();
900
+ let short_uid = uuidv4().substring(0, 8)
901
+ let TEST_KEY = "bottest:" + short_uid;
902
+
903
+ await redis_client.json.set(TEST_KEY, '.', info);
904
+ const value = await redis_client.json.get(TEST_KEY)
905
+ console.log("get --> value: ", value)
906
+ /*
907
+ const value = await redis_client.json.get(TEST_KEY, {
908
+ // JSON Path: .node = the element called 'node' at root level.
909
+ path: '.nodell',
910
+ });
911
+ */
912
+ res.status(200).send({short_uid: short_uid});
913
+ })
914
+
915
+ router.post("/testitout/:project_id", async (req, res) => {
916
+
917
+ //console.log("\n/(testitout): ", JSON.stringify(req.body, null, 2));
918
+ console.log("\n/(testitout)");
919
+ let projectId = req.params.project_id;
920
+ console.log("(testitout) projectId: ", projectId)
921
+
922
+ let whatsappChannelMessage = req.body.entry[0].changes[0].value.messages[0];
923
+ console.log("(testitout) whatsappChannelMessage: ", whatsappChannelMessage);
924
+
925
+ let whatsappContact = req.body.entry[0].changes[0].value.contacts[0];
926
+
927
+ let REDIS_KEY = "bottest:" + whatsappChannelMessage.text.body.substring(3);
928
+ console.log("(testitout) key: ", REDIS_KEY);
929
+
930
+ const info = await redis_client.json.get(REDIS_KEY);
931
+ console.log("(testitout) info: ", info);
932
+
933
+ let message_info = {
934
+ channel: "whatsapp",
935
+ whatsapp: {
936
+ phone_number_id: req.body.entry[0].changes[0].value.metadata.phone_number_id,
937
+ from: whatsappChannelMessage.from,
938
+ firstname: whatsappContact.profile.name,
939
+ lastname: " "
940
+ }
941
+ }
942
+ console.log("(testitout) message_info: ", message_info)
943
+
944
+ let CONTENT_KEY = "whatsapp-" + projectId;
945
+ let settings = await db.get(CONTENT_KEY);
946
+ if (log) {
947
+ console.log("[KVDB] settings: ", settings);
948
+ }
949
+
950
+ if (!settings) {
951
+ console.log("No settings found. Exit..");
952
+ res.sendStatus(200);
953
+ return;
954
+ }
955
+
956
+ const tlr = new TiledeskWhatsappTranslator();
957
+
958
+ whatsappChannelMessage.text.body = "/start";
959
+ let tiledeskJsonMessage = tlr.toTiledesk(whatsappChannelMessage, whatsappContact.profile.name);
960
+ console.log("(testitout) tiledeskJsonMessage: ", tiledeskJsonMessage)
961
+
962
+ const tdChannel = new TiledeskChannel({ settings: settings, API_URL: API_URL })
963
+ const response = await tdChannel.sendAndAddBot(tiledeskJsonMessage, message_info, info.bot_id)
964
+ console.log("testitout --> send response: ", response)
965
+
966
+ res.status(200).send("testitout")
967
+ })
968
+
723
969
 
724
970
  // *****************************
725
971
  // ********* FUNCTIONS *********
726
972
  // *****************************
727
973
 
728
- function startApp(settings, callback) {
974
+ async function startApp(settings, callback) {
729
975
  console.log("Starting Whatsapp App");
730
976
 
731
977
  if (!settings.MONGODB_URL) {
@@ -760,13 +1006,50 @@ function startApp(settings, callback) {
760
1006
  console.log("APPS_API_URL: ", APPS_API_URL);
761
1007
  }
762
1008
 
1009
+ if (!settings.REDIS_HOST) {
1010
+ throw new Error("!settings.REDIS_HOST is mandatory");
1011
+ } else {
1012
+ REDIS_HOST = settings.REDIS_HOST;
1013
+ console.log("REDIS_HOST: ", REDIS_HOST);
1014
+ }
1015
+
1016
+ if (!settings.REDIS_PORT) {
1017
+ throw new Error("!settings.REDIS_PORT is mandatory");
1018
+ } else {
1019
+ REDIS_PORT = settings.REDIS_PORT;
1020
+ console.log("REDIS_PORT: ", REDIS_PORT);
1021
+ }
1022
+
1023
+ if (!settings.REDIS_PASSWORD) {
1024
+ throw new Error("!settings.REDIS_PASSWORD is mandatory");
1025
+ } else {
1026
+ REDIS_PASSWORD = settings.REDIS_PASSWORD;
1027
+ console.log("REDIS_PASSWORD: *************");
1028
+ }
1029
+
763
1030
  if (settings.log) {
764
1031
  log = settings.log;
765
1032
  }
766
1033
 
1034
+ console.log("try to create client")
1035
+ redis_client = redis.createClient({
1036
+ socket: {
1037
+ host: REDIS_HOST,
1038
+ port: REDIS_PORT,
1039
+ },
1040
+ password: REDIS_PASSWORD
1041
+ });
1042
+ redis_client.on('connect', () => {
1043
+ console.log('Redis Connected!'); // Connected!
1044
+ });
1045
+ await redis_client.connect();
1046
+ redis_client.on('error', err => {
1047
+ console.log('Error ' + err);
1048
+ })
1049
+
767
1050
  db.connect(settings.MONGODB_URL, () => {
768
1051
  console.log("KVBaseMongo successfully connected.");
769
-
1052
+
770
1053
  if (callback) {
771
1054
  callback();
772
1055
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiledesk/tiledesk-whatsapp-connector",
3
- "version": "0.1.23",
3
+ "version": "0.1.25",
4
4
  "description": "Tiledesk Whatsapp connector",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -23,9 +23,10 @@
23
23
  "jsonwebtoken": "^8.5.1",
24
24
  "mongoose": "^6.5.0",
25
25
  "multer": "^1.4.5-lts.1",
26
+ "redis": "^4.5.1",
26
27
  "uuid": "^8.3.2"
27
28
  },
28
29
  "devDependencies": {
29
30
  "mocha": "^8.2.1"
30
31
  }
31
- }
32
+ }
@@ -54,10 +54,6 @@
54
54
  <div style="display: flex; flex-direction: row; justify-content: space-between; margin-left: 40px; width: 100%;">
55
55
  <div>
56
56
  <p style="font-size: 26px; font-weight: 500; margin-bottom: 0px;">WhatsApp Business</p>
57
- <p style="color: #676767; font-size: 16px; margin-bottom: 5px;">Connect your WhatsApp number with Tiledesk</p>
58
- <a style="font-size: 18px;" href="https://tiledesk.com/" target="_blank">Tiledesk</a>
59
-
60
- <p style="font-size: 15px; color: #676767; font-style: italic; margin-bottom: 0px; margin-top: 20px;">Free</p>
61
57
  </div>
62
58
 
63
59
  <div style="display: flex; flex-direction: column; justify-content: flex-end; align-items: flex-end;">
@@ -98,13 +94,6 @@
98
94
  </div>
99
95
 
100
96
  {{else}}
101
- <!-- Install button
102
- <form action="./install" method="post">
103
- <input type="hidden" name="project_id" value="{{ project_id }}" />
104
- <input type="hidden" name="app_id" value="{{ app_id }}" />
105
- <input type="hidden" name="token" value="{{ token }}" />
106
- <input type="submit" class="btn install-button" value="Install">
107
- </form>-->
108
97
  <button class="btn install-button" onclick="document.getElementById('install-modal').style.display='flex'">Install</button>
109
98
  <!-- Install modal -->
110
99
  <div id="install-modal" class="modal">
@@ -129,7 +118,6 @@
129
118
  </div>
130
119
  </div>
131
120
  {{/if}}
132
-
133
121
  </div>
134
122
  </div>
135
123
  </div>
@@ -137,26 +125,14 @@
137
125
  <hr style="margin-top: 20px; margin-bottom: 20px">
138
126
 
139
127
  <p style="font-size: 18px;"><b>Screenshot from the application</b></p>
140
- <!--<img src="https://media.discordapp.net/attachments/998542078587973734/1018841949534429184/2211.jpg?width=1055&height=686" style="width: 100%; height: 50%;"/>
141
- <img src="https://images-ext-2.discordapp.net/external/iKwvEo-ovnWVU0wvDgOwYZXdI9jfL-kKVsTZE2-ha5M/%3Fcrop%3D1/https/tiledesk.com/wp-content/uploads/2022/08/banner-adaptive-part2-1200x480.png" style="width: 100%; height: auto;"/>-->
142
128
 
143
129
  <div class="scrollmenu">
144
130
 
145
131
  <img src="https://user-images.githubusercontent.com/45603238/195042381-995ff805-359d-4d97-af67-f86f937c175a.jpg" class="screenshot" />
146
-
147
- <img src="https://user-images.githubusercontent.com/45603238/195042391-6560424b-6a20-48ef-a5b3-981f9cbda5db.jpg" class="screenshot" />
148
-
149
- <img src=" https://user-images.githubusercontent.com/45603238/195042354-e8ce2b8b-4a82-45b6-8ac1-c1d1bcf77e40.jpg" class="screenshot"/>
150
-
151
- <img src="https://user-images.githubusercontent.com/45603238/196982373-6b17cf76-6608-45bf-86da-551c14c46e0f.png" class="screenshot" />
152
-
153
132
 
154
133
  </div>
155
-
156
-
134
+
157
135
  <hr style="margin-top: 20px; margin-bottom: 20px">
158
-
159
-
160
136
  <div>
161
137
  <h7>Receive Whatsapp conversations in your Tiledesk dashboard. Seamlessly Chat with your targeted audience on Whatsapp right from the Tiledesk dashboard.</h7>
162
138
 
@@ -175,22 +151,12 @@
175
151
  </div>
176
152
  </ul>
177
153
 
178
- <!--
179
- <ul style="padding: 10px 20px;">
180
- <li><h7>Integrate your Whatsapp number with Tiledesk.</h7></li>
181
- <li><h7>Once a chat is initiated on your Whatsapp number, receive an alert on your Tiledesk account.</h7></li>
182
- <li><h7>Enable instant messaging and answer multiple conversations - everything from Tiledesk account.</h7></li>
183
- </ul>-->
184
-
185
154
  <div style="padding: 20px; background-color: aliceblue; border-radius: 8px;">
186
155
  <div style="display: flex; flex-direction: row; align-items: baseline;">
187
156
  <div>
188
157
  <img src="https://freeiconshop.com/wp-content/uploads/edd/arrow-flat.png" width="20px" height="auto" style="margin-right: 10px;">
189
158
  </div>
190
- <div>
191
- <a href="https://gethelp.tiledesk.com/articles/connect-tiledesk-with-whatsapp-business/" target="_blank">Connect Tiledesk with WhatsApp Business</a>
192
- <p style="color: grey; margin-bottom: 0px;">A small but very useful guide on how to connect your WhatsApp Business number with Tiledesk</p>
193
- </div>
159
+
194
160
  </div>
195
161
 
196
162
  <hr style="margin-top: 10px; margin-bottom: 10px;">
@@ -199,12 +165,7 @@
199
165
  <div>
200
166
  <img src="https://freeiconshop.com/wp-content/uploads/edd/arrow-flat.png" width="20px" height="auto" style="margin-right: 10px;">
201
167
  </div>
202
- <div>
203
- <a href="https://gethelp.tiledesk.com/articles/configure-a-whatsapp-business-account/" target="_blank">Configure a WhatsApp Business account</a>
204
- <p style="color: grey; margin-bottom: 0px;">Not sure how to set up a business account? Take a look here.</p>
205
- </div>
206
168
  </div>
207
-
208
169
  </div>
209
170
  </div>
210
171
 
@@ -215,74 +176,31 @@
215
176
 
216
177
  <div style="width: 100%; display: flex; flex-direction: row; justify-content: space-between; margin-bottom: 15px;">
217
178
  <div>
218
- <p style="margin-bottom: 0px">Bug Fixes</p>
179
+ <p style="margin-bottom: 0px">Added support for Test-it-out</p>
180
+ <p style="margin-bottom: 0px">Minor improvements</p>
219
181
  <!--<p>Bug fixes and performance improvements</p>-->
220
182
  </div>
221
- <p style="font-size: 12px; color: #676767; margin-bottom: 0px;">Version <b>0.1.23</b></p>
183
+ <p style="font-size: 12px; color: #676767; margin-bottom: 0px;">Version <b>0.1.24</b></p>
222
184
  </div>
223
185
 
224
186
  <div style="width: 100%; display: flex; flex-direction: row; justify-content: space-between; margin-bottom: 15px;">
225
187
  <div>
226
- <p style="margin-bottom: 0px;">New User Interface!</p>
227
- <p style="margin-bottom: 0px">Added support for tdImage</p>
228
188
  <p style="margin-bottom: 0px">Bug Fixes</p>
229
189
  <!--<p>Bug fixes and performance improvements</p>-->
230
190
  </div>
231
- <p style="font-size: 12px; color: #676767; margin-bottom: 0px;">Version <b>0.1.18</b></p>
191
+ <p style="font-size: 12px; color: #676767; margin-bottom: 0px;">Version <b>0.1.23</b></p>
232
192
  </div>
233
193
 
234
194
  <div style="width: 100%; display: flex; flex-direction: row; justify-content: space-between; margin-bottom: 15px;">
235
195
  <div>
236
- <p style="margin-bottom: 0px;">Graphics improvements</p>
196
+ <p style="margin-bottom: 0px;">New User Interface!</p>
197
+ <p style="margin-bottom: 0px">Added support for tdImage</p>
198
+ <p style="margin-bottom: 0px">Bug Fixes</p>
199
+ <!--<p>Bug fixes and performance improvements</p>-->
237
200
  </div>
238
- <p style="font-size: 12px; color: #676767; margin-bottom: 0px;">Version <b>0.1.16</b></p>
239
- </div>
240
-
241
- <!--
242
-
243
- <hr style="margin-top: 20px; margin-bottom: 20px">
244
-
245
-
246
- <p style="font-size: 18px;"><b>Other from Tiledesk</b> <a onclick="getParent()" target="_blank" style="font-size: 13px; margin-left: 15px;">View all</a></p>
247
-
248
- <div>
249
- <p>Visit our store and discovery all the available apps!</p>
201
+ <p style="font-size: 12px; color: #676767; margin-bottom: 0px;">Version <b>0.1.18</b></p>
250
202
  </div>
251
203
 
252
-
253
- <div style="display: flex;">
254
- <div class="app-summary-div">
255
- <img src="https://cdn3.iconfinder.com/data/icons/social-media-chamfered-corner/154/telegram-512.png" width="110" height="auto">
256
- <p class="app-summary-name">Telegram</p>
257
- </div>
258
-
259
- <div class="app-summary-div">
260
- <img src="https://cdn.jim-nielsen.com/ios/512/messenger-2020-11-17.png" width="110" height="auto">
261
- <p class="app-summary-name">Facebook Messenger</p>
262
- </div>
263
-
264
- <div class="app-summary-div">
265
- <img src="https://i.ibb.co/yWz3bZ5/2022-04-21-11-28-20.jpg" width="110" height="auto">
266
- <p class="app-summary-name">Help Center</p>
267
- </div>
268
-
269
- <div class="app-summary-div">
270
- <img src="https://i.pinimg.com/474x/f4/07/55/f407552380549b7ce1b508c5a6639b38.jpg" width="110" height="auto">
271
- <p class="app-summary-name">Github</p>
272
- </div>
273
- </div>
274
- -->
275
-
276
204
  <hr style="margin-top: 50px; margin-bottom: 20px">
277
-
278
- <!--
279
- <script>
280
- function getParent() {
281
- let parent_base = document.referrer;
282
- let app_store_url = parent_base + "dashboard/#/project/"+ {{project_id}} +"/app-store/"
283
- }
284
- </script>
285
- -->
286
-
287
205
 
288
206
  </body>
@@ -15,7 +15,7 @@ describe('Test Translator\n', function() {
15
15
  userFullname: 'John Doe'
16
16
  }
17
17
  }
18
- let whatsapp_receiver = tiledeskChannelMessage.recipient.substring(tiledeskChannelMessage.recipient.lastIndexOf("tel") + 1)
18
+ let whatsapp_receiver = tiledeskChannelMessage.recipient.substring(tiledeskChannelMessage.recipient.lastIndexOf("-") + 1)
19
19
 
20
20
  const tlr = new TiledeskWhatsappTranslator();
21
21
  assert(tlr != null);
@@ -45,7 +45,7 @@ describe('Test Translator\n', function() {
45
45
  userFullname: 'John Doe'
46
46
  }
47
47
  }
48
- let whatsapp_receiver = tiledeskChannelMessage.recipient.substring(tiledeskChannelMessage.recipient.lastIndexOf("tel") + 3)
48
+ let whatsapp_receiver = tiledeskChannelMessage.recipient.substring(tiledeskChannelMessage.recipient.lastIndexOf("-") + 1)
49
49
 
50
50
  const tlr = new TiledeskWhatsappTranslator();
51
51
  assert(tlr != null);
@@ -57,8 +57,8 @@ describe('Test Translator\n', function() {
57
57
  assert(whatsappJsonMessage.image);
58
58
  assert(whatsappJsonMessage.image.link === tiledeskChannelMessage.metadata.src);
59
59
  assert(whatsappJsonMessage.image.caption === tiledeskChannelMessage.text);
60
+ console.log("(test) whatsappJsonMessage: ", whatsappJsonMessage);
60
61
  if (log) {
61
- console.log("(test) whatsappJsonMessage: ", whatsappJsonMessage);
62
62
  }
63
63
  })
64
64
 
@@ -78,7 +78,7 @@ describe('Test Translator\n', function() {
78
78
  userFullname: 'John Doe'
79
79
  }
80
80
  }
81
- let whatsapp_receiver = tiledeskChannelMessage.recipient.substring(tiledeskChannelMessage.recipient.lastIndexOf("tel") + 3)
81
+ let whatsapp_receiver = tiledeskChannelMessage.recipient.substring(tiledeskChannelMessage.recipient.lastIndexOf("-") + 1)
82
82
 
83
83
  const tlr = new TiledeskWhatsappTranslator();
84
84
  assert(tlr != null);
@@ -111,7 +111,7 @@ describe('Test Translator\n', function() {
111
111
  userFullname: 'John Doe'
112
112
  }
113
113
  }
114
- let whatsapp_receiver = tiledeskChannelMessage.recipient.substring(tiledeskChannelMessage.recipient.lastIndexOf("tel") + 3)
114
+ let whatsapp_receiver = tiledeskChannelMessage.recipient.substring(tiledeskChannelMessage.recipient.lastIndexOf("-") + 1)
115
115
 
116
116
  const tlr = new TiledeskWhatsappTranslator();
117
117
  assert(tlr != null);
@@ -144,7 +144,7 @@ describe('Test Translator\n', function() {
144
144
  }
145
145
  }
146
146
  }
147
- let whatsapp_receiver = tiledeskChannelMessage.recipient.substring(tiledeskChannelMessage.recipient.lastIndexOf("tel") + 3)
147
+ let whatsapp_receiver = tiledeskChannelMessage.recipient.substring(tiledeskChannelMessage.recipient.lastIndexOf("-") + 1)
148
148
 
149
149
  const tlr = new TiledeskWhatsappTranslator();
150
150
  assert(tlr != null);
@@ -0,0 +1,74 @@
1
+ const axios = require("axios").default;
2
+ const jwt = require('jsonwebtoken');
3
+ const { v4: uuidv4 } = require('uuid');
4
+
5
+ class MessageHandler {
6
+
7
+ /**
8
+ * Constructor for TiledeskChannel
9
+ *
10
+ * @example
11
+ * const { TiledeskChannel } = require('tiledesk-channel');
12
+ * const tdChannel = new TiledeskChannel({tiledeskJsonMessage: replyFromWhatsapp, settings: appSettings, whatsappJsonMessage: originalWhatsappMessage, API_URL: tiledeskApiUrl });
13
+ *
14
+ * @param {Object} config JSON configuration.
15
+ * @param {string} config.tiledeskJsonMessage Mandatory. Message translated from Whatsapp to Tiledesk
16
+ * @param {string} config.whatsappJsonMessage Mandatory. Original whatsapp message.
17
+ * @param {string} config.settings Mandatory. Installation settings.
18
+ * @param {string} config.API_URL Mandatory. Tiledesk api url.
19
+ * @param {boolean} options.log Optional. If true HTTP requests are logged.
20
+ */
21
+
22
+ constructor(config) {
23
+
24
+ if (!config) {
25
+ throw new Error('config is mandatory');
26
+ }
27
+
28
+ if (!config.tiledeskChannelMessage) {
29
+ throw new Error('config.tiledeskChannelMessage is mandatory');
30
+ }
31
+
32
+ this.tiledeskChannelMessage = config.tiledeskChannelMessage;
33
+ this.log = true;
34
+
35
+ }
36
+
37
+ async generateMessageObject(command) {
38
+ console.log("[MessageHandler] command: ", command);
39
+ console.log("[MessageHandler] tiledeskChannelMessage: ", this.tiledeskChannelMessage);
40
+ let tiledeskCommandMessage = command.message;
41
+
42
+ tiledeskCommandMessage.recipient = this.tiledeskChannelMessage.recipient;
43
+
44
+ return tiledeskCommandMessage;
45
+ }
46
+
47
+ generateMessageObjectOriginal(command_message) {
48
+ let parentUid = this.tiledeskChannelMessage.uid
49
+ //command_message.uid = this.tiledeskChannelMessage.uid + "_" + index;
50
+ command_message.uid = this.tiledeskChannelMessage.uid;
51
+ if(command_message.text) command_message.text = command_message.text.trim()//remove black msg with only spaces
52
+ command_message.language = message.language;
53
+ command_message.recipient = message.recipient;
54
+ command_message.recipient_fullname = message.recipient_fullname;
55
+ command_message.sender = message.sender;
56
+ command_message.sender_fullname = message.sender_fullname;
57
+ command_message.channel_type = message.channel_type;
58
+ command_message.status = message.status;
59
+ command_message.isSender = message.isSender;
60
+ command_message.attributes? command_message.attributes.commands = true : command_message.attributes = {commands : true}
61
+ command_message.attributes.parentUid = parentUid //added to manage message STATUS UPDATES
62
+ command_message.attributes = {...message.attributes, ...command_message.attributes}
63
+ //this.addedNew(command_message)
64
+ //callback();
65
+
66
+ return command_message
67
+ }
68
+
69
+
70
+
71
+ }
72
+
73
+ module.exports = { MessageHandler }
74
+
@@ -32,7 +32,7 @@ class TiledeskChannel {
32
32
  throw new Error('config.API_URL is mandatory');
33
33
  }
34
34
 
35
- this.log = true;
35
+ this.log = false;
36
36
  if (config.log) {
37
37
  this.log = config.log;
38
38
  }
@@ -143,6 +143,80 @@ class TiledeskChannel {
143
143
  })
144
144
  }
145
145
 
146
+ async sendAndAddBot(tiledeskMessage, messageInfo, bot_id) {
147
+
148
+ let channel;
149
+ let new_request_id;
150
+ tiledeskMessage.participants = ["bot_" + bot_id]
151
+
152
+ if (messageInfo.channel == "whatsapp") {
153
+ channel = messageInfo.whatsapp;
154
+ new_request_id = "support-group-" + this.settings.project_id + "-" + uuidv4().substring(0, 8) + "-wab-" + channel.phone_number_id + "-" + channel.from;
155
+ } else {
156
+ console.log("[Tiledesk Channel] Channel not supported")
157
+ return null;
158
+ }
159
+
160
+ var payload = {
161
+ _id: 'wab-' + channel.from,
162
+ first_name: channel.firstname,
163
+ last_name: channel.lastname,
164
+ email: 'na@whatsapp.com',
165
+ sub: 'userexternal',
166
+ aud: 'https://tiledesk.com/subscriptions/' + this.settings.subscriptionId
167
+ }
168
+
169
+ var customToken = jwt.sign(payload, this.settings.secret);
170
+
171
+ return await axios({
172
+ url: this.API_URL + "/auth/signinWithCustomToken",
173
+ headers: {
174
+ 'Content-Type': 'application/json',
175
+ 'Authorization': 'JWT ' + customToken
176
+ },
177
+ data: {},
178
+ method: 'POST'
179
+ }).then((response) => {
180
+ let token = response.data.token;
181
+
182
+ return axios({
183
+ url: this.API_URL + `/${this.settings.project_id}/requests/${new_request_id}/messages`,
184
+ //url: this.API_URL + `/${this.settings.project_id}/requests/${new_request_id}/participants`,
185
+ headers: {
186
+ 'Content-Type': 'application/json',
187
+ 'Authorization': token
188
+ },
189
+ data: tiledeskMessage,
190
+ method: 'POST'
191
+ }).then((response) => {
192
+ console.log(response)
193
+ return response.data
194
+
195
+ /*
196
+ return axios({
197
+ url: this.API_URL + `/${this.settings.project_id}/requests/${new_request_id}/participants`,
198
+ headers: {
199
+ 'Content-Type': 'application/json',
200
+ 'Authorization': token
201
+ },
202
+ data: { member: bot_id },
203
+ method: 'POST'
204
+ }).then((response) => {
205
+ console.log("response: ", response.data)
206
+ return response.data
207
+ }).catch((err) => {
208
+ console.error("[Tiledesk Channel ERROR] add participant: ", err);
209
+ })
210
+ */
211
+ }).catch((err) => {
212
+ console.error("[Tiledesk Channel ERROR] send message (open conversation): " + err);
213
+ })
214
+ }).catch((err) => {
215
+ console.error("[Tiledesk Channel ERROR] sign in error: " + err);
216
+ })
217
+ }
218
+
219
+
146
220
  }
147
221
 
148
222
  module.exports = { TiledeskChannel }
@@ -29,7 +29,7 @@ const path = require('path');
29
29
  console.log("this.tiledeskChannelMessage: ", this.tiledeskChannelMessage);
30
30
  */
31
31
 
32
- this.log = true;
32
+ this.log = false;
33
33
 
34
34
 
35
35
  }