Skip to content

Instantly share code, notes, and snippets.

@mannguyen0107
Created January 3, 2022 14:25
Show Gist options
  • Save mannguyen0107/b6787aa87b5df3b13adccb7b986869d6 to your computer and use it in GitHub Desktop.
Save mannguyen0107/b6787aa87b5df3b13adccb7b986869d6 to your computer and use it in GitHub Desktop.
Gramjs album event handler with download photo
albumEventHandler = async (event: AlbumEvent) => {
const messages = event.messages;
const chat = (await messages[0].getChat()) as Api.Channel;
const chatId = messages[0].chatId.toString();
const noForwards = chat.noforwards;
await this.sendAlbumToForwardChannel(messages, chatId, noForwards);
};
sendAlbumToForwardChannel = async (
messages: Api.Message[],
sourceChannelId: Api.long,
noForwards: boolean = false,
) => {
try {
const media = [];
for (let index = 0; index < messages.length; index++) {
const message = messages[index];
let inputPhoto: Api.TypeInputMedia | null = null;
if (noForwards) {
inputPhoto = await downloadPhoto(this.client, message, 'SOMEWHERE TO SEND TO');
} else {
inputPhoto = utils.getInputMedia(message.media, {
isPhoto: true,
});
}
const [formattedMessage, formattingEntities] = await _parseMessageText(
this.client,
processMessage(message, true) || '',
'md',
);
media.push(
new Api.InputSingleMedia({
media: inputPhoto,
message: formattedMessage,
entities: formattingEntities,
randomId: generateRandomBigInt(),
}),
);
}
await this.client.invoke(
new Api.messages.SendMultiMedia({
peer: 'SOMEWHERE TO SEND TO',
multiMedia: media,
}),
);
} catch (error) {
console.error(error);
return;
}
};
export const downloadPhoto = async (
client: TelegramClient,
message: Api.Message,
forwardChannelId: string | bigint,
): Promise<Api.InputMediaUploadedPhoto> => {
const downloadedMediaBuffer = await client.downloadMedia(message, {});
const fileToUpload = new CustomFile(
`${message.id.toString()}.jpg`,
downloadedMediaBuffer.length,
'',
downloadedMediaBuffer,
);
const uploadedPhoto = await client.uploadFile({ file: fileToUpload, workers: 1 });
const inputMediaUploadedPhoto = new Api.InputMediaUploadedPhoto({ file: uploadedPhoto });
const uploadedMedia = (await client.invoke(
new Api.messages.UploadMedia({
peer: forwardChannelId,
media: inputMediaUploadedPhoto,
}),
)) as Api.MessageMediaPhoto;
const inputPhoto = getInputMedia(r.photo);
return inputPhoto;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment