Last active
April 18, 2021 12:04
-
-
Save waptik/dff071a40d87507da497555ede8599c4 to your computer and use it in GitHub Desktop.
How to get and save photo by group media in telegrafjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Composer, MiddlewareFn } from "telegraf" | |
import { logAction } from "app/core/helpers/logAction" | |
import { BotContext } from "types" | |
import { report } from "../helpers" | |
import { withoutKeys } from "app/core/helpers/misc" | |
import { Message } from "typegram" | |
// @see https://github.com/TGxTG/TOUGAO/blob/master/src/model/Message.js#L86 | |
const map = new Map() | |
const trackImages: MiddlewareFn<BotContext> = Composer.on("photo", async (ctx, next) => { | |
logAction("trackImages") | |
try { | |
const { message } = ctx | |
if (message.media_group_id) { | |
let groupMsg = processMediaMessage(message) | |
const handler = setTimeout(() => ctx.reply(groupMsg), 500) | |
clearTimeout(handler) | |
let reply_to_message_id = message.message_id | |
? message.message_id | |
: groupMsg.media[0].message_id | |
ctx.replyWithMediaGroup(groupMsg.media, { | |
reply_to_message_id, | |
}) | |
logAction("medias map", JSON.stringify(groupMsg)) | |
} else { | |
ctx.reply(`MSG w/o GroupMedia: ${JSON.stringify({ message })}`) | |
logAction("medias map", JSON.stringify(message)) | |
} | |
} catch (error) { | |
report(error, "trackImages") | |
} finally { | |
return next() | |
} | |
}) | |
function processMediaMessage(message: Message.PhotoMessage) { | |
logAction("processMediaMessage") | |
try { | |
const mediaId = message.media_group_id | |
let groupMsg = map.get(mediaId) | |
if (!groupMsg) { | |
groupMsg = withoutKeys(message, ["caption", "photo", "video", "message_id"]) | |
groupMsg.media = [] | |
} else { | |
let ids = Object.keys(groupMsg.media).map((f) => groupMsg.media[f].message_id) | |
if (ids.includes(message.message_id)) { | |
return groupMsg | |
} | |
} | |
const photo = message.photo.pop() | |
const mediaRow: Record<string, any> = { | |
message_id: message.message_id, | |
media: photo?.file_id, | |
type: "photo", | |
size: { | |
weigth: photo?.file_size, | |
height: 320, | |
width: 254, | |
}, | |
parse_mode: "Markdown", | |
} | |
if (message.caption) { | |
mediaRow.caption = message.caption | |
} | |
groupMsg.media.push(mediaRow) | |
if (groupMsg.media[0].caption) { | |
groupMsg.caption = groupMsg.media[0].caption | |
} | |
// add / update | |
map.set(mediaId, groupMsg) | |
logAction("count media ==>", groupMsg.media.length) | |
return map.get(mediaId) | |
} catch (error) { | |
report(error, "processMediaMessage") | |
} | |
} | |
export default trackImages |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment