@tiledesk/tiledesk-whatsapp-connector 0.1.23 → 0.1.24

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,14 +17,21 @@ 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
36
  var API_URL = null;
28
37
  var GRAPH_URL = null;
@@ -30,10 +39,9 @@ var BASE_URL = null;
30
39
  var APPS_API_URL = null;
31
40
  var log = false;
32
41
 
33
- const db = new KVBaseMongo(kvbase_collection);
34
42
 
35
43
  router.get('/', async (req, res) => {
36
- res.send('Home works!')
44
+ res.send('Welcome to Tiledesk-WhatsApp Business connector!')
37
45
  })
38
46
 
39
47
  router.get('/detail', async (req, res) => {
@@ -175,14 +183,13 @@ router.get('/configure', async (req, res) => {
175
183
  projectId = req.query.project_id;
176
184
  token = req.query.token;
177
185
 
178
- let CONTENT_KEY = "whatsapp-" + projectId;
186
+ let proxy_url = BASE_URL + "/webhook/" + projectId;
179
187
 
188
+ let CONTENT_KEY = "whatsapp-" + projectId;
189
+
180
190
  let settings = await db.get(CONTENT_KEY);
181
191
  console.log("[KVDB] settings: ", settings);
182
192
 
183
- let proxy_url = BASE_URL + "/webhook/" + projectId;
184
- console.log("proxy_url: ", proxy_url);
185
-
186
193
  if (settings) {
187
194
 
188
195
  readHTMLFile('/configure.html', (err, html) => {
@@ -431,7 +438,7 @@ router.post('/tiledesk', async (req, res) => {
431
438
  //}
432
439
 
433
440
  var tiledeskChannelMessage = req.body.payload;
434
- //console.log("(TILEDESK) Payload: ", JSON.stringify(req.body.payload));
441
+ console.log("(TILEDESK) Payload: ", JSON.stringify(req.body.payload));
435
442
 
436
443
  var projectId = req.body.payload.id_project;
437
444
  console.log("(TILEDESK) PROJECT ID: ", projectId);
@@ -444,9 +451,15 @@ router.post('/tiledesk', async (req, res) => {
444
451
  var text = req.body.payload.text;
445
452
  console.log("(TILEDESK) TEXT: ", text);
446
453
 
447
- var attributes = req.body.payload.attributes;
454
+ let attributes = req.body.payload.attributes;
455
+ console.log("(TILEDESK) ATTRIBUTES: ", JSON.stringify(attributes, null, 2))
448
456
  if (log) {
449
- console.log("(TILEDESK) ATTRIBUTES: ", attributes)
457
+ }
458
+
459
+ let commands;
460
+ if (attributes && attributes.commands) {
461
+ commands = attributes.commands;
462
+ console.log("commands: ", JSON.stringify(commands, null, 2));
450
463
  }
451
464
 
452
465
  var sender_id = req.body.payload.sender;
@@ -467,7 +480,12 @@ router.post('/tiledesk', async (req, res) => {
467
480
  return res.send(200);
468
481
  }
469
482
 
470
- console.log("/tiledesk ---> tiledeskChannelMessage: " + JSON.stringify(req.body.payload));
483
+ // Redirect for testing bots
484
+ //if (text.startsWith("#td")) {
485
+ // return res.redirect('/testitout');
486
+ //}
487
+
488
+ //console.log("/tiledesk ---> tiledeskChannelMessage: " + JSON.stringify(req.body.payload));
471
489
 
472
490
  let recipient_id = tiledeskChannelMessage.recipient;
473
491
  console.log("(Tiledesk) Recipient_id: ", recipient_id);
@@ -482,10 +500,134 @@ router.post('/tiledesk', async (req, res) => {
482
500
  let phone_number_id = recipient_id.substring(recipient_id.lastIndexOf("wab-") + 4, recipient_id.lastIndexOf("-"));
483
501
  console.log("(Tiledesk) phone_number_id: ", phone_number_id)
484
502
 
503
+ console.log("-----> (Tiledesk) ANSWER: ", tiledeskChannelMessage.answer)
504
+
505
+ const messageHandler = new MessageHandler({ tiledeskChannelMessage: tiledeskChannelMessage });
485
506
  const tlr = new TiledeskWhatsappTranslator();
486
507
 
508
+ if (commands) {
509
+ const that = this;
510
+ let i = 0;
511
+ async function execute(command) {
512
+ // message
513
+ console.log/("----> next command: ", command);
514
+ if (command.type === "message") {
515
+ let tiledeskCommandMessage = await messageHandler.generateMessageObject(command);
516
+ console.log("message generated!\ntiledeskCommandMessage: ", tiledeskCommandMessage)
517
+
518
+ let whatsappJsonMessage = await tlr.toWhatsapp(tiledeskCommandMessage, whatsapp_receiver);
519
+ console.log('\x1b[34m%s\x1b[0m', 'whatsappJsonMessage', whatsappJsonMessage)
520
+
521
+
522
+ if (whatsappJsonMessage) {
523
+ const twClient = new TiledeskWhatsapp({ token: settings.wab_token, GRAPH_URL: GRAPH_URL });
524
+ twClient.sendMessage(phone_number_id, whatsappJsonMessage).then((response) => {
525
+ //console.log("Send message response: ", response.status, response.statusText);
526
+ i += 1;
527
+ if (i < commands.length) {
528
+ execute(commands[i]);
529
+ } else {
530
+ console.log("End of commands")
531
+ }
532
+ }).catch((err) => {
533
+ console.error("ERROR Send message: ", err);
534
+ })
535
+ } else {
536
+ console.error("Whatsapp Json Message is undefined!")
537
+ }
538
+
539
+ }
540
+
541
+ //wait
542
+ if (command.type === "wait") {
543
+ setTimeout(() => {
544
+ console.log("wait for " + command.time + " s")
545
+ i += 1;
546
+ if (i < commands.length) {
547
+ execute(commands[i]);
548
+ } else {
549
+ console.log("End of commands")
550
+ }
551
+ }, command.time)
552
+ }
553
+ }
554
+ execute(commands[0]);
555
+ }
556
+
557
+ else if (tiledeskChannelMessage.text) {
558
+
559
+ console.log("tiledeskChannelMessage.text: ", tiledeskChannelMessage.text)
560
+
561
+ let whatsappJsonMessage = await tlr.toWhatsapp(tiledeskChannelMessage, whatsapp_receiver);
562
+ console.log('\x1b[34m%s\x1b[0m', 'whatsappJsonMessage', whatsappJsonMessage)
563
+ //console.log("whatsappJsonMessage: ", whatsappJsonMessage);
564
+
565
+ if (whatsappJsonMessage) {
566
+ const twClient = new TiledeskWhatsapp({ token: settings.wab_token, GRAPH_URL: GRAPH_URL });
567
+
568
+ twClient.sendMessage(phone_number_id, whatsappJsonMessage).then((response) => {
569
+ console.log("Send message response: ", response.status, response.statusText);
570
+ }).catch((err) => {
571
+ console.error("ERROR Send message: ", err);
572
+ })
573
+
574
+ /*
575
+ sendMessage(phone_number_id, whatsappJsonMessage, wab_token).then((response) => {
576
+ console.log("sendMessage() response: ", response);
577
+ }).catch((err) => {
578
+ console.log("ERROR sendMessage(): ", err);
579
+ })
580
+ */
581
+ } else {
582
+ console.error("Whatsapp Json Message is undefined!")
583
+ }
584
+
585
+ } else {
586
+ console.log("no command, no text --> skip")
587
+ }
588
+
589
+
590
+
591
+
592
+ /*
593
+ if (commands) {
594
+ commands.forEach( async (command) => {
595
+ console.log("\ncommand: ", command);
596
+ if (command.type === "message") {
597
+ let tiledeskCommandMessage = await messageHandler.generateMessageObject(command);
598
+ console.log("message generated!\ntiledeskCommandMessage: ", tiledeskCommandMessage)
599
+
600
+ let whatsappJsonMessage = await tlr.toWhatsapp(tiledeskCommandMessage, whatsapp_receiver);
601
+ console.log('\x1b[34m%s\x1b[0m', 'whatsappJsonMessage', whatsappJsonMessage)
602
+
603
+
604
+ if (whatsappJsonMessage) {
605
+ const twClient = new TiledeskWhatsapp({ token: settings.wab_token, GRAPH_URL: GRAPH_URL });
606
+ twClient.sendMessage(phone_number_id, whatsappJsonMessage).then((response) => {
607
+ console.log("Send message response: ", response.status, response.statusText);
608
+ }).catch((err) => {
609
+ console.error("ERROR Send message: ", err);
610
+ })
611
+ } else {
612
+ console.error("Whatsapp Json Message is undefined!")
613
+ }
614
+
615
+ }
616
+ if (command.type === "wait") {
617
+ setTimeout(() => {
618
+ console.log("wait for " + command.time + " s")
619
+ console.log("Next command")
620
+ }, command.time)
621
+ }
622
+ })
623
+ }
624
+ */
625
+ //new_tiledesk_message = addCommandmessage(commands[0]);
626
+
627
+ /*
487
628
  let whatsappJsonMessage = await tlr.toWhatsapp(tiledeskChannelMessage, whatsapp_receiver);
488
- console.log("whatsappJsonMessage: ", whatsappJsonMessage);
629
+ console.log('\x1b[34m%s\x1b[0m', 'whatsappJsonMessage', whatsappJsonMessage)
630
+ //console.log("whatsappJsonMessage: ", whatsappJsonMessage);
489
631
 
490
632
  if (whatsappJsonMessage) {
491
633
  const twClient = new TiledeskWhatsapp({ token: settings.wab_token, GRAPH_URL: GRAPH_URL });
@@ -503,9 +645,12 @@ router.post('/tiledesk', async (req, res) => {
503
645
  console.log("ERROR sendMessage(): ", err);
504
646
  })
505
647
  */
648
+
649
+ /*
506
650
  } else {
507
651
  console.error("Whatsapp Json Message is undefined!")
508
652
  }
653
+ */
509
654
  // richiamo toWhatsapp;
510
655
  // sendMessage
511
656
  //callSendAPI(project_id, phone_number_id, to, payload);
@@ -515,6 +660,7 @@ router.post('/tiledesk', async (req, res) => {
515
660
  // Endpoint for Whatsapp Business
516
661
  // Accepts POST requests at /webhook endpoint
517
662
  router.post("/webhook/:project_id", async (req, res) => {
663
+
518
664
  // Parse the request body from the POST
519
665
  let body = req.body;
520
666
  let projectId = req.params.project_id;
@@ -542,6 +688,25 @@ router.post("/webhook/:project_id", async (req, res) => {
542
688
  //let originalWhatsappMessage = req.body;
543
689
  let whatsappChannelMessage = req.body.entry[0].changes[0].value.messages[0];
544
690
 
691
+ if (whatsappChannelMessage.text && whatsappChannelMessage.text.body.startsWith("#td")) {
692
+ return res.redirect(307, '/testitout/' + projectId);
693
+ }
694
+
695
+ // check redis
696
+ /*
697
+ let foo = await redis_client.get('foo');
698
+ console.log(foo);
699
+ */
700
+
701
+ /*
702
+ await redis_client.get('foo', (err, reply) => {
703
+ if (err) {
704
+ console.log("redis get error: ", err)
705
+ }
706
+ console.log("redis get reply: ", reply)
707
+ })
708
+ */
709
+
545
710
 
546
711
  let firstname = req.body.entry[0].changes[0].value.contacts[0].profile.name;
547
712
  console.log("(WAB) firstname: ", firstname)
@@ -581,7 +746,6 @@ router.post("/webhook/:project_id", async (req, res) => {
581
746
  else if (whatsappChannelMessage.type == 'interactive') {
582
747
  console.log("message type interactive")
583
748
  tiledeskJsonMessage = tlr.toTiledesk(whatsappChannelMessage, firstname);
584
-
585
749
  }
586
750
  else if ((whatsappChannelMessage.type == 'image') || (whatsappChannelMessage.type == 'video') || (whatsappChannelMessage.type == 'document')) {
587
751
  let media;
@@ -720,12 +884,108 @@ router.get("/webhook/:project_id", async (req, res) => {
720
884
 
721
885
  });
722
886
 
887
+ function getRandomName() {
888
+
889
+ let hexString = uuidv4();
890
+ console.log("hex: ", hexString);
891
+
892
+ // remove decoration
893
+ hexString = hexString.replace(/-/g, '');
894
+
895
+ let base64String = Buffer.from(hexString, 'hex').toString('base64')
896
+ console.log("base64: ", base64String);
897
+
898
+ return base64String;
899
+ }
900
+
901
+
902
+ router.post("/newtest", async (req, res) => {
903
+ //bottest:bot_id:code
904
+ console.log("/newtest body: ", JSON.stringify(req.body, null, 2));
905
+ let project_id = req.body.project_id;
906
+ let bot_id = req.body.bot_id;
907
+
908
+ let info = {
909
+ project_id: project_id,
910
+ bot_id: bot_id
911
+ }
912
+
913
+ //let short_uid = getRandomName();
914
+ let short_uid = uuidv4().substring(0, 8)
915
+ let TEST_KEY = "bottest:" + short_uid;
916
+
917
+ await redis_client.json.set(TEST_KEY, '.', info);
918
+ const value = await redis_client.json.get(TEST_KEY)
919
+ console.log("get --> value: ", value)
920
+ /*
921
+ const value = await redis_client.json.get(TEST_KEY, {
922
+ // JSON Path: .node = the element called 'node' at root level.
923
+ path: '.nodell',
924
+ });
925
+ */
926
+ res.status(200).send({short_uid: short_uid});
927
+ })
928
+
929
+ router.post("/testitout/:project_id", async (req, res) => {
930
+
931
+ //console.log("\n/(testitout): ", JSON.stringify(req.body, null, 2));
932
+ console.log("\n/(testitout)");
933
+ let projectId = req.params.project_id;
934
+ console.log("(testitout) projectId: ", projectId)
935
+
936
+ let whatsappChannelMessage = req.body.entry[0].changes[0].value.messages[0];
937
+ console.log("(testitout) whatsappChannelMessage: ", whatsappChannelMessage);
938
+
939
+ let whatsappContact = req.body.entry[0].changes[0].value.contacts[0];
940
+
941
+ let REDIS_KEY = "bottest:" + whatsappChannelMessage.text.body.substring(3);
942
+ console.log("(testitout) key: ", REDIS_KEY);
943
+
944
+ const info = await redis_client.json.get(REDIS_KEY);
945
+ console.log("(testitout) info: ", info);
946
+
947
+ let message_info = {
948
+ channel: "whatsapp",
949
+ whatsapp: {
950
+ phone_number_id: req.body.entry[0].changes[0].value.metadata.phone_number_id,
951
+ from: whatsappChannelMessage.from,
952
+ firstname: whatsappContact.profile.name,
953
+ lastname: " "
954
+ }
955
+ }
956
+ console.log("(testitout) message_info: ", message_info)
957
+
958
+ let CONTENT_KEY = "whatsapp-" + projectId;
959
+ let settings = await db.get(CONTENT_KEY);
960
+ if (log) {
961
+ console.log("[KVDB] settings: ", settings);
962
+ }
963
+
964
+ if (!settings) {
965
+ console.log("No settings found. Exit..");
966
+ res.sendStatus(200);
967
+ return;
968
+ }
969
+
970
+ const tlr = new TiledeskWhatsappTranslator();
971
+
972
+ whatsappChannelMessage.text.body = "/start";
973
+ let tiledeskJsonMessage = tlr.toTiledesk(whatsappChannelMessage, whatsappContact.profile.name);
974
+ console.log("(testitout) tiledeskJsonMessage: ", tiledeskJsonMessage)
975
+
976
+ const tdChannel = new TiledeskChannel({ settings: settings, API_URL: API_URL })
977
+ const response = await tdChannel.sendAndAddBot(tiledeskJsonMessage, message_info, info.bot_id)
978
+ console.log("testitout --> send response: ", response)
979
+
980
+ res.status(200).send("testitout")
981
+ })
982
+
723
983
 
724
984
  // *****************************
725
985
  // ********* FUNCTIONS *********
726
986
  // *****************************
727
987
 
728
- function startApp(settings, callback) {
988
+ async function startApp(settings, callback) {
729
989
  console.log("Starting Whatsapp App");
730
990
 
731
991
  if (!settings.MONGODB_URL) {
@@ -764,9 +1024,37 @@ function startApp(settings, callback) {
764
1024
  log = settings.log;
765
1025
  }
766
1026
 
1027
+ console.log("try to create client")
1028
+ redis_client = redis.createClient({
1029
+ socket: {
1030
+ host: 'redis-19390.c6.eu-west-1-1.ec2.cloud.redislabs.com',
1031
+ port: 19390,
1032
+ },
1033
+ password: process.env.REDIS_PASSWORD
1034
+ });
1035
+ redis_client.on('connect', () => {
1036
+ console.log('Redis Connected!'); // Connected!
1037
+ });
1038
+ await redis_client.connect();
1039
+ redis_client.on('error', err => {
1040
+ console.log('Error ' + err);
1041
+ })
1042
+
767
1043
  db.connect(settings.MONGODB_URL, () => {
768
1044
  console.log("KVBaseMongo successfully connected.");
769
1045
 
1046
+ //const Redis = require('ioredis');
1047
+ //const fs = require('fs');
1048
+
1049
+ /*
1050
+ const redis = new Redis({
1051
+ host: 'redis-19390.c6.eu-west-1-1.ec2.cloud.redislabs.com',
1052
+ port: 19390,
1053
+ password: 'wAU4boYxtS5120tscd2BDjIL22vae7d9'
1054
+ });
1055
+ */
1056
+
1057
+
770
1058
  if (callback) {
771
1059
  callback();
772
1060
  }
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.24",
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">
@@ -137,26 +126,14 @@
137
126
  <hr style="margin-top: 20px; margin-bottom: 20px">
138
127
 
139
128
  <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
129
 
143
130
  <div class="scrollmenu">
144
131
 
145
132
  <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
133
 
154
134
  </div>
155
-
156
-
135
+
157
136
  <hr style="margin-top: 20px; margin-bottom: 20px">
158
-
159
-
160
137
  <div>
161
138
  <h7>Receive Whatsapp conversations in your Tiledesk dashboard. Seamlessly Chat with your targeted audience on Whatsapp right from the Tiledesk dashboard.</h7>
162
139
 
@@ -175,22 +152,12 @@
175
152
  </div>
176
153
  </ul>
177
154
 
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
155
  <div style="padding: 20px; background-color: aliceblue; border-radius: 8px;">
186
156
  <div style="display: flex; flex-direction: row; align-items: baseline;">
187
157
  <div>
188
158
  <img src="https://freeiconshop.com/wp-content/uploads/edd/arrow-flat.png" width="20px" height="auto" style="margin-right: 10px;">
189
159
  </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>
160
+
194
161
  </div>
195
162
 
196
163
  <hr style="margin-top: 10px; margin-bottom: 10px;">
@@ -199,12 +166,7 @@
199
166
  <div>
200
167
  <img src="https://freeiconshop.com/wp-content/uploads/edd/arrow-flat.png" width="20px" height="auto" style="margin-right: 10px;">
201
168
  </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
169
  </div>
207
-
208
170
  </div>
209
171
  </div>
210
172
 
@@ -215,74 +177,31 @@
215
177
 
216
178
  <div style="width: 100%; display: flex; flex-direction: row; justify-content: space-between; margin-bottom: 15px;">
217
179
  <div>
218
- <p style="margin-bottom: 0px">Bug Fixes</p>
180
+ <p style="margin-bottom: 0px">Added support for Test-it-out</p>
181
+ <p style="margin-bottom: 0px">Minor improvements</p>
219
182
  <!--<p>Bug fixes and performance improvements</p>-->
220
183
  </div>
221
- <p style="font-size: 12px; color: #676767; margin-bottom: 0px;">Version <b>0.1.23</b></p>
184
+ <p style="font-size: 12px; color: #676767; margin-bottom: 0px;">Version <b>0.1.24</b></p>
222
185
  </div>
223
186
 
224
187
  <div style="width: 100%; display: flex; flex-direction: row; justify-content: space-between; margin-bottom: 15px;">
225
188
  <div>
226
- <p style="margin-bottom: 0px;">New User Interface!</p>
227
- <p style="margin-bottom: 0px">Added support for tdImage</p>
228
189
  <p style="margin-bottom: 0px">Bug Fixes</p>
229
190
  <!--<p>Bug fixes and performance improvements</p>-->
230
191
  </div>
231
- <p style="font-size: 12px; color: #676767; margin-bottom: 0px;">Version <b>0.1.18</b></p>
192
+ <p style="font-size: 12px; color: #676767; margin-bottom: 0px;">Version <b>0.1.23</b></p>
232
193
  </div>
233
194
 
234
195
  <div style="width: 100%; display: flex; flex-direction: row; justify-content: space-between; margin-bottom: 15px;">
235
196
  <div>
236
- <p style="margin-bottom: 0px;">Graphics improvements</p>
197
+ <p style="margin-bottom: 0px;">New User Interface!</p>
198
+ <p style="margin-bottom: 0px">Added support for tdImage</p>
199
+ <p style="margin-bottom: 0px">Bug Fixes</p>
200
+ <!--<p>Bug fixes and performance improvements</p>-->
237
201
  </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>
202
+ <p style="font-size: 12px; color: #676767; margin-bottom: 0px;">Version <b>0.1.18</b></p>
250
203
  </div>
251
204
 
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
205
  <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
206
 
288
207
  </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
  }