chatbot-fca 0.0.2

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.

Potentially problematic release.


This version of chatbot-fca might be problematic. Click here for more details.

Files changed (97) hide show
  1. package/.cache/nix/binary-cache-v6.sqlite +0 -0
  2. package/.cache/nix/binary-cache-v6.sqlite-journal +0 -0
  3. package/.cache/replit/env/latest +125 -0
  4. package/.cache/replit/env/latest.json +1 -0
  5. package/.cache/replit/modules/nix.res +1 -0
  6. package/.cache/replit/modules/nodejs-20.res +1 -0
  7. package/.cache/replit/modules/replit.res +1 -0
  8. package/.cache/replit/modules.stamp +0 -0
  9. package/.cache/replit/nix/env.json +1 -0
  10. package/.replit +8 -0
  11. package/LICENSE +21 -0
  12. package/index.js +460 -0
  13. package/package.json +46 -0
  14. package/replit.nix +3 -0
  15. package/src/Screenshot.js +83 -0
  16. package/src/addExternalModule.js +25 -0
  17. package/src/addUserToGroup.js +115 -0
  18. package/src/changeAdminStatus.js +103 -0
  19. package/src/changeArchivedStatus.js +55 -0
  20. package/src/changeAvatar.js +136 -0
  21. package/src/changeAvatarV2.js +86 -0
  22. package/src/changeAvt.js +85 -0
  23. package/src/changeBio.js +76 -0
  24. package/src/changeBlockedStatus.js +49 -0
  25. package/src/changeBlockedStatusMqtt.js +80 -0
  26. package/src/changeCover.js +72 -0
  27. package/src/changeGroupImage.js +135 -0
  28. package/src/changeName.js +79 -0
  29. package/src/changeNickname.js +59 -0
  30. package/src/changeThreadColor.js +65 -0
  31. package/src/changeThreadEmoji.js +55 -0
  32. package/src/changeUsername.js +59 -0
  33. package/src/createCommentPost.js +230 -0
  34. package/src/createNewGroup.js +88 -0
  35. package/src/createPoll.js +71 -0
  36. package/src/createPost.js +276 -0
  37. package/src/deleteMessage.js +56 -0
  38. package/src/deleteThread.js +56 -0
  39. package/src/editMessage.js +68 -0
  40. package/src/editMessageOld.js +67 -0
  41. package/src/follow.js +74 -0
  42. package/src/forwardAttachment.js +60 -0
  43. package/src/getAccess.js +112 -0
  44. package/src/getAvatarUser.js +78 -0
  45. package/src/getCurrentUserID.js +7 -0
  46. package/src/getEmojiUrl.js +29 -0
  47. package/src/getFriendsList.js +83 -0
  48. package/src/getMessage.js +835 -0
  49. package/src/getRegion.js +7 -0
  50. package/src/getThreadHistory.js +680 -0
  51. package/src/getThreadHistoryDeprecated.js +71 -0
  52. package/src/getThreadInfo.js +232 -0
  53. package/src/getThreadInfoDeprecated.js +56 -0
  54. package/src/getThreadList.js +213 -0
  55. package/src/getThreadListDeprecated.js +46 -0
  56. package/src/getThreadPictures.js +59 -0
  57. package/src/getUID.js +119 -0
  58. package/src/getUserID.js +61 -0
  59. package/src/getUserInfo.js +66 -0
  60. package/src/handleFriendRequest.js +46 -0
  61. package/src/handleMessageRequest.js +47 -0
  62. package/src/httpGet.js +49 -0
  63. package/src/httpPost.js +48 -0
  64. package/src/listenMqtt.js +827 -0
  65. package/src/listenMqtt.txt +827 -0
  66. package/src/logout.js +75 -0
  67. package/src/markAsDelivered.js +47 -0
  68. package/src/markAsRead.js +70 -0
  69. package/src/markAsReadAll.js +40 -0
  70. package/src/markAsSeen.js +48 -0
  71. package/src/muteThread.js +45 -0
  72. package/src/postFormData.txt +46 -0
  73. package/src/refreshFb_dtsg.js +89 -0
  74. package/src/removeUserFromGroup.js +79 -0
  75. package/src/resolvePhotoUrl.js +45 -0
  76. package/src/searchForThread.js +53 -0
  77. package/src/searchStickers.js +53 -0
  78. package/src/sendMessage.js +329 -0
  79. package/src/sendMessageMqtt.js +322 -0
  80. package/src/sendTypingIndicator.js +101 -0
  81. package/src/sendTypingIndicatorV2.js +28 -0
  82. package/src/setMessageReaction.js +122 -0
  83. package/src/setMessageReactionMqtt.js +62 -0
  84. package/src/setPostReaction.js +112 -0
  85. package/src/setStoryReaction.js +64 -0
  86. package/src/setTitle.js +90 -0
  87. package/src/shareContact.js +110 -0
  88. package/src/shareLink.js +59 -0
  89. package/src/stopListenMqtt.js +23 -0
  90. package/src/threadColors.js +131 -0
  91. package/src/unfriend.js +52 -0
  92. package/src/unsendMessage.js +45 -0
  93. package/src/uploadAttachment.js +94 -0
  94. package/test/example-config.json +18 -0
  95. package/test/test-page.js +140 -0
  96. package/test/test.js +385 -0
  97. package/utils.js +2876 -0
@@ -0,0 +1,329 @@
1
+ "use strict";
2
+
3
+ var utils = require("../utils");
4
+ var log = require("npmlog");
5
+ var bluebird = require("bluebird");
6
+
7
+ var allowedProperties = {
8
+ attachment: true,
9
+ url: true,
10
+ sticker: true,
11
+ emoji: true,
12
+ emojiSize: true,
13
+ body: true,
14
+ mentions: true,
15
+ location: true,
16
+ };
17
+
18
+ module.exports = function (defaultFuncs, api, ctx) {
19
+ function uploadAttachment(attachments, callback) {
20
+ var uploads = [];
21
+
22
+ // create an array of promises
23
+ for (var i = 0; i < attachments.length; i++) {
24
+ if (!utils.isReadableStream(attachments[i])) throw { error: "Attachment should be a readable stream and not " + utils.getType(attachments[i]) + "." };
25
+ var form = {
26
+ upload_1024: attachments[i],
27
+ voice_clip: "true"
28
+ };
29
+
30
+ uploads.push(
31
+ defaultFuncs
32
+ .postFormData("https://upload.facebook.com/ajax/mercury/upload.php", ctx.jar, form, {}, {})
33
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
34
+ .then(function (resData) {
35
+ if (resData.error) throw resData;
36
+ // We have to return the data unformatted unless we want to change it
37
+ // back in sendMessage.
38
+ return resData.payload.metadata[0];
39
+ })
40
+ );
41
+ }
42
+
43
+ // resolve all promises
44
+ bluebird
45
+ .all(uploads)
46
+ .then(resData => callback(null, resData))
47
+ .catch(function (err) {
48
+ log.error("uploadAttachment", err);
49
+ return callback(err);
50
+ });
51
+ }
52
+
53
+ function getUrl(url, callback) {
54
+ var form = {
55
+ image_height: 960,
56
+ image_width: 960,
57
+ uri: url
58
+ };
59
+
60
+ defaultFuncs
61
+ .post("https://www.facebook.com/message_share_attachment/fromURI/", ctx.jar, form)
62
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
63
+ .then(function (resData) {
64
+ if (resData.error) return callback(resData);
65
+ if (!resData.payload) return callback({ error: "Invalid url" });
66
+ callback(null, resData.payload.share_data.share_params);
67
+ })
68
+ .catch(function (err) {
69
+ log.error("getUrl", err);
70
+ return callback(err);
71
+ });
72
+ }
73
+
74
+ function sendContent(form, threadID, isSingleUser, messageAndOTID, callback) {
75
+ // There are three cases here:
76
+ // 1. threadID is of type array, where we're starting a new group chat with users
77
+ // specified in the array.
78
+ // 2. User is sending a message to a specific user.
79
+ // 3. No additional form params and the message goes to an existing group chat.
80
+ if (utils.getType(threadID) === "Array") {
81
+ for (var i = 0; i < threadID.length; i++) form["specific_to_list[" + i + "]"] = "fbid:" + threadID[i];
82
+ form["specific_to_list[" + threadID.length + "]"] = "fbid:" + ctx.userID;
83
+ form["client_thread_id"] = "root:" + messageAndOTID;
84
+ log.info("sendMessage", "Sending message to multiple users: " + threadID);
85
+ }
86
+ else {
87
+ // This means that threadID is the id of a user, and the chat
88
+ // is a single person chat
89
+ if (isSingleUser) {
90
+ form["specific_to_list[0]"] = "fbid:" + threadID;
91
+ form["specific_to_list[1]"] = "fbid:" + ctx.userID;
92
+ form["other_user_fbid"] = threadID;
93
+ }
94
+ else form["thread_fbid"] = threadID;
95
+ }
96
+
97
+ if (ctx.globalOptions.pageID) {
98
+ form["author"] = "fbid:" + ctx.globalOptions.pageID;
99
+ form["specific_to_list[1]"] = "fbid:" + ctx.globalOptions.pageID;
100
+ form["creator_info[creatorID]"] = ctx.userID;
101
+ form["creator_info[creatorType]"] = "direct_admin";
102
+ form["creator_info[labelType]"] = "sent_message";
103
+ form["creator_info[pageID]"] = ctx.globalOptions.pageID;
104
+ form["request_user_id"] = ctx.globalOptions.pageID;
105
+ form["creator_info[profileURI]"] = "https://www.facebook.com/profile.php?id=" + ctx.userID;
106
+ }
107
+
108
+ defaultFuncs
109
+ .post("https://www.facebook.com/messaging/send/", ctx.jar, form)
110
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
111
+ .then(function (resData) {
112
+ if (!resData) return callback({ error: "Send message failed." });
113
+ if (resData.error) {
114
+ if (resData.error === 1545012) {
115
+ log.warn("sendMessage", "Got error 1545012. This might mean that you're not part of the conversation " + threadID);
116
+ }
117
+ else {
118
+ log.error("sendMessage", resData);
119
+ }
120
+ return callback(resData);
121
+ }
122
+
123
+ var messageInfo = resData.payload.actions.reduce(function (p, v) {
124
+ return (
125
+ {
126
+ threadID: v.thread_fbid,
127
+ messageID: v.message_id,
128
+ timestamp: v.timestamp
129
+ } || p
130
+ );
131
+ }, null);
132
+
133
+ return callback(null, messageInfo);
134
+ })
135
+ .catch(function (err) {
136
+ log.error("sendMessage", err);
137
+ if (utils.getType(err) == "Object" && err.error === "Not logged in.") ctx.loggedIn = false;
138
+ return callback(err);
139
+ });
140
+ }
141
+
142
+ function send(form, threadID, messageAndOTID, callback, isGroup) {
143
+ // We're doing a query to this to check if the given id is the id of
144
+ // a user or of a group chat. The form will be different depending
145
+ // on that.
146
+ if (utils.getType(threadID) === "Array") sendContent(form, threadID, false, messageAndOTID, callback);
147
+ else {
148
+ if (utils.getType(isGroup) != "Boolean") sendContent(form, threadID, threadID.length === 15, messageAndOTID, callback);
149
+ else sendContent(form, threadID, !isGroup, messageAndOTID, callback);
150
+ }
151
+ }
152
+
153
+ function handleUrl(msg, form, callback, cb) {
154
+ if (msg.url) {
155
+ form["shareable_attachment[share_type]"] = "100";
156
+ getUrl(msg.url, function (err, params) {
157
+ if (err) return callback(err);
158
+ form["shareable_attachment[share_params]"] = params;
159
+ cb();
160
+ });
161
+ }
162
+ else cb();
163
+ }
164
+
165
+ function handleLocation(msg, form, callback, cb) {
166
+ if (msg.location) {
167
+ if (msg.location.latitude == null || msg.location.longitude == null) return callback({ error: "location property needs both latitude and longitude" });
168
+ form["location_attachment[coordinates][latitude]"] = msg.location.latitude;
169
+ form["location_attachment[coordinates][longitude]"] = msg.location.longitude;
170
+ form["location_attachment[is_current_location]"] = !!msg.location.current;
171
+ }
172
+ cb();
173
+ }
174
+
175
+ function handleSticker(msg, form, callback, cb) {
176
+ if (msg.sticker) form["sticker_id"] = msg.sticker;
177
+ cb();
178
+ }
179
+
180
+ function handleEmoji(msg, form, callback, cb) {
181
+ if (msg.emojiSize != null && msg.emoji == null) return callback({ error: "emoji property is empty" });
182
+ if (msg.emoji) {
183
+ if (msg.emojiSize == null) msg.emojiSize = "medium";
184
+ if (msg.emojiSize != "small" && msg.emojiSize != "medium" && msg.emojiSize != "large") return callback({ error: "emojiSize property is invalid" });
185
+ if (form["body"] != null && form["body"] != "") return callback({ error: "body is not empty" });
186
+ form["body"] = msg.emoji;
187
+ form["tags[0]"] = "hot_emoji_size:" + msg.emojiSize;
188
+ }
189
+ cb();
190
+ }
191
+
192
+ function handleAttachment(msg, form, callback, cb) {
193
+ if (msg.attachment) {
194
+ form["image_ids"] = [];
195
+ form["gif_ids"] = [];
196
+ form["file_ids"] = [];
197
+ form["video_ids"] = [];
198
+ form["audio_ids"] = [];
199
+
200
+ if (utils.getType(msg.attachment) !== "Array") msg.attachment = [msg.attachment];
201
+ if (msg.attachment.every(e=>/_id$/.test(e[0]))) {
202
+ //console.log(msg.attachment)
203
+ msg.attachment.map(e=>form[`${e[0]}s`].push(e[1]));
204
+ return cb();
205
+ }
206
+ uploadAttachment(msg.attachment, function (err, files) {
207
+ if (err) return callback(err);
208
+ files.forEach(function (file) {
209
+ var key = Object.keys(file);
210
+ var type = key[0]; // image_id, file_id, etc
211
+ form["" + type + "s"].push(file[type]); // push the id
212
+ });
213
+ cb();
214
+ });
215
+ }
216
+ else cb();
217
+ }
218
+
219
+ function handleMention(msg, form, callback, cb) {
220
+ if (msg.mentions) {
221
+ for (let i = 0; i < msg.mentions.length; i++) {
222
+ const mention = msg.mentions[i];
223
+ const tag = mention.tag;
224
+ if (typeof tag !== "string") return callback({ error: "Mention tags must be strings." });
225
+ const offset = msg.body.indexOf(tag, mention.fromIndex || 0);
226
+ if (offset < 0) log.warn("handleMention", 'Mention for "' + tag + '" not found in message string.');
227
+ if (mention.id == null) log.warn("handleMention", "Mention id should be non-null.");
228
+
229
+ const id = mention.id || 0;
230
+ const emptyChar = '\u200E';
231
+ form["body"] = emptyChar + msg.body;
232
+ form["profile_xmd[" + i + "][offset]"] = offset + 1;
233
+ form["profile_xmd[" + i + "][length]"] = tag.length;
234
+ form["profile_xmd[" + i + "][id]"] = id;
235
+ form["profile_xmd[" + i + "][type]"] = "p";
236
+ }
237
+ }
238
+ cb();
239
+ }
240
+
241
+ return function sendMessage(msg, threadID, callback, replyToMessage, isGroup) {
242
+ typeof isGroup == "undefined" ? isGroup = null : "";
243
+ if (!callback && (utils.getType(threadID) === "Function" || utils.getType(threadID) === "AsyncFunction")) return threadID({ error: "Pass a threadID as a second argument." });
244
+ if (!replyToMessage && utils.getType(callback) === "String") {
245
+ replyToMessage = callback;
246
+ callback = function () { };
247
+ }
248
+
249
+ var resolveFunc = function () { };
250
+ var rejectFunc = function () { };
251
+ var returnPromise = new Promise(function (resolve, reject) {
252
+ resolveFunc = resolve;
253
+ rejectFunc = reject;
254
+ });
255
+
256
+ if (!callback) {
257
+ callback = function (err, data) {
258
+ if (err) return rejectFunc(err);
259
+ resolveFunc(data);
260
+ };
261
+ }
262
+
263
+ var msgType = utils.getType(msg);
264
+ var threadIDType = utils.getType(threadID);
265
+ var messageIDType = utils.getType(replyToMessage);
266
+
267
+ if (msgType !== "String" && msgType !== "Object") return callback({ error: "Message should be of type string or object and not " + msgType + "." });
268
+
269
+ // Changing this to accomodate an array of users
270
+ if (threadIDType !== "Array" && threadIDType !== "Number" && threadIDType !== "String") return callback({ error: "ThreadID should be of type number, string, or array and not " + threadIDType + "." });
271
+
272
+ if (replyToMessage && messageIDType !== 'String') return callback({ error: "MessageID should be of type string and not " + threadIDType + "." });
273
+
274
+ if (msgType === "String") msg = { body: msg };
275
+ var disallowedProperties = Object.keys(msg).filter(prop => !allowedProperties[prop]);
276
+ if (disallowedProperties.length > 0) return callback({ error: "Dissallowed props: `" + disallowedProperties.join(", ") + "`" });
277
+
278
+ var messageAndOTID = utils.generateOfflineThreadingID();
279
+ // console.log(messageAndOTID)
280
+ var form = {
281
+ client: "mercury",
282
+ action_type: "ma-type:user-generated-message",
283
+ author: "fbid:" + ctx.userID,
284
+ timestamp: Date.now(),
285
+ timestamp_absolute: "Today",
286
+ timestamp_relative: utils.generateTimestampRelative(),
287
+ timestamp_time_passed: "0",
288
+ is_unread: false,
289
+ is_cleared: false,
290
+ is_forward: false,
291
+ is_filtered_content: false,
292
+ is_filtered_content_bh: false,
293
+ is_filtered_content_account: false,
294
+ is_filtered_content_quasar: false,
295
+ is_filtered_content_invalid_app: false,
296
+ is_spoof_warning: false,
297
+ source: "source:chat:web",
298
+ "source_tags[0]": "source:chat",
299
+ body: msg.body ? msg.body.toString() : "",
300
+ html_body: false,
301
+ ui_push_phase: "V3",
302
+ status: "0",
303
+ offline_threading_id: messageAndOTID,
304
+ message_id: messageAndOTID,
305
+ threading_id: utils.generateThreadingID(ctx.clientID),
306
+ "ephemeral_ttl_mode:": "0",
307
+ manual_retry_cnt: "0",
308
+ has_attachment: !!(msg.attachment || msg.url || msg.sticker),
309
+ signatureID: utils.getSignatureID(),
310
+ replied_to_message_id: replyToMessage
311
+ };
312
+ // console.log(form)
313
+
314
+ handleLocation(msg, form, callback, () =>
315
+ handleSticker(msg, form, callback, () =>
316
+ handleAttachment(msg, form, callback, () =>
317
+ handleUrl(msg, form, callback, () =>
318
+ handleEmoji(msg, form, callback, () =>
319
+ handleMention(msg, form, callback, () =>
320
+ send(form, threadID, messageAndOTID, callback, isGroup)
321
+ )
322
+ )
323
+ )
324
+ )
325
+ )
326
+ );
327
+ return returnPromise;
328
+ };
329
+ };
@@ -0,0 +1,322 @@
1
+ var utils = require("../utils");
2
+ // @NethWs3Dev
3
+ var bluebird = require("bluebird");
4
+
5
+ module.exports = function (defaultFuncs, api, ctx) {
6
+ function uploadAttachment(attachments, callback) {
7
+ callback = callback || function () {};
8
+ var uploads = [];
9
+
10
+ // create an array of promises
11
+ for (var i = 0; i < attachments.length; i++) {
12
+ if (!utils.isReadableStream(attachments[i])) {
13
+ throw {
14
+ error:
15
+ "Attachment should be a readable stream and not " +
16
+ utils.getType(attachments[i]) +
17
+ ".",
18
+ };
19
+ }
20
+
21
+ var form = {
22
+ upload_1024: attachments[i],
23
+ voice_clip: "true",
24
+ };
25
+
26
+ uploads.push(
27
+ defaultFuncs
28
+ .postFormData(
29
+ "https://upload.facebook.com/ajax/mercury/upload.php",
30
+ ctx.jar,
31
+ form,
32
+ {},
33
+ )
34
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
35
+ .then(function (resData) {
36
+ if (resData.error) {
37
+ throw resData;
38
+ }
39
+
40
+ // We have to return the data unformatted unless we want to change it
41
+ // back in sendMessage.
42
+ return resData.payload.metadata[0];
43
+ }),
44
+ );
45
+ }
46
+
47
+ // resolve all promises
48
+ bluebird
49
+ .all(uploads)
50
+ .then(function (resData) {
51
+ callback(null, resData);
52
+ })
53
+ .catch(function (err) {
54
+ console.error("uploadAttachment", err);
55
+ return callback(err);
56
+ });
57
+ }
58
+
59
+ let variance = 0;
60
+ const epoch_id = () =>
61
+ Math.floor(Date.now() * (4194304 + (variance = (variance + 0.1) % 5)));
62
+ const emojiSizes = {
63
+ small: 1,
64
+ medium: 2,
65
+ large: 3,
66
+ };
67
+
68
+ function handleEmoji(msg, form, callback, cb) {
69
+ if (msg.emojiSize != null && msg.emoji == null) {
70
+ return callback({ error: "emoji property is empty" });
71
+ }
72
+ if (msg.emoji) {
73
+ if (!msg.emojiSize) {
74
+ msg.emojiSize = "small";
75
+ }
76
+ if (
77
+ msg.emojiSize !== "small" &&
78
+ msg.emojiSize !== "medium" &&
79
+ msg.emojiSize !== "large" &&
80
+ (isNaN(msg.emojiSize) || msg.emojiSize < 1 || msg.emojiSize > 3)
81
+ ) {
82
+ return callback({ error: "emojiSize property is invalid" });
83
+ }
84
+
85
+ form.payload.tasks[0].payload.send_type = 1;
86
+ form.payload.tasks[0].payload.text = msg.emoji;
87
+ form.payload.tasks[0].payload.hot_emoji_size = !isNaN(msg.emojiSize)
88
+ ? msg.emojiSize
89
+ : emojiSizes[msg.emojiSize];
90
+ }
91
+ cb();
92
+ }
93
+
94
+ function handleSticker(msg, form, callback, cb) {
95
+ if (msg.sticker) {
96
+ form.payload.tasks[0].payload.send_type = 2;
97
+ form.payload.tasks[0].payload.sticker_id = msg.sticker;
98
+ }
99
+ cb();
100
+ }
101
+
102
+ function handleAttachment(msg, form, callback, cb) {
103
+ if (msg.attachment) {
104
+ form.payload.tasks[0].payload.send_type = 3;
105
+ form.payload.tasks[0].payload.attachment_fbids = [];
106
+ if (form.payload.tasks[0].payload.text == "")
107
+ form.payload.tasks[0].payload.text = null;
108
+ if (utils.getType(msg.attachment) !== "Array") {
109
+ msg.attachment = [msg.attachment];
110
+ }
111
+
112
+ uploadAttachment(msg.attachment, function (err, files) {
113
+ if (err) {
114
+ return callback(err);
115
+ }
116
+
117
+ files.forEach(function (file) {
118
+ var key = Object.keys(file);
119
+ var type = key[0]; // image_id, file_id, etc
120
+ form.payload.tasks[0].payload.attachment_fbids.push(file[type]); // push the id
121
+ });
122
+ cb();
123
+ });
124
+ } else {
125
+ cb();
126
+ }
127
+ }
128
+
129
+ function handleMention(msg, form, callback, cb) {
130
+ if (msg.mentions) {
131
+ form.payload.tasks[0].payload.send_type = 1;
132
+
133
+ const arrayIds = [];
134
+ const arrayOffsets = [];
135
+ const arrayLengths = [];
136
+ const mention_types = [];
137
+
138
+ for (let i = 0; i < msg.mentions.length; i++) {
139
+ const mention = msg.mentions[i];
140
+
141
+ const tag = mention.tag;
142
+ if (typeof tag !== "string") {
143
+ return callback({ error: "Mention tags must be strings." });
144
+ }
145
+
146
+ const offset = msg.body.indexOf(tag, mention.fromIndex || 0);
147
+
148
+ if (offset < 0) {
149
+ console.warn(
150
+ "handleMention",
151
+ 'Mention for "' + tag + '" not found in message string.',
152
+ );
153
+ }
154
+
155
+ if (mention.id == null) {
156
+ console.warn("handleMention", "Mention id should be non-null.");
157
+ }
158
+
159
+ const id = mention.id || 0;
160
+ arrayIds.push(id);
161
+ arrayOffsets.push(offset);
162
+ arrayLengths.push(tag.length);
163
+ mention_types.push("p");
164
+ }
165
+
166
+ form.payload.tasks[0].payload.mention_data = {
167
+ mention_ids: arrayIds.join(","),
168
+ mention_offsets: arrayOffsets.join(","),
169
+ mention_lengths: arrayLengths.join(","),
170
+ mention_types: mention_types.join(","),
171
+ };
172
+ }
173
+ cb();
174
+ }
175
+
176
+ function handleLocation(msg, form, callback, cb) {
177
+ // this is not working yet
178
+ if (msg.location) {
179
+ if (msg.location.latitude == null || msg.location.longitude == null) {
180
+ return callback({
181
+ error: "location property needs both latitude and longitude",
182
+ });
183
+ }
184
+
185
+ form.payload.tasks[0].payload.send_type = 1;
186
+ form.payload.tasks[0].payload.location_data = {
187
+ coordinates: {
188
+ latitude: msg.location.latitude,
189
+ longitude: msg.location.longitude,
190
+ },
191
+ is_current_location: !!msg.location.current,
192
+ is_live_location: !!msg.location.live,
193
+ };
194
+ }
195
+
196
+ cb();
197
+ }
198
+
199
+ function send(form, threadID, callback, replyToMessage) {
200
+ if (replyToMessage) {
201
+ form.payload.tasks[0].payload.reply_metadata = {
202
+ reply_source_id: replyToMessage,
203
+ reply_source_type: 1,
204
+ reply_type: 0,
205
+ };
206
+ }
207
+ const mqttClient = ctx.mqttClient;
208
+ form.payload.tasks.forEach((task) => {
209
+ task.payload = JSON.stringify(task.payload);
210
+ });
211
+ form.payload = JSON.stringify(form.payload);
212
+ console.log(global.jsonStringifyColor(form, null, 2));
213
+
214
+ return mqttClient.publish(
215
+ "/ls_req",
216
+ JSON.stringify(form),
217
+ function (err, data) {
218
+ if (err) {
219
+ console.error("Error publishing message: ", err);
220
+ callback(err);
221
+ } else {
222
+ console.log("Message published successfully with data: ", data);
223
+ callback(null, data);
224
+ }
225
+ },
226
+ );
227
+ }
228
+
229
+ return function sendMessageMqtt(msg, threadID, callback, replyToMessage) {
230
+ if (
231
+ !callback &&
232
+ (utils.getType(threadID) === "Function" ||
233
+ utils.getType(threadID) === "AsyncFunction")
234
+ ) {
235
+ return threadID({ error: "Pass a threadID as a second argument." });
236
+ }
237
+ if (!replyToMessage && utils.getType(callback) === "String") {
238
+ replyToMessage = callback;
239
+ callback = function () {};
240
+ }
241
+
242
+ if (!callback) {
243
+ callback = function (err, friendList) {};
244
+ }
245
+
246
+ var msgType = utils.getType(msg);
247
+ var threadIDType = utils.getType(threadID);
248
+ var messageIDType = utils.getType(replyToMessage);
249
+
250
+ if (msgType !== "String" && msgType !== "Object") {
251
+ return callback({
252
+ error:
253
+ "Message should be of type string or object and not " + msgType + ".",
254
+ });
255
+ }
256
+
257
+ if (msgType === "String") {
258
+ msg = { body: msg };
259
+ }
260
+
261
+ const timestamp = Date.now();
262
+ // get full date time
263
+ const epoch = timestamp << 22;
264
+ //const otid = epoch + 0; // TODO replace with randomInt(0, 2**22)
265
+ const otid = epoch + Math.floor(Math.random() * 4194304);
266
+
267
+ const form = {
268
+ app_id: "2220391788200892",
269
+ payload: {
270
+ tasks: [
271
+ {
272
+ label: "46",
273
+ payload: {
274
+ thread_id: threadID.toString(),
275
+ otid: otid.toString(),
276
+ source: 0,
277
+ send_type: 1,
278
+ sync_group: 1,
279
+ text:
280
+ msg.body != null && msg.body != undefined
281
+ ? msg.body.toString()
282
+ : "",
283
+ initiating_source: 1,
284
+ skip_url_preview_gen: 0,
285
+ },
286
+ queue_name: threadID.toString(),
287
+ task_id: 0,
288
+ failure_count: null,
289
+ },
290
+ {
291
+ label: "21",
292
+ payload: {
293
+ thread_id: threadID.toString(),
294
+ last_read_watermark_ts: Date.now(),
295
+ sync_group: 1,
296
+ },
297
+ queue_name: threadID.toString(),
298
+ task_id: 1,
299
+ failure_count: null,
300
+ },
301
+ ],
302
+ epoch_id: epoch_id(),
303
+ version_id: "6120284488008082",
304
+ data_trace_id: null,
305
+ },
306
+ request_id: 1,
307
+ type: 3,
308
+ };
309
+
310
+ handleEmoji(msg, form, callback, function () {
311
+ handleLocation(msg, form, callback, function () {
312
+ handleMention(msg, form, callback, function () {
313
+ handleSticker(msg, form, callback, function () {
314
+ handleAttachment(msg, form, callback, function () {
315
+ send(form, threadID, callback, replyToMessage);
316
+ });
317
+ });
318
+ });
319
+ });
320
+ });
321
+ };
322
+ };