From 8361d9c8ff5f33b87f50bd2d5c74d3250eb422fc Mon Sep 17 00:00:00 2001 From: Christian Kellner Date: Fri, 12 Nov 2021 09:14:55 +0100 Subject: [PATCH] splitting telegram messages into chunks to avoid errors when message exceeds limit of 4096 chars --- lib/notification/adapter/telegram.js | 45 ++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/lib/notification/adapter/telegram.js b/lib/notification/adapter/telegram.js index 6cfc7bc..745a71e 100644 --- a/lib/notification/adapter/telegram.js +++ b/lib/notification/adapter/telegram.js @@ -1,6 +1,19 @@ const { markdown2Html } = require('../../services/markdown'); const axios = require('axios'); +/** + * splitting an array into chunks because Telegram only allows for messages up to + * 4096 chars, thus we have to split messages into chunks + * @param inputArray + * @param perChunk + */ +const arrayChunks = (inputArray, perChunk) => + inputArray.reduce((all, one, i) => { + const ch = Math.floor(i / perChunk); + all[ch] = [].concat(all[ch] || [], one); + return all; + }, []); + /** * sends new listings to telegram * @param serviceName e.g immowelt @@ -12,22 +25,28 @@ const axios = require('axios'); exports.send = ({ serviceName, newListings, notificationConfig, jobKey }) => { const { token, chatId } = notificationConfig.find((adapter) => adapter.id === 'telegram').fields; - let message = `Job: ${jobKey} | Service ${serviceName} found ${newListings.length} new listings:\n\n`; + //we have to split messages into chunk, because otherwise messages are going to become too big and will fail + const chunks = arrayChunks(newListings, 3); - message += newListings.map( - (o) => - `${shorten(o.title.replace(/\*/g, ''), 45)}\n` + - [o.address, o.price, o.size].join(' | ') + - '\n' + - `${o.link}\n\n` - ); + const promises = chunks.map((chunk) => { + let message = `Job: ${jobKey} | Service ${serviceName} found ${newListings.length} new listings:\n\n`; + message += chunk.map( + (o) => + `${shorten(o.title.replace(/\*/g, ''), 45)}\n` + + [o.address, o.price, o.size].join(' | ') + + '\n' + + `${o.link}\n\n` + ); - return axios.post(`https://api.telegram.org/bot${token}/sendMessage`, { - chat_id: chatId, - text: message, - parse_mode: 'HTML', - disable_web_page_preview: true, + return axios.post(`https://api.telegram.org/bot${token}/sendMessage`, { + chat_id: chatId, + text: message, + parse_mode: 'HTML', + disable_web_page_preview: true, + }); }); + + return Promise.all(promises); }; function shorten(str, len = 30) {