telegram-send.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /**
  2. * @node telegram-send
  3. * @name Telegram
  4. * @category integration
  5. * @version 1.0.0
  6. * @description Send a message, photo or document to a Telegram chat through a bot
  7. * @icon send
  8. */
  9. const configSchema = {
  10. type: 'object',
  11. properties: {
  12. credentialId: {
  13. type: 'string',
  14. title: 'Bot Token Credential',
  15. description: 'An API key or bearer credential holding the bot token from BotFather',
  16. dynamicOptions: {
  17. source: 'credentials',
  18. filter: { type: ['api_key', 'bearer'] }
  19. }
  20. },
  21. chatId: {
  22. type: 'string',
  23. title: 'Chat ID',
  24. description: 'Numeric chat id, or @channelusername for a public channel'
  25. },
  26. action: {
  27. type: 'string',
  28. title: 'Action',
  29. enum: ['sendMessage', 'sendPhoto', 'sendDocument'],
  30. default: 'sendMessage',
  31. description: 'What to send'
  32. },
  33. text: {
  34. type: 'string',
  35. title: 'Text',
  36. description: 'Message text, or the caption for a photo or document. Supports {{variable}} interpolation.'
  37. },
  38. parseMode: {
  39. type: 'string',
  40. title: 'Formatting',
  41. enum: ['none', 'Markdown', 'MarkdownV2', 'HTML'],
  42. default: 'none',
  43. description: 'How Telegram should interpret markup in the text'
  44. },
  45. fileUrl: {
  46. type: 'string',
  47. title: 'File URL',
  48. description: 'Address of the photo or document to send. Telegram fetches it itself.'
  49. },
  50. fileId: {
  51. type: 'string',
  52. title: 'Stored File ID',
  53. description: 'File store id to upload instead of giving Telegram an address'
  54. },
  55. disableNotification: {
  56. type: 'boolean',
  57. title: 'Send Silently',
  58. description: 'Deliver without a notification sound',
  59. default: false
  60. },
  61. replyToMessageId: {
  62. type: 'string',
  63. title: 'Reply To Message ID',
  64. description: 'Send as a reply to this message'
  65. },
  66. apiBaseUrl: {
  67. type: 'string',
  68. title: 'API Base URL',
  69. description: 'Telegram Bot API address, for a self-hosted API server',
  70. default: 'https://api.telegram.org'
  71. },
  72. timeoutMs: {
  73. type: 'number',
  74. title: 'Timeout (ms)',
  75. default: 30000
  76. }
  77. },
  78. required: ['credentialId', 'chatId']
  79. };
  80. const inputSchema = {
  81. type: 'object',
  82. properties: {
  83. chatId: { type: 'string', description: 'Overrides the configured chat' },
  84. text: { type: 'string', description: 'Overrides the configured text' },
  85. fileUrl: { type: 'string', description: 'Overrides the configured file address' },
  86. fileId: { type: 'string', description: 'Overrides the configured stored file' }
  87. }
  88. };
  89. const outputSchema = {
  90. type: 'object',
  91. properties: {
  92. success: { type: 'boolean' },
  93. messageId: { type: 'integer', description: 'The id Telegram gave the sent message' },
  94. chatId: { type: 'string' },
  95. date: { type: 'integer', description: 'When Telegram accepted it, in seconds' }
  96. }
  97. };
  98. const outputs = [
  99. { name: 'main', displayName: 'Sent', type: 'object', color: '#3b82f6' }
  100. ];
  101. // A connection hands the previous node's whole output over as input.data, and
  102. // some nodes wrap their own return in a result object on top of that. Rather
  103. // than guess which shape arrived, the layers are flattened with the innermost
  104. // winning, so a field set anywhere in the chain is found.
  105. function incoming(input) {
  106. const isPlain = (v) => v && typeof v === 'object' && !Array.isArray(v);
  107. const merged = {};
  108. for (const layer of [input, input && input.data, input && input.data && input.data.result]) {
  109. if (!isPlain(layer)) continue;
  110. for (const key of Object.keys(layer)) {
  111. merged[key] = layer[key];
  112. }
  113. }
  114. return merged;
  115. }
  116. // The bot token belongs in the URL rather than a header, so the stored header
  117. // value is unwrapped: a bearer credential arrives prefixed, an api key does not.
  118. function readBotToken(credentialId) {
  119. const credential = smartbotic.credentials.get(credentialId);
  120. if (!credential || !credential.success) {
  121. throw new Error('Could not read the bot token credential: ' +
  122. ((credential && credential.error) || 'unknown error'));
  123. }
  124. const value = String(credential.headerValue || '').trim();
  125. const token = value.indexOf('Bearer ') === 0 ? value.substring(7).trim() : value;
  126. if (!token) {
  127. throw new Error('The credential holds no bot token');
  128. }
  129. return token;
  130. }
  131. // Telegram accepts a file either as an address it fetches or as an upload. A
  132. // stored file has no address Telegram's servers can reach, so its bytes are
  133. // posted as multipart form data instead.
  134. function uploadStoredFile(url, field, fileId, fields, timeout) {
  135. const info = smartbotic.storage.getFileInfo(fileId);
  136. const file = smartbotic.storage.downloadFile(fileId);
  137. if (!file || !file.success || !file.data) {
  138. throw new Error('Stored file ' + fileId + ' could not be read');
  139. }
  140. // Every value in a form part is sent as text, so the flags Telegram expects
  141. // as booleans or numbers are written out as strings here.
  142. const formData = {};
  143. for (const key of Object.keys(fields)) {
  144. formData[key] = String(fields[key]);
  145. }
  146. return smartbotic.http.request({
  147. method: 'POST',
  148. url: url,
  149. formData: formData,
  150. files: [{
  151. name: field,
  152. filename: (info && info.name) || fileId,
  153. mimeType: (info && info.mimeType) || 'application/octet-stream',
  154. data: file.data
  155. }],
  156. timeout: timeout
  157. });
  158. }
  159. module.exports = {
  160. configSchema,
  161. inputSchema,
  162. outputSchema,
  163. outputs,
  164. async execute(config, input, context) {
  165. const from = incoming(input);
  166. if (!config.credentialId) {
  167. throw new Error('A bot token credential is required');
  168. }
  169. const chatId = String(from.chatId || config.chatId || '').trim();
  170. if (!chatId) {
  171. throw new Error('A chat id is required');
  172. }
  173. const action = config.action || 'sendMessage';
  174. const text = from.text || config.text || '';
  175. const token = readBotToken(config.credentialId);
  176. const base = String(config.apiBaseUrl || 'https://api.telegram.org').replace(/\/+$/, '');
  177. const payload = { chat_id: chatId };
  178. if (config.parseMode && config.parseMode !== 'none') {
  179. payload.parse_mode = config.parseMode;
  180. }
  181. if (config.disableNotification === true) {
  182. payload.disable_notification = true;
  183. }
  184. if (config.replyToMessageId) {
  185. payload.reply_to_message_id = Number(config.replyToMessageId);
  186. }
  187. const url = base + '/bot' + token + '/' + action;
  188. const timeout = Number(config.timeoutMs) || 30000;
  189. const fileUrl = from.fileUrl || config.fileUrl;
  190. const fileId = from.fileId || config.fileId;
  191. let response;
  192. if (action === 'sendMessage') {
  193. if (!text) {
  194. throw new Error('Message text is required');
  195. }
  196. payload.text = text;
  197. response = smartbotic.http.request({
  198. method: 'POST',
  199. url: url,
  200. headers: { 'Content-Type': 'application/json' },
  201. body: JSON.stringify(payload),
  202. timeout: timeout
  203. });
  204. } else {
  205. const field = action === 'sendPhoto' ? 'photo' : 'document';
  206. if (text) payload.caption = text;
  207. if (fileId) {
  208. response = uploadStoredFile(url, field, fileId, payload, timeout);
  209. } else if (fileUrl) {
  210. // Telegram fetches the file itself from the address it is given,
  211. // which avoids moving the bytes through this node. The address
  212. // has to be one Telegram's servers can reach.
  213. payload[field] = fileUrl;
  214. response = smartbotic.http.request({
  215. method: 'POST',
  216. url: url,
  217. headers: { 'Content-Type': 'application/json' },
  218. body: JSON.stringify(payload),
  219. timeout: timeout
  220. });
  221. } else {
  222. throw new Error(action + ' requires a file URL or a stored file id');
  223. }
  224. }
  225. let body = response.data;
  226. if (typeof body === 'string') {
  227. try {
  228. body = JSON.parse(body);
  229. } catch (e) {
  230. // A proxy or a wrong API base answers with HTML, and parsing it
  231. // as JSON throws a syntax error that names neither the request
  232. // nor the response.
  233. throw new Error('Telegram ' + action + ' failed: HTTP ' + response.status +
  234. ' returned a non-JSON body: ' + body.substring(0, 200).replace(/\s+/g, ' '));
  235. }
  236. }
  237. // Telegram reports its own failures in the body with a 4xx status and a
  238. // description that says far more than the status code does.
  239. if (!body || body.ok !== true) {
  240. const description = (body && body.description) || ('HTTP ' + response.status);
  241. throw new Error('Telegram ' + action + ' failed: ' + description);
  242. }
  243. const message = body.result || {};
  244. smartbotic.log.info('Telegram: ' + action + ' to chat ' + chatId);
  245. return {
  246. success: true,
  247. messageId: message.message_id,
  248. chatId: chatId,
  249. date: message.date
  250. };
  251. }
  252. };