Skip to content

Commit

Permalink
transfer group of files from Discord to Tg as Gallery
Browse files Browse the repository at this point in the history
  • Loading branch information
kutuk committed Aug 3, 2023
1 parent 3285512 commit d460409
Show file tree
Hide file tree
Showing 3 changed files with 157 additions and 51 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "tedicross",
"version": "0.11.11",
"version": "0.12.0",
"description": "Bridging Telegram and Discord",
"license": "MIT",
"repository": {
Expand Down
197 changes: 148 additions & 49 deletions src/discord2telegram/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { Telegraf } from "telegraf";
import { escapeHTMLSpecialChars, ignoreAlreadyDeletedError } from "./helpers";
import { Client, Message, TextChannel } from "discord.js";
import { Settings } from "../settings/Settings";
import { InputMediaVideo, InputMediaAudio, InputMediaDocument, InputMediaPhoto } from "telegraf/types";

/***********
* Helpers *
Expand Down Expand Up @@ -147,10 +148,10 @@ export function setup(
// Check if the message is from the correct chat
const bridges = bridgeMap.fromDiscordChannelId(Number(message.channel.id));
if (!R.isEmpty(bridges)) {
bridges.forEach(async bridge => {
for (const bridge of bridges) {
// Ignore it if this is a telegram-to-discord bridge
if (bridge.direction === Bridge.DIRECTION_TELEGRAM_TO_DISCORD) {
return;
continue;
}

// This is now the latest message for this bridge
Expand Down Expand Up @@ -183,16 +184,24 @@ export function setup(
}
}

// Check for attachments and pass them on
message.attachments.forEach(async ({ url }) => {
// console.dir(message.attachments);

// Check if there is an ordinary text message
if (message.cleanContent) {
// Modify the message to fit Telegram
const processedMessage = md2html(message.cleanContent, settings.telegram);

// Pass the message on to Telegram
try {
const textToSend = bridge.discord.sendUsernames
? `<b>${senderName}</b>\n<a href="${url}">${url}</a>`
: `<a href="${url}">${url}</a>`;
? `<b>${senderName}</b>\n${processedMessage}`
: processedMessage;
if (replyId === "0" || replyId === undefined) {
const tgMessage = await tgBot.telegram.sendMessage(bridge.telegram.chatId, textToSend, {
parse_mode: "HTML"
});

// Make the mapping so future edits can work
messageMap.insert(
MessageMap.DISCORD_TO_TELEGRAM,
bridge,
Expand All @@ -212,9 +221,139 @@ export function setup(
);
}
} catch (err) {
logger.error(`[${bridge.name}] Telegram did not accept an attachment:`, (err as Error).toString());
logger.error(`[${bridge.name}] Telegram did not accept a message`);
logger.error(`[${bridge.name}] Failed message:`, (err as Error).toString());
}
});
}

// NOTE: can set caption for media group if media types <= 1 - else send text in standalone message
// For now: ignoring captions - always send as standalone message

// Check for attachments and pass them on
// TODO: limit = 10 files (if more - split)
const images = []; // size limit = 10 mb
const videos = []; // size limit = 20 mb
const audios = [];
const documents = [];

for (const attachment of message.attachments.values()) {
const fileType: string = attachment.contentType || "";
if (fileType.indexOf("video") >= 0) {
if (attachment.size < 20000000) {
videos.push({
media: { url: attachment.url },
type: "video"
} as InputMediaVideo);
} else {
logger.error(`[${bridge.name}] Too big attachment Video File: ${attachment.name}`);
}
} else if (fileType.indexOf("image") >= 0) {
if (attachment.size < 10000000) {
images.push({ media: { url: attachment.url }, type: "photo" } as InputMediaPhoto);
} else {
logger.error(`[${bridge.name}] Too big attachment Image File: ${attachment.name}`);
}
} else if (fileType.indexOf("audio") >= 0) {
if (attachment.size < 20000000) {
audios.push({ media: { url: attachment.url }, type: "audio" } as InputMediaAudio);
} else {
logger.error(`[${bridge.name}] Too big attachment Audio File: ${attachment.name}`);
}
} else {
if (attachment.size < 20000000) {
documents.push({ media: { url: attachment.url }, type: "document" } as InputMediaDocument);
} else {
logger.error(`[${bridge.name}] Too big attachment Document File: ${attachment.name}`);
}
}
}

// TODO refactoring - combine in one cycle
// let tgMessage;
if (images.length) {
try {
if (images.length > 1) {
// tgMessage =
await tgBot.telegram.sendMediaGroup(bridge.telegram.chatId, images, {
reply_to_message_id: +replyId
});
} else {
// tgMessage =
await tgBot.telegram.sendPhoto(bridge.telegram.chatId, images[0].media, {
reply_to_message_id: +replyId
});
}
// NOTE: disabled message mapping for galleries
// messageMap.insert(
// MessageMap.DISCORD_TO_TELEGRAM,
// bridge,
// message.id,
// tgMessage.message_id.toString()
// );
} catch (err) {
logger.error(
`[${bridge.name}] Telegram did not accept an Image attachment:`,
(err as Error).toString()
);
}
}

if (videos.length) {
try {
if (videos.length > 1) {
await tgBot.telegram.sendMediaGroup(bridge.telegram.chatId, videos, {
reply_to_message_id: +replyId
});
} else {
await tgBot.telegram.sendVideo(bridge.telegram.chatId, videos[0].media, {
reply_to_message_id: +replyId
});
}
} catch (err) {
logger.error(
`[${bridge.name}] Telegram did not accept Video attachment:`,
(err as Error).toString()
);
}
}

if (audios.length) {
try {
if (videos.length > 1) {
await tgBot.telegram.sendMediaGroup(bridge.telegram.chatId, audios, {
reply_to_message_id: +replyId
});
} else {
await tgBot.telegram.sendAudio(bridge.telegram.chatId, audios[0].media, {
reply_to_message_id: +replyId
});
}
} catch (err) {
logger.error(
`[${bridge.name}] Telegram did not accept Audio attachment:`,
(err as Error).toString()
);
}
}

if (documents.length) {
try {
if (videos.length > 1) {
await tgBot.telegram.sendMediaGroup(bridge.telegram.chatId, documents, {
reply_to_message_id: +replyId
});
} else {
await tgBot.telegram.sendDocument(bridge.telegram.chatId, documents[0].media, {
reply_to_message_id: +replyId
});
}
} catch (err) {
logger.error(
`[${bridge.name}] Telegram did not accept Document attachment:`,
(err as Error).toString()
);
}
}

// Check the message for embeds
message.embeds.forEach(embed => {
Expand Down Expand Up @@ -244,47 +383,7 @@ export function setup(
logger.error(`[${bridge.name}] Telegram did not accept an embed:`, (err as Error).toString());
}
});

// Check if there is an ordinary text message
if (message.cleanContent) {
// Modify the message to fit Telegram
const processedMessage = md2html(message.cleanContent, settings.telegram);

// Pass the message on to Telegram
try {
const textToSend = bridge.discord.sendUsernames
? `<b>${senderName}</b>\n${processedMessage}`
: processedMessage;
if (replyId === "0" || replyId === undefined) {
const tgMessage = await tgBot.telegram.sendMessage(bridge.telegram.chatId, textToSend, {
parse_mode: "HTML"
});

// Make the mapping so future edits can work
messageMap.insert(
MessageMap.DISCORD_TO_TELEGRAM,
bridge,
message.id,
tgMessage.message_id.toString()
);
} else {
const tgMessage = await tgBot.telegram.sendMessage(bridge.telegram.chatId, textToSend, {
reply_to_message_id: +replyId,
parse_mode: "HTML"
});
messageMap.insert(
MessageMap.DISCORD_TO_TELEGRAM,
bridge,
message.id,
tgMessage.message_id.toString()
);
}
} catch (err) {
logger.error(`[${bridge.name}] Telegram did not accept a message`);
logger.error(`[${bridge.name}] Failed message:`, (err as Error).toString());
}
}
});
}
} else if (
R.isNil((message.channel as TextChannel).guild) ||
!knownServerIds.has((message.channel as TextChannel).guild.id)
Expand Down
9 changes: 8 additions & 1 deletion src/telegram2discord/middlewares.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,13 @@ function addMessageObj(ctx: TediCrossContext, next: () => void) {
return;
}

// TODO: console
console.dir((ctx as any).update);

if ((ctx as any).update.message.photo) {
console.log(JSON.stringify((ctx as any).update.message.photo, null, " "));
}

ctx.tediCross.message = R.cond([
// XXX I tried both R.has and R.hasIn as conditions. Neither worked for some reason
[ctx => !R.isNil((ctx as any).update.channel_post), R.path(["update", "channel_post"])],
Expand Down Expand Up @@ -290,7 +297,7 @@ function informThisIsPrivateBot(ctx: TediCrossContext, next: () => void) {
"This is an instance of a [TediCross](https://github.com/TediCross/TediCross) bot, " +
"bridging a chat in Telegram with one in Discord. " +
"If you wish to use TediCross yourself, please download and create an instance.",
{parse_mode: "Markdown"}
{ parse_mode: "Markdown" }
)
.then(msg =>
// Delete it again after a while
Expand Down

0 comments on commit d460409

Please sign in to comment.