Node Red Contrib Telegrambot (Node) Node RED
Node Red Contrib Telegrambot (Node) Node RED
Node-RED
home
about
blog
documentation
forum
flows
github
node-red-contrib-telegrambot 16.1.0
Telegram bot nodes for Node-RED
This package contains a receiver and a sender node which act as a Telegram Bot. The only thing required is the token that can be retrieved by the @botfather
Telegram Bot.
Credits
dvv (Vladimir Dronnikov): for providing the saveDataDir configuration option
snippet-java: for adding venue messages and for providing the markdown problem fallback
greenstone7: for providing the callback query node
dceejay: for cleaning up the project
psyntium: for providing the weblink for additional content link videos, pictures, animations, audio files
MatthiasHunziker: for extending the callback query node to support generic events
Skiepp: for providing the send chat action idea.
MK-2001: for providing the sendMediaGroup fuhttps://github.com/yagop/node-telegram-bot-apinction
cowchimp: for adding the support for Node-RED v1.0+ (async)
JokerQyou: for adding the support for using webhook without certificate
bonastreyair: for providing ideas for improving the command node
StephanStS: for extension/clearification/beautification of Readme.md and finding minor bugs
Diddlik: for extending webhook options
MorbidDevil: for extending answerInlineQuery with options
daredoes: for providing the webhook decumentation on Unraid/Docker with SWAG/NGINX/REVERSE-PROXY
kickouille: for fixing the payment functions and providing the full payment example flow
skrashevich: for providing approveChatJoinRequest, declineChatJoinRequest
ShotokanZH: for providing the web app data example
Dodoooh: for providing the send to topic example flow
MariusSchiffer: for improving documentation
ptath: for providing pullrequest for setChatAdministratorCustomTitle
gmag11: for providing pullrequest for enhancing getFile
Installation
NPM
You can install the nodes using node-red's "Manage palette" in the side bar.
Or run the following command in the root directory of your Node-RED installation
npm install node-red-contrib-telegrambot --save
Note that the minimum node-red version 1.3.7 and minimum nodejs version is 12.x.
Dependencies
The nodes are tested with Node.js v18.20.0 and Node-RED v3.1.9.
node-telegram-bot-api
socks-proxy-agent
https://flows.nodered.org/node/node-red-contrib-telegrambot 1/19
06/12/2024, 11:55 node-red-contrib-telegrambot (node) - Node-RED
Changelog
Changes can be followed here.
Hints
It is recommended to always do a full deploy when you changed some of the nodes of this library to prevent unexpected behavior.
Do not use a token in more than one configuration node at the same time as the telegram server does not allow multiple connections for one bot.
Usage
Basics
Receiver and sender nodes
The Telegram receiver node receives messages from the bot and sends a message object with the following layout:
chatId : The unique id of the chat. This value needs to be passed to the out node when responding to the same chat
type : The type of message received. Types see table below
content : Received message content: String or file_id, or object with full data (location, contact)
Additional:
date (Optional element): Date the message was sent in Unix time (integer)
further elements depending on the type (see table below)
msg.originalMessage contains the original message object from the underlying node-telegram-bot-api lib.
The Telegram sender node sends the content to a specified username or chat. The node's input msg object is similar to the output msg object of the Telegram receiver
node. Some of the additional elements are mandatory and some are optional (see table below).
echo flow
Fig. 1: Simple echo flow
Note that media groups are sent/received not as a group, but as separate messages of type photo and video.
The following msg.payload.type contents indicate changes in the group or channel itself:
For more details of the content types listed above also refer to the telegram api description.
https://flows.nodered.org/node/node-red-contrib-telegrambot 2/19
06/12/2024, 11:55 node-red-contrib-telegrambot (node) - Node-RED
Message types and corresponding content elements in msg.payload
The msg.payload contains several elements additional to chatId, type and content. These additional elements depend on the contents of msg.payload.type. In addition
the format of msg.payload.content depends on the type.
The following table shows the relationship between the message type and additional elements.
Legend:
For more details of the content types listed above also refer to the telegram api description and the telegram bot api description.
Error handling
There are two ways of how to handle errors in the sender node:
https://flows.nodered.org/node/node-red-contrib-telegrambot 3/19
06/12/2024, 11:55 node-red-contrib-telegrambot (node) - Node-RED
Configuration Node
The mandatory configuration entries are
https://flows.nodered.org/node/node-red-contrib-telegrambot 4/19
06/12/2024, 11:55 node-red-contrib-telegrambot (node) - Node-RED
Instead of entering the token from bot father directly into the token field, you can also instruct the node to read ot from on external location.
The token field in the configuration node must then look like
{env.get("BOT_TOKEN")}
The node contains the two optional properties: Users and ChatIds. You may enter a list of names and/or chatIds that are authorized to use this bot. This is useful, if
the bot should only accept incoming calls from dedicated persons resp. chat groups. The values in the property fields must be separated by a comma e.g.:
Hugo,Sepp,Egon Leave the fields Users and ChatIds blank if you do not want to use this feature to mask senders.
User names can only be used, if a telegram user has set its Username in the Telegram settings. The following screenshot shows the according settings dialog in the
Telegram app where you can set your personal preferences:
If no Username is set you can only filter via the ChatId property.
https://flows.nodered.org/node/node-red-contrib-telegrambot 5/19
06/12/2024, 11:55 node-red-contrib-telegrambot (node) - Node-RED
This is the server url of the telegram server (https://api.telegram.org). If you use a different instance of a telegram server somewhere else (e.g. on premise) you could
then use this property to connect to that server instead the global one.
Polling mode
By default the bot is polling every 300ms for new messages. This polling interval can be set via the property Poll Interval in the Do you mean a table which
describes the logic within the function getMessageDetails(botMsg)? E.g. a table with these coloumns:
Webhook mode
As setting up a webhook can be very complex depending on the infrastructure this was moved to a seprate readme file. See also WEBHOOK.md
None mode
The None method may be chosen to avoid traffic due to polling or incoming webhook calls. You can only send messages using the sender node but you can not
receive any data.
SOCKS4/5 proxy support is optional when running behind a SOCKS4/5 proxy that requires authentication. In this case, additional configuration properties have to
be set in the configuration node.
As setting up a socks5 proxy can be very complex depending on the infrastructure this was moved to a seprate readme file. See also SOCKS5.md
The Verbose Logging flag should only be activated when debugging network problems as this will create cyclic warnings when the network is down.
Receiver Node
This node can receive telegram messages sent to the bot and (under certain circumstances) also receive messages from a chat.
https://flows.nodered.org/node/node-red-contrib-telegrambot 6/19
06/12/2024, 11:55 node-red-contrib-telegrambot (node) - Node-RED
Telegram messages sent directly to the bot are automatically received (if not masked via the configuration node property Users).
To be able to receive telegram chat messages, invite the bot to a chat (/setprivacy must be configured correctly!). If the configuration node property ChatIds is not
set, all chat messages are received.
You can control if the bot receives every message by calling /setprivacy @botfather (refer also to there).
Note that there are certain limitations for bots in channels, groups and super groups. You should make the bot admin or grant the rights if you discover problems. Bot
to bot communication is also not allowed by telegram. Please read the telegram bot documentation.
Configuration
When the receiver node receives data like videos, documents and so on, the file is downloaded automatically to the local harddisc when the node's property
Download Directory is set in the configuration node. The directory may also be part of the message payload: msg.payload.path. In addition to that the message
object may contain the direct download link in the payload: msg.payload.weblink.
Normally, a receiver node receives all content that is sent to the bot. However if you have command nodes next to a receiver you can enable the commands flag in the
configuration property Filter so that commands meant for a command node will not be handled by the receiver node.
I.e. the command message then only appears in the configured command node and not in this node.
Outputs
The original message from the underlying node library is stored in msg.originalMessage. The msg.payload contains the most important data like chatId, type and
content. Additional elements are present in the msg.payload structure and depend on the message type. These additional elements are described in the table Tab. 1
above.
The content format depends on the message type. E.g. if you receive a text message then the content format is a string, if you receive a location, the content format is
an object containing latitude and longitude. See also "available methods" in the api core description.
1. The node's upper output (Standard Output) is used if the message is from an authorized user.
2. The node's lower output (Unauthorized Output) is used when security is applied (via configuration properties Users and ChatIds) and the user is not
authorized to access the bot.
Sender Node
This node sends contents to a telegram user or to a telegram chat. It is triggered by an incoming msg object at its input containing all necessary telegram information.
Inputs
The input msg.payload must contain the following elements:
msg.payload.chatId - chatId or an array of chatIds if you want to send the same message to several chats
msg.payload.type - e.g. message, document, photo, etc. (see section Receiver Node above)
msg.payload.content - your message content (e.g. message text)
Additional elements are present in the msg.payload structure and depend on the message type. These additional elements are described in the table Tab. 1 above.
https://flows.nodered.org/node/node-red-contrib-telegrambot 7/19
06/12/2024, 11:55 node-red-contrib-telegrambot (node) - Node-RED
The content format depends on the message type. E.g. if you send a text message then the content format is a string, if you send a location, the content format is an
object containing latitude and longitude. See also "available methods" in the api core description.
Outputs
Basically the input msg object is forwarded unchanged to the node's output.
The node has up to two outputs (selectable via the Send errors to second output flag):
1. The node's first/upper output (Standard Output) is used if the message was successfully transmitted.
2. The node's second/lower output (Error Output) is used when an exception occured. The output msg object contains a string property msg.error.
Additionally to sending content, the sender node can be used to issue commands direct to the API. In this case the msg.payload elements contain (see examples for
further details):
https://flows.nodered.org/node/node-red-contrib-telegrambot 8/19
06/12/2024, 11:55 node-red-contrib-telegrambot (node) - Node-RED
msg.payload.type msg.payload.content msg.payload.options see also
editForumTopic message_thread_id (integer) optional arguments https://core.telegram.org/bots/api#editforumtopic
closeForumTopic message_thread_id (integer) - https://core.telegram.org/bots/api#closeforumtopic
reopenForumTopic message_thread_id (integer) - https://core.telegram.org/bots/api#reopenforumtopic
deleteForumTopic message_thread_id (integer) - https://core.telegram.org/bots/api#deleteforumtopic
editGeneralForumTopic name (string) - https://core.telegram.org/bots/api#editgeneralforumtopic
closeGeneralForumTopic - - https://core.telegram.org/bots/api#closegeneralforumtopic
reopenGeneralForumTopic - - https://core.telegram.org/bots/api#reopengeneralforumtopic
hideGeneralForumTopic - - https://core.telegram.org/bots/api#hidegeneralforumtopic
unhideGeneralForumTopic - - https://core.telegram.org/bots/api#unhidegeneralforumtopic
stopPoll message_id (integer) optional arguments https://core.telegram.org/bots/api#stoppoll
setChatAdministratorCustomTitle message_id (integer) optional arguments https://core.telegram.org/bots/api#setchatadministratorcustomtitle
The content format of the command arguments (required and optional) depends on the api command.
See also "available methods" in the api core description.
Command Node
The command node can be used for triggering a message when a specified command is received: e.g. /help. See examples below. Note that commands always start
with a / like /help, /start, /stop. if you have several bots in one group chat implementing the same command e.g. /help you should send commands directly to a
dedicated bot using the full notation /help@YourBot to avoid that different bots would get triggered at once. It it recommended to turn on the strict mode in this case.
Configuration
The node's configuration contains the following special properties:
Outputs
The node has up to two outputs (selectable via the Has response output flag):
1. The node's first/upper output (Standard Output) is used if the message is from an authorized user and it contains a specified command at the beginning of the
message.
2. The node's second/lower output (Unauthorized Output) is used in all other cases. This may be the case when security is applied (via configuration properties
Users and ChatIds) and the user is not authorized to access the bot or if it is from an autorized user and the message does not contain a specified command.
The second output is useful when you want to use a keyboard. See example below.
It is only issued if a command was received before. If another command was triggered in the meantime, the pending status of the first one is reset. The state is stored
per user and per chat.
Event Node
A telegram node that triggers the output when a event is received from a chat.
Callback Query of inline keyboards. See example-flow inline keyboard flow in examples folder.
Inline Query of inline bots. See Inline mode in the bot API.
Edited Message which is triggered when someone alters an already sent message.
Edited Message Text which is triggered when someone alters an already sent message text.
Edited Message Caption which is triggered when someone alters an already sent caption e.g. of a photo.
Channel Post which is triggered when the bot is member of a public channel (/setprivacy to disabled!).
Edited Channel Post which is triggered when someone alters an already sent message in a public channel.
Edited Channel Post Text which is triggered when someone alters an already sent message text in a public channel.
https://flows.nodered.org/node/node-red-contrib-telegrambot 9/19
06/12/2024, 11:55 node-red-contrib-telegrambot (node) - Node-RED
Edited Channel Post Caption which is triggered when someone alters an already sent caption of e.g. a photo in a public channel.
Pre Checkout Query which is triggered when someone issues a payment (see send invoice).
Shipping Query which is triggered when someone issues a shipping.
Chosen Inline Result which is triggered when a user has chosen a result from an inline query.
Poll which is triggered when a poll is created.
Poll Answer which is triggered when a poll is answered.
My Chat Member which is triggered when the status of the bot is changed.
Chat Join Request which is triggered when a chat join request is issued. Note that - Chat Member is deactivated as it requires special rights by the bot and
modifications in polling.
Configuration
The Event to be received is configured via the node's configuration dialog:
The Auto-Answer checkbox can be set for Callback_Query. If activated, you do not need to send an explicit answer to the bot on your own.
Outputs
The output msg.payload typically contains the parsed data as follows:
The output msg.originalMessage contains the raw data object from the underlying library, and contains many useful properties.
Reply Node
A telegram node that is triggered when someone answered to a specified message.
The reply node waits for an answer to a specified message. It should be used in conjunction with the sender node.
Input
Output
This node may be useful, when the bot e.g. sent a message and you want to take some action when someone responded to this specified message. Responding to
messages is done by clicking on the message in your client and choose answer from the popup.
Control Node
This node can be used to stop, start, restart a bot (config node). It send a message to the output after every poll cycle. See the example flow control bot in the
examples folder.
Input
The msg.payload contains:
Output
Standard Output: Contains the msg object passed to the input or a message with poll information:
Keyboards
General
Keyboards can be used to interact with the user by displaying a flexibly definable keyboard. The user then presses one of the keys to give his selection.
Two different keyboard types are available:
Custom Keyboards - These are keyboards which replace the standard keyboard. They are located below the message enter area.
Inline Keyboards - These are keyboards which are inline in the message area.
A remarkable feature of Inline Keyboards is the ability to change them on the fly. See examples section for further details.
With keyboards also complex keyboard procedures with several hierarchy levels can be implemented to direct the user in a step by step button pressing procedure.
Custom keyboards
Examples for Custom keyboards can be seen in the Keyboards section of the telegram bot description.
Custom keyboards act with message nodes and telegram receiver nodes to handle the keyboard procedure, which is as follows:
1. The appearance of the keyboard is initiated via a message sent to the bot. In the message the keyboard configuration is defined within the msg.payload.options
property.
2. The user presses a displayed key.
3. The key text is sent back via a message. This message is received with a receiver node and can then be evaluated.
The keyboard configuration contains the key description, layout and further options. A description of it can be found in the ReplyKeyboardMarkup section.
See also the custom keyboard example.
A basic flow handling a custom keyboard with its reply shows the following figure.
The look&feel at a mobile device could look like the following figure:
https://flows.nodered.org/node/node-red-contrib-telegrambot 11/19
06/12/2024, 11:55 node-red-contrib-telegrambot (node) - Node-RED
The answering options are located below the user text input field.
Several options for the keyboard layout can be found there in the Telegram Bot API SDK description.
The keyboard layout shown in Fig. 12 (given in the create response node) is
keyboard: [
['Yes'],
['No']],
Another example of a different key layout may be to arrange several keys in one line. This may be like:
keyboard: [
['Yes','No','Maybe'],
['Conditional']],
Inline keyboards
Examples for Inline keyboards can be seen in the Inline keyboards section of the telegram bot description.
Inline keyboards act with message nodes and event nodes (event Callback Query) to handle the keyboard procedure, which is as follows:
1. The appearance of the keyboard is initiated via a message sent to the bot. In the message the keyboard configuration is defined within the msg.payload.options
property.
2. The user presses a displayed key.
3. The key text is sent back via an Callback Query event. This message is received with an event node and can then be evaluated.
The keyboard configuration contains the key description, layout and further options. A description of it can be found in the InlineKeyboardMarkup section.
See also the inline keyboard example.
A basic flow handling an inline keyboard with its reply shows the following figure.
The look&feel at a mobile device could look like the following figure:
https://flows.nodered.org/node/node-red-contrib-telegrambot 12/19
06/12/2024, 11:55 node-red-contrib-telegrambot (node) - Node-RED
Several options for the keyboard layout can be found there in the Telegram Bot API SDK description.
The keyboard layout shown in Fig. 15 (given in the inline keyboard message node) is
"inline_keyboard": [[
{"text": "Yes","callback_data": "FOO YES"},
{"text": "No", "callback_data": "FOO NO"}
]]
Another example of a different key layout may be to arrange several keys in one line. This may be like:
"inline_keyboard": [[
{"text": "Yes","callback_data": "FOO YES"},
{"text": "No","callback_data": "FOO NO"}],
[
{"text": "#1","callback_data": "FOO ONE"},
{"text": "#2","callback_data": "FOO TWO"},
{"text": "#3","callback_data": "FOO THREE"}
],
[
{"text": "dog","callback_data": "FOO DOG"},
{"text": "eel","callback_data": "FOO EEL"},
{"text": "cow","callback_data": "FOO COW"},
{"text": "cat","callback_data": "FOO CAT"}
]
]
Examples
Remark: Example flows are present in the examples subdirectory. In Node-RED they can be imported via the import function and then selecting Examples in the
vertical tab menue.
All example flows can also be found in the examples folder of this package.
echo flow
Fig. 18: Simple echo flow
https://flows.nodered.org/node/node-red-contrib-telegrambot 13/19
06/12/2024, 11:55 node-red-contrib-telegrambot (node) - Node-RED
Note: You can access the sender's data via the msg.originalMessage property.
keyboard flow
Fig. 21: Keyboard example
The answer is send to the second output triggering the lower flow. Data is passed via global properties here.
onreplymessage flow
Fig. 22: On reply example flow
The question is sent to the chat. This node triggers the on reply node waiting for the answer.
Note: The user has to explicitly respond to this message. If the user only writes some text, the get reply node will not be triggered.
https://flows.nodered.org/node/node-red-contrib-telegrambot 14/19
06/12/2024, 11:55 node-red-contrib-telegrambot (node) - Node-RED
inlinekeyboard flow
Fig. 23: Inline keyboard example flow
The callback query is received by the event node. It must be answered like shown as follows. There you can add your code to trigger the desired bot command. The
answer contains the callback query data in msg.payload.content.
editinlinekeyboard flow
Fig. 24: Edit an inline keyboard example flow
The message id needs to be saved in the flow or global context (via node save messageId). This is just a demo assuming that there is only one single chat.
As next the initial keyboard has to be replaced with a modified one using the api command editMessageReplyMarkup command as type (via node edit inline
keyboard message).
As an alternative to 'editMessageReplyMarkup you can also use the api command editMessageText to replace the keyboard and also the text as given in the function
example edit message text.
The switch node evaluate callback query just handles the response and hides the keyboard using another api command deleteMessage.
Click to expand code snippet for initial inline keyboard message function
Click to expand code snippet for save messageId function
Click to expand code snippet for edit inline keyboard message function
Click to expand code snippet for evaluate callback query function
Click to expand code snippet for an alternative to node edit inline keyboard message function
The following figure shows the behaviour on a mobile device (e.g. cell phone). The example given above replaces the button description within the node edit inline
keyboard message:
Implementing an inline_query
Bots can be called from any chat via inline_query when the bot is set to inline mode in botfather via /setinline (see https://core.telegram.org/bots/api#inline-mode).
A sample flow is provided in the examples folder and could look like this:
https://flows.nodered.org/node/node-red-contrib-telegrambot 15/19
06/12/2024, 11:55 node-red-contrib-telegrambot (node) - Node-RED
inlinequery flow
Fig. 26: inline_query example flow
Note that the inline_query can also contain the location of the sender. To enable this call /setinlinegeo in botfather.
Receiving a location
Locations can be send to the chat. The bot can receive the longitude and latitude:
receivinglocation flow
Fig. 27: Receiving a location example
sendmessagetochat flow
Fig. 28: Sending messages to a chat example flow
Note: The chatId is already the correct one when you reuse the received msg object from a receiver node.
You can use one of the following types to send your file as content:
photo
audio
video
video_note
sticker
dice
animation
voice
document
Note that some clients convert gif animations to videos. This will lead to problems when passing a received animation object to the sender node as the content is mp4
instead of gif. The content can be downloaded automatically to a local folder by setting the Download Directory property in the receiver node configuration dialog.
You can add a caption to photo, audio, document, video, video_note, animation, voice by setting the caption property as follows:
msg.payload.caption = "You must have a look at this!";
The following types require a special content format to be used. See the underlying node api for further details.
location
contact
venue
https://flows.nodered.org/node/node-red-contrib-telegrambot 16/19
06/12/2024, 11:55 node-red-contrib-telegrambot (node) - Node-RED
mediaGroup
Instead of passing a file name you can also directly pass the buffer of a photo as msg.payload.content. This is useful whenever you download files or already have the
buffer in memory from a previous action. The following example demonstrates how to accomplish this: SendPhotoBuffer
sendmediagroup flow
Fig. 30: Sending media group example flow
Sending contacts
Sending a contact is limited to the elements supported by the underlying API to "phone_number" and "first_name". But you can also receive "last_name" if the client
sends it.
msg.payload.type = 'contact';
msg.payload.content : { phone_number: "+49 110", first_name: "Polizei" };
sendcontacttochat flow
Fig. 31: Sending contact example flow
The display within the telegram app of a sent contact may look like this:
https://flows.nodered.org/node/node-red-contrib-telegrambot 17/19
06/12/2024, 11:55 node-red-contrib-telegrambot (node) - Node-RED
The following example illustrate how to send for example "typing...". Of course a real bot would send the real data after finishing the processing, but this is not part
of the example.
sendchataction flow
Fig. 33: Sending chat actions example flow
Node Info
Version: 16.1.0
Updated 2 months, 3 weeks ago
License: MIT
Rating: 4.6 46
View on npm
View on GitHub
View Scorecard 12
Categories
communication
Actions
Rate:
Downloads
Nodes
telegram bot
telegram receiver
telegram command
telegram event
telegram sender
telegram reply
telegram control
Keywords
node-red
telegram
bot
Maintainers
windkh
If you have a concern about the contents of this module, please let us know. For example, if you believe it contains unsuitable or inappropriate material.
This is not a way to get help with this module. For that, please contact its maintainers directly or post to the Node-RED Forum.
Cancel Report
GitHub
npm
Documentation
APIs
Flow Library
About
Code of Conduct
Community
https://flows.nodered.org/node/node-red-contrib-telegrambot 18/19
06/12/2024, 11:55 node-red-contrib-telegrambot (node) - Node-RED
Blog
Twitter
Forum
Slack
Copyright OpenJS Foundation and Node-RED contributors. All rights reserved. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of
trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation
trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them.
The OpenJS Foundation | Terms of Use | Privacy Policy | OpenJS Foundation Bylaws | Trademark Policy | Trademark List | Cookie Policy | Cookie Settings
https://flows.nodered.org/node/node-red-contrib-telegrambot 19/19