-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi-adapter.js
More file actions
387 lines (351 loc) · 21.4 KB
/
Copy pathapi-adapter.js
File metadata and controls
387 lines (351 loc) · 21.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
/**
* FCA to TCA API Adapter Layer
*
* Provides backwards compatibility for Facebook Chat API (FCA) command logic
* by translating incoming Telegram update context objects into classic FCA event
* structures and proxying outgoing API calls to the Telegram Bot API (TCA).
*
* @module system/api-adapter
* @author NTKhang & Modded for Telegram by frnAlt & Gtajisan
*/
const { InputFile } = require("grammy");
const fs = require("fs-extra");
const path = require("path");
const log = require("../logger/log.js");
/**
* Detects the media type (video, audio, photo, document) of an attachment input.
*
* @param {any} attachmentInput - Stream, path string, URL, or payload object
* @returns {string} "video" | "audio" | "photo" | "document"
*/
function detectMediaType(attachmentInput) {
if (!attachmentInput) return "document";
if (typeof attachmentInput === "object" && attachmentInput !== null) {
if (attachmentInput.type === "video" || attachmentInput.type === "audio" || attachmentInput.type === "photo") {
return attachmentInput.type;
}
}
const targetStr = (typeof attachmentInput === "string" ? attachmentInput : (attachmentInput.path || "")).toLowerCase();
if (/\.(mp4|mov|mkv|webm|avi|flv)$/i.test(targetStr)) {
return "video";
}
if (/\.(mp3|m4a|wav|ogg|aac|flac|opus)$/i.test(targetStr)) {
return "audio";
}
if (/\.(png|jpg|jpeg|gif|webp|bmp)$/i.test(targetStr)) {
return "photo";
}
return "photo"; // Default fallback for images/attachments
}
/**
* Creates a stream-based or URL-based InputFile for grammY media methods.
* Ensures streams are used for file paths to minimize memory consumption.
*
* @param {string|Buffer|Stream} mediaInput - Input file path, URL, buffer, or readable stream
* @returns {InputFile|null}
*/
function createInputFile(mediaInput) {
if (!mediaInput) return null;
if (typeof mediaInput === "string") {
if (mediaInput.startsWith("http://") || mediaInput.startsWith("https://")) {
return new InputFile({ url: mediaInput });
}
if (fs.existsSync(mediaInput)) {
return new InputFile(fs.createReadStream(mediaInput));
}
return new InputFile(mediaInput);
}
if (Buffer.isBuffer(mediaInput) || typeof mediaInput.pipe === "function") {
return new InputFile(mediaInput);
}
return new InputFile(mediaInput);
}
/**
* Constructs an FCA-compliant API wrapper object over the Telegram Bot API.
*
* @param {import("grammy").Context} ctx - grammY update context
* @returns {Object} FCA api wrapper
*/
function createFcaApiWrapper(ctx) {
const botApi = ctx.api;
return {
/**
* Send message wrapper supporting string messages, caption objects, and attachments.
* Supports Photo, Video, Audio/Voice, and Document formats like GoatBot V2.
*
* @param {string|Object} msg - Text string or payload object containing body/attachment
* @param {string|number} threadID - Target Telegram chat/channel ID
* @param {Function} [callback] - Optional completion callback (err, info)
* @param {number|string} [replyToMessageID] - Optional message ID to reply to
*/
sendMessage: async function (msg, threadID, callback, replyToMessageID) {
const targetThread = (threadID || ctx.chat?.id)?.toString();
const cb = typeof callback === "function" ? callback : (typeof replyToMessageID === "function" ? replyToMessageID : null);
const replyId = (typeof replyToMessageID === "number" || typeof replyToMessageID === "string") ? replyToMessageID : undefined;
try {
let sentMsgInfo = null;
if (typeof msg === "string" || typeof msg === "number") {
const res = await botApi.sendMessage(targetThread, msg.toString(), {
reply_to_message_id: replyId,
parse_mode: "HTML"
}).catch(() => botApi.sendMessage(targetThread, msg.toString(), { reply_to_message_id: replyId }));
sentMsgInfo = { messageID: res.message_id, threadID: targetThread, timestamp: res.date * 1000 };
} else if (typeof msg === "object" && msg !== null) {
const text = msg.body || msg.text || "";
const attachments = msg.attachment ? (Array.isArray(msg.attachment) ? msg.attachment : [msg.attachment]) : [];
if (attachments.length > 0) {
for (const att of attachments) {
const inputFile = createInputFile(att);
const mediaType = detectMediaType(att);
let res = null;
if (mediaType === "video") {
res = await botApi.sendVideo(targetThread, inputFile, {
caption: text,
reply_to_message_id: replyId,
parse_mode: "HTML"
}).catch(async () => {
return await botApi.sendDocument(targetThread, inputFile, {
caption: text,
reply_to_message_id: replyId
});
});
} else if (mediaType === "audio") {
res = await botApi.sendAudio(targetThread, inputFile, {
caption: text,
reply_to_message_id: replyId,
parse_mode: "HTML"
}).catch(async () => {
return await botApi.sendVoice(targetThread, inputFile, {
caption: text,
reply_to_message_id: replyId
});
}).catch(async () => {
return await botApi.sendDocument(targetThread, inputFile, {
caption: text,
reply_to_message_id: replyId
});
});
} else if (mediaType === "photo") {
res = await botApi.sendPhoto(targetThread, inputFile, {
caption: text,
reply_to_message_id: replyId,
parse_mode: "HTML"
}).catch(async () => {
return await botApi.sendDocument(targetThread, inputFile, {
caption: text,
reply_to_message_id: replyId
});
});
} else {
res = await botApi.sendDocument(targetThread, inputFile, {
caption: text,
reply_to_message_id: replyId,
parse_mode: "HTML"
}).catch(async () => {
return await botApi.sendPhoto(targetThread, inputFile, {
caption: text,
reply_to_message_id: replyId
});
});
}
sentMsgInfo = { messageID: res.message_id, threadID: targetThread, timestamp: res.date * 1000 };
}
} else if (text) {
const res = await botApi.sendMessage(targetThread, text, { reply_to_message_id: replyId, parse_mode: "HTML" })
.catch(() => botApi.sendMessage(targetThread, text, { reply_to_message_id: replyId }));
sentMsgInfo = { messageID: res.message_id, threadID: targetThread, timestamp: res.date * 1000 };
}
}
if (cb) cb(null, sentMsgInfo);
return sentMsgInfo;
} catch (err) {
log.error("FCA_API_SEND", `Failed sending message to ${targetThread}: ${err.message}`);
if (cb) cb(err, null);
throw err;
}
},
/**
* Deletes a message by ID.
*/
unsendMessage: async function (messageID, callback) {
try {
const targetID = messageID || ctx.message?.message_id;
await botApi.deleteMessage(ctx.chat.id, targetID);
if (typeof callback === "function") callback(null);
} catch (err) {
if (typeof callback === "function") callback(err);
}
},
/**
* Sets an emoji reaction on a target message.
*/
setMessageReaction: async function (emoji, messageID, threadID, force, callback) {
try {
const targetMsg = messageID || ctx.message?.message_id;
const targetThread = threadID || ctx.chat?.id;
if (botApi.setMessageReaction) {
await botApi.setMessageReaction(targetThread, targetMsg, [{ type: "emoji", emoji }]);
}
if (typeof callback === "function") callback(null);
} catch (err) {
if (typeof callback === "function") callback(err);
}
},
/**
* Fetches user details including name, username, and profile picture avatar.
*/
getUserInfo: async function (userID, callback) {
try {
const targetUser = Array.isArray(userID) ? userID[0] : userID;
const chat = await botApi.getChat(targetUser);
let avatarUrl = "";
try {
if (botApi.getUserProfilePhotos) {
const photos = await botApi.getUserProfilePhotos(targetUser, { limit: 1 });
if (photos && photos.total_count > 0 && photos.photos[0]?.length > 0) {
const fileId = photos.photos[0][photos.photos[0].length - 1].file_id;
const file = await botApi.getFile(fileId);
avatarUrl = `https://api.telegram.org/file/bot${botApi.token}/${file.file_path}`;
}
}
} catch (e) {}
const name = `${chat.first_name || ""} ${chat.last_name || ""}`.trim() || chat.username || "User";
const result = {
[targetUser]: {
name,
firstName: chat.first_name || "",
lastName: chat.last_name || "",
username: chat.username || "",
profileUrl: chat.username ? `https://t.me/${chat.username}` : "",
avatar: avatarUrl || `https://api.dicebear.com/7.x/bottts/png?seed=${targetUser}`,
thumbUrl: avatarUrl || `https://api.dicebear.com/7.x/bottts/png?seed=${targetUser}`
}
};
if (typeof callback === "function") callback(null, result);
return result;
} catch (err) {
if (typeof callback === "function") callback(err, null);
return {};
}
},
/**
* Fetches thread metadata for a chat ID.
*/
getThreadInfo: async function (threadID, callback) {
try {
const targetThread = threadID || ctx.chat?.id;
const chat = await botApi.getChat(targetThread);
const result = {
threadID: chat.id.toString(),
threadName: chat.title || chat.first_name || "Chat",
isGroup: chat.type === "group" || chat.type === "supergroup",
userInfo: []
};
if (typeof callback === "function") callback(null, result);
return result;
} catch (err) {
if (typeof callback === "function") callback(err, null);
return {};
}
},
/**
* Returns full Telegram download URL for a file_id.
*/
getFileUrl: async function (fileId) {
try {
if (!fileId) return null;
const file = await botApi.getFile(fileId);
if (file && file.file_path) {
return `https://api.telegram.org/file/bot${botApi.token}/${file.file_path}`;
}
return null;
} catch (err) {
return null;
}
},
/**
* Returns avatar URL for a user ID.
*/
getUserAvatarUrl: async function (userID) {
try {
const targetUser = Array.isArray(userID) ? userID[0] : userID;
if (botApi.getUserProfilePhotos) {
const photos = await botApi.getUserProfilePhotos(targetUser, { limit: 1 });
if (photos && photos.total_count > 0 && photos.photos[0]?.length > 0) {
const fileId = photos.photos[0][photos.photos[0].length - 1].file_id;
const file = await botApi.getFile(fileId);
if (file && file.file_path) {
return `https://api.telegram.org/file/bot${botApi.token}/${file.file_path}`;
}
}
}
} catch (e) {}
return `https://api.dicebear.com/7.x/bottts/png?seed=${encodeURIComponent(userID)}&size=512`;
},
/**
* Returns current bot user ID.
*/
getCurrentUserID: function () {
return (global.GoatBot.botID || ctx.me?.id)?.toString();
},
/**
* Bans and unbans a group member to kick them.
*/
kickParticipant: async function (userID, threadID, callback) {
try {
const targetThread = threadID || ctx.chat?.id;
await botApi.banChatMember(targetThread, userID);
await botApi.unbanChatMember(targetThread, userID);
if (typeof callback === "function") callback(null);
} catch (err) {
if (typeof callback === "function") callback(err);
}
}
};
}
/**
* Constructs an FCA event object from a Telegram update context.
*
* @param {import("grammy").Context} ctx - grammY context
* @returns {Object} FCA event object
*/
function createFcaEventObject(ctx) {
const msg = ctx.message || ctx.editedMessage || {};
const from = ctx.from || msg.from || {};
const chat = ctx.chat || msg.chat || {};
const event = {
type: msg.reply_to_message ? "message_reply" : "message",
threadID: chat.id?.toString() || "",
senderID: from.id?.toString() || "",
body: msg.text || msg.caption || "",
messageID: msg.message_id,
isGroup: chat.type === "group" || chat.type === "supergroup",
attachments: [],
telegramCtx: ctx
};
if (msg.photo) {
const largestPhoto = msg.photo[msg.photo.length - 1];
event.attachments.push({ type: "photo", url: largestPhoto.file_id, file_id: largestPhoto.file_id });
} else if (msg.document) {
event.attachments.push({ type: "file", url: msg.document.file_id, filename: msg.document.file_name });
}
if (msg.reply_to_message) {
const replyMsg = msg.reply_to_message;
const replyPhoto = replyMsg.photo ? replyMsg.photo[replyMsg.photo.length - 1] : null;
const replyDoc = replyMsg.document || null;
const replyAttachments = [];
if (replyPhoto) {
replyAttachments.push({ type: "photo", url: replyPhoto.file_id, file_id: replyPhoto.file_id });
} else if (replyDoc) {
replyAttachments.push({ type: "file", url: replyDoc.file_id, file_id: replyDoc.file_id, filename: replyDoc.file_name });
}
event.messageReply = {
messageID: replyMsg.message_id,
senderID: replyMsg.from?.id?.toString() || "",
body: replyMsg.text || replyMsg.caption || "",
attachments: replyAttachments
};
}
return event;
}
module.exports = { createFcaApiWrapper, createFcaEventObject, createInputFile };