Create a serverless chat demo with Telegram (2023)

    Create a serverless chat demo with Telegram (1)Doorhao wang 27-07-2023

    Gore Facebook LinkedIn

    Create a serverless chat demo with Telegram (2)

    Twilio conversationsis an omnichannel messaging platform that allows you to create engaging conversational experiences across multiple channels, including chat, SMS, WhatsApp, and Facebook Messenger. But what if you want to add another channel, like Telegram?

    Conversational webhooksprovide a way to associate a unique screen, bot, or other integration with each conversation. This can be used to add a Telegram bot to Conversations.

    This hereFast start conversationscreate a demo application that provides a simple Javascript based chat UI usingCodeSandbox.io. In this demo, we add and use a Telegram bot to the conversationTwilio Featuresfor the implementation of the back-end logic.

    General description

    This blog post provides a step-by-step guide to creating a serverless chat demo with Telegram and ChatUI, using Twilio functions to implement the back-end logic. The guide walks you through integrating a Telegram bot into the conversation, adding another participant via ChatUI, and setting up a scoped webhook to process Telegram messages. The document includes a high-level diagram and flow, along with code snippets for each step in the process. In addition, the publication provides the prerequisites and configuration needed to run the features.

    previous requirements

    • A Twilio account (if you don't have one,You can register here for free)
    • A Telegram account
    • learn and startTwilio Features
    • get used to itFast start conversationsand have the Conversations demo app ready with CodeSandbox.io

    High-level diagram and step-by-step configuration

    The high-level diagram and flow are shown in the following image. Illustrates how messages are sent and received between Twilio, Telegram, and Conversation Demo conversations (chat UI). Let's start!

    Create a serverless chat demo with Telegram (3)

    Step 0: Sign up for the Telegram callback

    To start,create a Telegram bot. Install the Telegram Messenger app on your device and then search forBotVader.

    BotFather is a bot that allows you to create new bot accounts and manage your existing bots. Use it to create a new bot and choose a username for it by sending commands to BotFather. You should see the conversation and commands with BotFather as shown below, but you can start the prompt with/To startand BotFather will guide you.

    Create a serverless chat demo with Telegram (4)

    After the Telegram bot is created and the token is acquired, an HTTP Post request is required to set up the callback for new Telegram messages. This is realized in/in thatfunction to be executed once to set the callback. Alternatively, you can use curl to perform the same task.

    navigate toTwilio Features Sectionin the console and create a new service. After a service is created, create a function called/in thatand replace the existing code in the Function Editor with the following:

    // This is your new function. To get started, specify the name and path on the left. const axios = require('axios'); exports.handler = async(context, event, callback) => { console.log("Configuring Telegram webhook..."); let {data} = wait axios.get(`https://api.telegram.org/bot${context.TELEGRAM_API_TOKEN}/setWebhook?url=${context.WEBHOOK_BASE_URL}/receive-message&allowed_updates=["message"]` ); console.log("telegram", data); // This callback is what is returned in response to the call to this function. // This is very important! E.g. you can reply with TWiML here for a voice or text reply. // Or you can return JSON data to a study stream. I have not forgotten! callback(null, data); };

    Step 1: Telegram sends a callback message

    Telegram sends HTTP Post to the webhook registered in step 0 for every message sent to the bot.

    Step 2: Handle the incoming Telegram message

    This function is a webhook that handles incoming Telegram messages. Several tasks are performed here:

    1. Find the existing conversation and join the Telegram chat ID.
    2. If they don't exist, a new conversation and participant identity are created.
    3. The message is forwarded to the conversation.
    4. The big chat webhook is configured to handle outgoing messages to Telegram. The chat ID is used as a parameter to compile the webhook address, ensuring consistency in Telegram.

    Below is the code of the function. To use it, you need to create a new function in your function service called/receive messagesand replace the existing code with the following.

    /receipt message

    // This is your new function. To begin with, specify the name and path on the left. exports.handler = async(context, event, callback) => { // msg from telegram const chatId = event.message.chat.id; const body = event.message.text; console.log('telegram message', chatId, body); // start twilio client const client = require('twilio') (context.TWILIO_ACCOUNT_SID, context.TWILIO_AUTH_TOKEN); let identity = `telegram_user_${chatId}`; console.log('identity', identity); // check if a conversation exists with the identity drop conversations = wait client.conversations.participantConversations.list({identity:identity}); let existing = conversations.find(conversation => conversation.ConversationStatus !== 'closed'); console.log("Existing: ", existing); let existingConversationSid = existing! == undefined? existence.conversationSid: undefined; // if it didn't exist then create a new conversation and join, also create a webhook to process the message sent to Telegram using the chatId of the incoming message if (existingConversationSid === undefined) { console .log('existingConversationSid' , 'undetermined'); // create chat const { sid: chatSid } = wait for customer.chats.chats.create({ friendlyName: `Telegram_conversation_${chatId}` }); //create participant wait client.conversations.conversations(conversationSid).participants.create({identity:identity}); // create a webhook to handle messages to Telegram wait for client.conversations.conversations(conversationSid) .webhooks .create(target: 'webhook', 'configuration.filters': 'onMessageAdded', 'configuration.method': ' POST', 'configuration.url': `${process.env.WEBHOOK_BASE_URL}/new-message?chat_id=${chatId}`, })existentConversationSid = conversationSid; } console.log('existingConversationSid', existingConversationSid); // forward telegram messages to conversations by creating message waiting client.conversations.conversations(existingConversationSid).messages.create({ author: identity, body: body, xTwilioWebhookEnabled: true }); // This callback is what is returned in response to the call to this function. // This is very important! E.g. you can reply with TWiML here for a voice or text reply. // Or you can return JSON data to a study stream. I have not forgotten! callback(null, event); };

    Step 3: Set up the Chat UI and add it to the conversation

    It's time to add another chat participant to talk to your Telegram participant. we recycleconversation application examplevanFast start conversations, follow the instructions to set it up.

    Once the chat demo is running, find the SID of the chat in step 2 and add the chat participant with the following command. You can see more details inAdd a chat participant. vanTWILIO_ACCOUNT_SIDjTWILIO_AUTH_TOKENcan be found in the Twilio console.

    rizo -X POST "" \\--data-urlencode "Identity=testPineapple" \\-u $TWILIO_ACCOUNT_SIDE:$TWILIO_AUTH_TOKEN

    Step 4 and 5: The conversation sends messages to the ChatUI and vice versa

    In a conversation, messages are automatically sent to all participants. This means that everyone in the conversation receives the message at the same time. When a participant responds to a message, that response is also sent to the entire conversation. This ensures that everyone is kept up to date with all messages and replies, ensuring a smooth and efficient communication process. This feature also helps avoid confusion or misunderstandings that can occur when messages are only sent to certain participants, as everyone can see the entire conversation and all replies.

    Step 6: The conversation sends messages to the scoped webhook

    In step 2, the scoped webhook is registered withonMessage added. Therefore, each new message in the conversation triggers an HTTP POST to the webhook.

    Step 7: The scoped webhook sends a message to Telegram

    He/New messageThe feature plays an important role in integrating a Telegram bot into Twilio conversations. Check the HTTP POST of the conversation to determine the origin of the message. if the source isSDK, send the message to Telegram via HTTP POST. This feature is essential for smooth communication between the conversation participants and the Telegram bot.

    The code for this function is easy to understand. It uses the Axios library to send an HTTP POST request to the Telegram API. The request contains the chat ID and the body of the message. If the source of the message is not "SDK", the function will not execute any code.

    Below is the code of the function.New message.

    // This is your new function. To get started, enter the name and path on the left. exports.handler = async(context, event, callback) => { console.log('new message for Telegram', event.Body, event.Source); const axios = require('axios'); if (event.Source === 'SDK') { expected axios.post(`https://api.telegram.org/bot${context.TELEGRAM_API_TOKEN}/sendMessage`, { chat_id: event.chat_id, text: event .Body }) } // This callback is what is returned in response to calling this function. // This is very important! E.g. you can reply with TWiML here for a voice or text reply. // Or you can return JSON data to a study stream. I have not forgotten! callback(null, event); };

    Configure features in the Twilio console

    After you complete all the steps mentioned above, you will see 3 features on your Twilio console. These features are essential to the overall functionality of your Twilio application and must be configured correctly for your application to function properly. To run these functions correctly, it is important to make sure that all variables and dependencies are set correctly. Taking the time to double check these settings can save you a lot of time and frustration in the long run and ensure that your Twilio application runs smoothly and efficiently.

    Create a serverless chat demo with Telegram (5)

    • TWILIO_ACCOUNT_SID – The Twilio account SID is a 34-character alphanumeric identifier that begins with the letters "AC" and can be found on the dashboard when you log into the Twilio console. See thishelp pagefor more details.
    • TWILIO_AUTH_TOKEN - The authentication token acts as a password to access the Twilio API; you can use thisguideto find it.
    • WEBHOOK_BASE_URL - This is the endpoint of the Twilio function used as a webhook to receive messages from the conversation. For this guide, yestelegram2conversaciones-4852.twil.io, you can find the URL in the Twilio Functions console.
    • TELEGRAM_API_TOKEN – The Telegram token you received from BotFather in step 0.

    Create a serverless chat demo with Telegram (6)

    Test Telegram-bot

    Finally, after setting up the Telegram Bot, you can start sending messages. The bot receives your messages and forwards them to the chat demo you created earlier. Likewise, all messages sent from the chat demo are routed to the bot. This seamless integration between the bot and the chat demo enables direct communication between users and the bot. To get a better idea of ​​how this works, see the screenshots below that illustrate how the messages are presented.

    Create a serverless chat demo with Telegram (7)

    Create a serverless chat demo with Telegram (8)

    Conclusion

    This guide provides a step-by-step process on how to create a serverless chat demo with Telegram and ChatUI using Twilio features. By following the instructions in this document, you can seamlessly integrate a Telegram bot into your Twilio conversations and enable smooth and efficient communication between participants. With the right tools and resources, you can create compelling conversational messaging experiences that span multiple channels and meet the needs of your audience.

    Hao Wang is a Principal Solutions Engineer at Twilio helping customers get the most out of Twilio products. He can be reached at hwang0 [at]twilio. withOLinkedIn.

    Rate this article

    Auteurs

    • Create a serverless chat demo with Telegram (9) hao wang

    proofreaders

    • Create a serverless chat demo with Telegram (10) Dhruv Patel
    • Create a serverless chat demo with Telegram (11) Paul fight

FAQs

How to create a Telegram Bot that replies? ›

Open Telegram messenger, sign in to your account or create a new one.
  1. Enter @Botfather in the search tab and choose this bot.
  2. Choose or type the /newbot command and send it.
  3. Choose a name for your bot — your subscribers will see it in the conversation. ...
  4. Go to the @BotFather bot and send the command /token .
Feb 3, 2023

How to create a Telegram chatbot using Python? ›

To automate Telegram using Python, you can use the python-telegram-bot library. Install it using pip, create a bot on Telegram using BotFather, and obtain the bot token. Use the library's API to interact with Telegram, send and receive messages, and perform actions.

How can I create automated messages in Telegram? ›

Here's how:
  1. Go to Trengo's settings → automation → auto-replies.
  2. Click on the green + sign.
  3. Select Telegram as a channel.
  4. Decide when the auto-reply should be triggered. You can choose between the following instances: During business hours. Outside of business hours. ...
  5. Write your auto-reply message.
  6. Click 'Save'.

Is making a Telegram bot easy? ›

BotFather is a bot created by Telegram to make bot creation a breeze. With BotFather, you can create your very own bot by following a few simple steps. You can customize your bot's name, profile picture, description, and even add custom commands to make it do exactly what you want it to do.

How do you make a chat box? ›

Building the Chat Interface using HTML and CSS
  1. Creating the basic structure using HTML. ...
  2. Adding the basic CSS.
  3. Creating the Message Header Section. ...
  4. Creating the Chat Box and Message Page. ...
  5. Creating the Message-Bottom Section. ...
  6. Adding the Incoming Messages. ...
  7. Adding the Outgoing Messages. ...
  8. Adding a few more messages.

How to create Telegram chatbot for free? ›

Go to Telegram, search for Botfather, start a chat and click on Start at the bottom. So, now you need to say “/newbot” to create your chatbot. NOTE: Don't share this API token with anyone else besides yourself! And that's it!

What programming languages does Telegram bot use? ›

  • HTML.
  • Java.
  • Python.
  • C.
Jan 30, 2022

How to make a Telegram bot using API? ›

Getting Ready
  1. Obtain Your Bot Token. In this context, a token is a string that authenticates your bot (not your account) on the bot API. ...
  2. Download an IDE. ...
  3. Pick a Framework or Library. ...
  4. Create Your Project. ...
  5. Add Framework Dependency. ...
  6. Creating a Bot Class. ...
  7. Available Methods. ...
  8. Registering the Bot.

Is hosting Telegram bot free? ›

The platform also has a free tier that allows you to host a Telegram bot, and is fairly priced should you exceed its limits.

How to create a bot using Python? ›

ChatterBot: Build a Chatbot With Python
  1. Demo.
  2. Project Overview.
  3. Prerequisites.
  4. Step 1: Create a Chatbot Using Python ChatterBot.
  5. Step 2: Begin Training Your Chatbot.
  6. Step 3: Export a WhatsApp Chat.
  7. Step 4: Clean Your Chat Export.
  8. Step 5: Train Your Chatbot on Custom Data and Start Chatting.
Oct 12, 2022

How to create a Telegram Assistant bot? ›

Create a Telegram bot
  1. Search for the official bot builder — @BotFather.
  2. Run the command /new - to create a new bot.
  3. Give the new bot a name — this is a display name, you can think of any, whatever you like.
  4. Define the username of the bot, at the end of the name must be the word bot.
Mar 4, 2023

How to create a bot on Telegram and teach it to respond to specific terms? ›

In order to create a Telegram Bot, follow these steps:
  1. Contact the user @BotFather on Telegram and start a chat. ...
  2. Write /newbot to @BotFather and choose a friendly bot name. ...
  3. Specify the bot username. ...
  4. Copy this token and navigate to the plugin: Admin Dashboard → CM Telegram Bot → Settings → API Settings tab.
Jun 29, 2023

How to make an interactive Telegram bot? ›

Go to Telegram, search for Botfather, start a chat and click on Start at the bottom. So, now you need to say “/newbot” to create your chatbot. NOTE: Don't share this API token with anyone else besides yourself! And that's it!

Can Telegram bots send messages? ›

Armed with the token and the chat ID, you can engage the Telegram API to send messages with your new bot!

Can a telegram bot start a conversation? ›

Telegram Bots can't initiate a conversation with a user.

There is no way to around this. In your case, you can ask the user to start the bot before asking questions in the channel, for example by attaching a button containing the bot URL (https://t.me/bot_username).

References

Top Articles
Latest Posts
Article information

Author: Kelle Weber

Last Updated: 09/12/2023

Views: 5930

Rating: 4.2 / 5 (53 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Kelle Weber

Birthday: 2000-08-05

Address: 6796 Juan Square, Markfort, MN 58988

Phone: +8215934114615

Job: Hospitality Director

Hobby: tabletop games, Foreign language learning, Leather crafting, Horseback riding, Swimming, Knapping, Handball

Introduction: My name is Kelle Weber, I am a magnificent, enchanting, fair, joyous, light, determined, joyous person who loves writing and wants to share my knowledge and understanding with you.