Skip to content

Commit

Permalink
fix: make features introduced in #270 a setting option
Browse files Browse the repository at this point in the history
the new settings default to false
  • Loading branch information
Lulalaby committed May 4, 2023
1 parent a9f006b commit cc554ed
Show file tree
Hide file tree
Showing 6 changed files with 119 additions and 33 deletions.
4 changes: 4 additions & 0 deletions example.settings.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ telegram:
colonAfterSenderName: false
skipOldMessages: true
sendEmojiWithStickers: true
useCustomEmojiFilter: false # Experimental, might break
replaceAtWithHash: false # Experimental, might break
replaceExcessiveSpaces: false # Experimental, might break
removeNewlineSpaces: false # Experimental, might break
discord:
useNickname: false
token: DISCORD_BOT_TOKEN_HERE # Discord bot tokens look like this: MjI3MDA1NzIvOBQ2MzAzMiMz.DRf-aw.N0MVYtDxXYPSQew4g2TPqvQve2c
Expand Down
7 changes: 4 additions & 3 deletions src/discord2telegram/handleEmbed.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Embed } from "discord.js";
import { md2html } from "./md2html";
import { TelegramSettings } from "../settings/TelegramSettings";

/****************************
* The handleEmbed function *
Expand All @@ -13,7 +14,7 @@ import { md2html } from "./md2html";
*
* @returns A string ready to send to Telegram
*/
export function handleEmbed(embed: Embed, senderName: string) {
export function handleEmbed(embed: Embed, senderName: string, settings: TelegramSettings) {
// Construct the text to send
let text = `<b>${senderName}</b>\n`;

Expand All @@ -32,12 +33,12 @@ export function handleEmbed(embed: Embed, senderName: string) {

// Handle the description
if (embed.description !== undefined) {
text += md2html(embed.description!) + "\n";
text += md2html(embed.description!, settings) + "\n";
}

// Handle the fields
embed.fields.forEach(field => {
text += `\n<b>${field.name}</b>\n` + md2html(field.value) + "\n";
text += `\n<b>${field.name}</b>\n` + md2html(field.value, settings) + "\n";
});

// Handle the author part
Expand Down
42 changes: 27 additions & 15 deletions src/discord2telegram/md2html.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import simpleMarkdown, { SingleASTNode } from "simple-markdown";
import { escapeHTMLSpecialChars, customEmojiFilter, replaceAtWithHash, replaceExcessiveSpaces, removeNewlineSpaces } from "./helpers";
import { TelegramSettings } from "../settings/TelegramSettings";
import {
escapeHTMLSpecialChars,
customEmojiFilter,
replaceAtWithHash,
replaceExcessiveSpaces,
removeNewlineSpaces
} from "./helpers";
import R from "ramda";

/***********
Expand Down Expand Up @@ -80,7 +87,7 @@ const mdParse = simpleMarkdown.defaultBlockParse;
*
* @return Telegram-friendly HTML
*/
export function md2html(text: string) {
export function md2html(text: string, settings: TelegramSettings) {
// XXX Some users get a space after @ in mentions bridged to Telegram. See #148
// This is compensation for that discord error
text = R.replace("@\u200B", "@", R.defaultTo("", text));
Expand Down Expand Up @@ -118,19 +125,24 @@ export function md2html(text: string) {
// Build the HTML
return html + `${tags.start}${extractText(node)}${tags.end}`;
}, "");
return htmlCleanup(html, settings);
}

function htmlCleanup(input: string, settings: TelegramSettings) {
if (settings.useCustomEmojiFilter) {
input = customEmojiFilter(input);
}

if (settings.replaceAtWithHash) {
input = replaceAtWithHash(input);
}

if (settings.replaceExcessiveSpaces) {
input = replaceExcessiveSpaces(input);
}

// Making a couple of formatting adjustments
function htmlCleanup(input: string){
// Removing custom emojis from the HTML
input = customEmojiFilter(input)
// Replacing @ character with # character to prevent unintentional references in Telegram
input = replaceAtWithHash(input)
// Replacing excessive whitespaces with a single space (tends to be an issue after custom emoji filtering)
input = replaceExcessiveSpaces(input)
// Removing whitespaces if they're placed on the beginning of the newline (tends to be an issue after custom emoji filtering)
input = removeNewlineSpaces(input)
return input;
if (settings.removeNewlineSpaces) {
input = removeNewlineSpaces(input);
}

return htmlCleanup(html);
return input;
}
15 changes: 7 additions & 8 deletions src/discord2telegram/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ export function setup(
}

// Convert it to something Telegram likes
const text = handleEmbed(embed, senderName);
const text = handleEmbed(embed, senderName, settings.telegram);

try {
// Send it
Expand All @@ -245,7 +245,7 @@ export function setup(
// Check if there is an ordinary text message
if (message.cleanContent) {
// Modify the message to fit Telegram
const processedMessage = md2html(message.cleanContent);
const processedMessage = md2html(message.cleanContent, settings.telegram);

// Pass the message on to Telegram
try {
Expand Down Expand Up @@ -294,8 +294,8 @@ export function setup(
message
.reply(
"This is an instance of a TediCross bot, bridging a chat in Telegram with one in Discord. " +
"If you wish to use TediCross yourself, please download and create an instance. " +
"See https://github.com/TediCross/TediCross"
"If you wish to use TediCross yourself, please download and create an instance. " +
"See https://github.com/TediCross/TediCross"
)
// Delete it again after some time
.then(sleepOneMinute)
Expand All @@ -316,9 +316,8 @@ export function setup(
// Pass it on to the bridges
bridgeMap.fromDiscordChannelId(Number(newMessage.channel.id)).forEach(async bridge => {
try {

// Get the corresponding Telegram message ID
let [tgMessageId] = await messageMap.getCorresponding(
const [tgMessageId] = await messageMap.getCorresponding(
MessageMap.DISCORD_TO_TELEGRAM,
bridge,
newMessage.id
Expand All @@ -331,7 +330,7 @@ export function setup(
(settings.telegram.colonAfterSenderName ? ":" : "");

// Modify the message to fit Telegram
const processedMessage = md2html(newMessage.cleanContent || "");
const processedMessage = md2html(newMessage.cleanContent || "", settings.telegram);

// Send the update to Telegram
const textToSend = bridge.discord.sendUsernames
Expand Down Expand Up @@ -361,7 +360,7 @@ export function setup(
try {
// Get the corresponding Telegram message IDs
const tgMessageIds = isFromTelegram
? await messageMap.getCorrespondingReverse(MessageMap.DISCORD_TO_TELEGRAM, bridge, message.id)
? await messageMap.getCorrespondingReverse(MessageMap.DISCORD_TO_TELEGRAM, bridge, message.id)
: await messageMap.getCorresponding(MessageMap.DISCORD_TO_TELEGRAM, bridge, message.id);
//console.log("d2t delete: " + tgMessageIds);
// Try to delete them
Expand Down
34 changes: 28 additions & 6 deletions src/settings/Settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,33 @@ export class Settings {
* @throws If the object is not suitable. The error message says what the problem is
*/
static validate(settings: SettingProperties) {

// An Array of valid units of time
const validUnitsOfTime = ["year", "years", "y", "month", "months", "M", "week", "weeks", "w",
"day", "days", "d", "hour", "hours", "h", "minute", "minutes", "m", "second", "seconds", "s",
"millisecond", "milliseconds", "ms"];
const validUnitsOfTime = [
"year",
"years",
"y",
"month",
"months",
"M",
"week",
"weeks",
"w",
"day",
"days",
"d",
"hour",
"hours",
"h",
"minute",
"minutes",
"m",
"second",
"seconds",
"s",
"millisecond",
"milliseconds",
"ms"
];

// Check that the settings are indeed in object form
if (!(settings instanceof Object)) {
Expand Down Expand Up @@ -149,7 +171,7 @@ export class Settings {
// Check that all the bridges have unique names
settings.bridges.forEach(function (value: Bridge, index: number, array: Bridge[]) {
for (let i = 0; i < array.length; i++) {
if ((value.name === array[i].name) && (i !== index)) {
if (value.name === array[i].name && i !== index) {
throw new Error("`settings.bridges` must have unique names for each bridge");
}
}
Expand Down Expand Up @@ -231,7 +253,7 @@ export class Settings {
discord: DiscordSettings.DEFAULTS,
bridges: [],
messageTimeoutAmount: 24,
messageTimeoutUnit: 'hours',
messageTimeoutUnit: "hours",
persistentMessageMap: false,
debug: false
} as any;
Expand Down
50 changes: 49 additions & 1 deletion src/settings/TelegramSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ interface SettingProperties {
colonAfterSenderName: boolean;
sendEmojiWithStickers: boolean;
useFirstNameInsteadOfUsername: boolean;
useCustomEmojiFilter: boolean;
replaceAtWithHash: boolean;
replaceExcessiveSpaces: boolean;
removeNewlineSpaces: boolean;
}

/******************************
Expand All @@ -17,6 +21,10 @@ export class TelegramSettings {
colonAfterSenderName: boolean;
skipOldMessages: boolean;
sendEmojiWithStickers: boolean;
useCustomEmojiFilter: boolean;
replaceAtWithHash: boolean;
replaceExcessiveSpaces: boolean;
removeNewlineSpaces: boolean;

/**
* Creates a new TelegramSettings object
Expand All @@ -27,6 +35,10 @@ export class TelegramSettings {
* @param settings.colonAfterSenderName Whether or not to put a colon after the name of the sender in messages from Discord to Telegram. If true, the name is displayed `Name:`. If false, it is displayed `Name`
* @param settings.skipOldMessages Whether or not to skip through all previous messages cached from the telegram-side and start processing new messages ONLY
* @param settings.sendEmojiWithStickers Whether or not to send the corresponding emoji when relaying stickers to Discord
* @param settings.useCustomEmojiFilter Whether or not to use the custom emoji filter
* @param settings.replaceAtWithHash Whether or not to replace @ with #
* @param settings.replaceExcessiveSpaces Whether or not to replace excessive spaces
* @param settings.removeNewlineSpaces Whether or not to remove newline spaces
*
* @throws If the settings object does not validate
*/
Expand All @@ -48,6 +60,18 @@ export class TelegramSettings {

/** Whether or not to send the corresponding emoji when relaying stickers to Discord */
this.sendEmojiWithStickers = settings.sendEmojiWithStickers;

/** Whether or not to use the custom emoji filter */
this.useCustomEmojiFilter = settings.useCustomEmojiFilter;

/** Whether or not to replace @ with # */
this.replaceAtWithHash = settings.replaceAtWithHash;

/** Whether or not to replace excessive spaces */
this.replaceExcessiveSpaces = settings.replaceExcessiveSpaces;

/** Whether or not to remove newline spaces */
this.removeNewlineSpaces = settings.removeNewlineSpaces;
}

/** The bot token to use */
Expand Down Expand Up @@ -107,6 +131,26 @@ export class TelegramSettings {
if (Boolean(settings.sendEmojiWithStickers) !== settings.sendEmojiWithStickers) {
throw new Error("`settings.sendEmojiWithStickers` must be a boolean");
}

// Check that useCustomEmojiFilter is a boolean
if (Boolean(settings.useCustomEmojiFilter) !== settings.useCustomEmojiFilter) {
throw new Error("`settings.useCustomEmojiFilter` must be a boolean");
}

// Check that replaceAtWithHash is a boolean
if (Boolean(settings.replaceAtWithHash) !== settings.replaceAtWithHash) {
throw new Error("`settings.replaceAtWithHash` must be a boolean");
}

// Check that replaceExcessiveSpaces is a boolean
if (Boolean(settings.replaceExcessiveSpaces) !== settings.replaceExcessiveSpaces) {
throw new Error("`settings.replaceExcessiveSpaces` must be a boolean");
}

// Check that removeNewlineSpaces is a boolean
if (Boolean(settings.removeNewlineSpaces) !== settings.removeNewlineSpaces) {
throw new Error("`settings.removeNewlineSpaces` must be a boolean");
}
}

/** Constant telling the Telegram token should be gotten from the environment */
Expand All @@ -121,7 +165,11 @@ export class TelegramSettings {
useFirstNameInsteadOfUsername: false,
colonAfterSenderName: false,
skipOldMessages: true,
sendEmojiWithStickers: true
sendEmojiWithStickers: true,
useCustomEmojiFilter: false,
replaceAtWithHash: false,
replaceExcessiveSpaces: false,
removeNewlineSpaces: false
};
}
}

0 comments on commit cc554ed

Please sign in to comment.