How can i create telegram bot


Connect a Bot Framework bot to Telegram - Bot Service

Twitter LinkedIn Facebook Email

  • Article
  • 2 minutes to read

APPLIES TO: SDK v4

You can configure your bot to communicate with people using the Telegram messaging app. This article describes how create a Telegram bot and connect it to your bot in the Azure portal.

Tip

For information about which features are supported on each channel, see the channels reference article.

Prerequisites

  • An Azure account. If you don't already have one, create a free account before you begin.
  • An existing bot published to Azure.
  • A device with Telegram installed and a Telegram account.

Create a new Telegram bot with BotFather

Create a Telegram bot with BotFather before connecting your bot to Telegram.

  1. Start a new conversation with the BotFather.

  2. Send /newbot to create a new Telegram bot.

  3. When asked, enter a name for the bot.

  4. Give the Telegram bot a unique username. Note that the bot name must end with the word "bot" (case-insensitive).

  5. Copy and save the Telegram bot's access token for later steps.

Configure Telegram in the Azure portal

Now that you have an access token, you can configure your bot in the Azure portal to communicate with Telegram.

  1. Log in to the Azure portal.
  2. Go to your bot. Then select Channels from Settings.
  3. Select Telegram from the list of Available Channels.
  4. Enter the token you copied previously into the Access Token field and select Apply.

Your bot's now successfully configured to communicate with users in Telegram.

For information about using Telegram-specific actions in messages, see how to Implement channel-specific functionality.

Feedback

Submit and view feedback for

This page

View all page feedback

How to Create a Telegram Bot

Chatbots are often touted as a revolution in the way users interact with technology and businesses. They have a fairly simple interface compared with traditional apps, as they only require users to chat, and the chatbots are supposed to understand and do whatever the user demands from them, at least in theory.

Many industries are shifting their customer service to chatbot systems. That’s because of the huge drop in the cost compared to actual humans, and also because of the robustness and constant availability. Chatbots deliver a degree of user support without substantial additional cost.

Today, chatbots are used in many scenarios, ranging from menial tasks such as displaying time and weather data to more complex operations such as rudimentary medical diagnosis and customer communication/support. You can devise a chatbot that will help your customers when they ask certain questions about your product, or you can make a personal assistant chatbot that can handle basic tasks and remind you when it’s time to head to a meeting or the gym.

There are a lot of options when it comes to where you can deploy your chatbot, and one of the most common uses are social media platforms, as most people use them on a regular basis. The same can be said of instant messaging apps, though with some caveats.

Telegram is one of the more popular IM platforms today, as it allows you to store messages on the cloud instead of just your device and it boasts good multi-platform support, as you can have Telegram on Android, iOS, Windows, and just about any other platform that can support the web version. Building a chatbot on Telegram is fairly simple and requires few steps that take very little time to complete. The chatbot can be integrated in Telegram groups and channels, and it also works on its own.

In this tutorial, we will be creating a Telegram bot that gives you an avatar image from Adorable Avatars. Our example will involve building a bot using Flask and deploying it on a free Heroku server.

To complete this tutorial, you will need Python 3 installed on your system as well as Python coding skills. Also, a good understanding of how apps work would be a good addition, but not a must, as we will be going through most of the stuff we present in detail. You also need Git installed on your system.

Of course, the tutorial also requires a Telegram account, which is free. You can sign up here. A Heroku account is required, too, and you can get it for free here.

Bringing Your Telegram Bot to Life

To create a chatbot on Telegram, you need to contact the BotFather, which is essentially a bot used to create other bots.

The command you need is /newbot which leads to the following steps to create your bot:

Your bot should have two attributes: a name and a username. The name will show up for your bot, while the username will be used for mentions and sharing.

After choosing your bot name and username—which must end with “bot”—you will get a message containing your access token, and you’ll obviously need to save your access token and username for later, as you will be needing them.

Code the Chatbot Logic

We will be using Ubuntu in this tutorial. For Windows users, most of the commands here will work without any problems, but should you face any issues with the virtual environment setup, please consult this link. As for Mac users, this tutorial should work just fine.

First, let’s create a virtual environment. It helps isolate your project’s requirements from your global Python environment.

$ python -m venv botenv/ 

Now we will have a botenv/ directory which will contain all the Python libraries we will be using. Go ahead and activate virtualenv using the following command:

$ source botenv/bin/activate 

The libraries we need for our bot are:

  • Flask: A micro web framework built in Python.
  • Python-telegram-bot: A Telegram wrapper in Python.
  • Requests: A popular Python http library.

You can install them in the virtual environment using pip command as follows:

(telebot) $ pip install flask (telebot) $ pip install python-telegram-bot (telebot) $ pip install requests 

Now let’s browse our project directory.

. ├── app.py ├── telebot │ ├── credentials.py │ | . │ | you can build your engine here │ | . │ └── __init__.py └── botenv 

In the credentials.py file we will need three variables:

bot_token = "here goes your access token from BotFather" bot_user_name = "the username you entered" URL = "the heroku app link that we will create later" 

Now let’s go back to our app.py and go through the code step by step:

# import everything from flask import Flask, request import telegram from telebot.credentials import bot_token, bot_user_name,URL 
global bot global TOKEN TOKEN = bot_token bot = telegram.Bot(token=TOKEN) 

Now we have the bot object which will be used for any action we require the bot to perform.

# start the flask app app = Flask(__name__) 

We also need to bind functions to specific routes. In other words, we need to tell Flask what to do when a specific address is called. More detailed info about Flask and routes can be found here.

In our example, the route function responds to a URL which is basically /{token}, and this is the URL Telegram will call to get responses for messages sent to the bot.

@app.route('/{}'.format(TOKEN), methods=['POST']) def respond(): # retrieve the message in JSON and then transform it to Telegram object update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.message.chat.id msg_id = update.message.message_id # Telegram understands UTF-8, so encode text for unicode compatibility text = update.message.text.encode('utf-8').decode() # for debugging purposes only print("got text message :", text) # the first time you chat with the bot AKA the welcoming message if text == "/start": # print the welcoming message bot_welcome = """ Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name. """ # send the welcoming message bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id) else: try: # clear the message we got from any non alphabets text = re. sub(r"\W", "_", text) # create the api link for the avatar based on http://avatars.adorable.io/ url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip()) # reply with a photo to the name the user sent, # note that you can send photos by url and telegram will fetch it for you bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id) except Exception: # if things went wrong bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id) return 'ok' 

The intuitive way to make this function to work is that we will call it every second, so that it checks whether a new message has arrived, but we won’t be doing that. Instead, we will be using Webhook which provides us a way of letting the bot call our server whenever a message is called, so that we don’t need to make our server suffer in a while loop waiting for a message to come.

So, we will make a function that we ourself need to call to activate the Webhook of Telegram, basically telling Telegram to call a specific link when a new message arrives. We will call this function one time only, when we first create the bot. If you change the app link, then you will need to run this function again with the new link you have.

The route here can be anything; you’re the one who will call it:

@app.route('/setwebhook', methods=['GET', 'POST']) def set_webhook(): # we use the bot object to link the bot to our app which live # in the link provided by URL s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN)) # something to let us know things work if s: return "webhook setup ok" else: return "webhook setup failed" 

Now that everything is set, let’s just make a fancy homepage so that we know the engine is up.

@app.route('/') def index(): return '.' if __name__ == '__main__': # note the threaded arg which allow # your app to have more than one thread app. run(threaded=True) 

Let’s take a look at the full version of app.py:

import re from flask import Flask, request import telegram from telebot.credentials import bot_token, bot_user_name,URL global bot global TOKEN TOKEN = bot_token bot = telegram.Bot(token=TOKEN) app = Flask(__name__) @app.route('/{}'.format(TOKEN), methods=['POST']) def respond(): # retrieve the message in JSON and then transform it to Telegram object update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.message.chat.id msg_id = update.message.message_id # Telegram understands UTF-8, so encode text for unicode compatibility text = update.message.text.encode('utf-8').decode() # for debugging purposes only print("got text message :", text) # the first time you chat with the bot AKA the welcoming message if text == "/start": # print the welcoming message bot_welcome = """ Welcome to coolAvatar bot, the bot is using the service from http://avatars. adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name. """ # send the welcoming message bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id) else: try: # clear the message we got from any non alphabets text = re.sub(r"\W", "_", text) # create the api link for the avatar based on http://avatars.adorable.io/ url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip()) # reply with a photo to the name the user sent, # note that you can send photos by url and telegram will fetch it for you bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id) except Exception: # if things went wrong bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id) return 'ok' @app. route('/set_webhook', methods=['GET', 'POST']) def set_webhook(): s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN)) if s: return "webhook setup ok" else: return "webhook setup failed" @app.route('/') def index(): return '.' if __name__ == '__main__': app.run(threaded=True) 

That’s the last bit of code you will write in our tutorial. Now we can progress to the last step, launching our app on Heroku.

Launch Our App on Heroku

We need a couple of things before we make our app.

Heroku can’t know what libraries your project uses, so we have to tell it using the requirements.txt file—a common problem is that you misspell requirements, so be careful—to generate the requirements file using pip:

pip freeze > requirements.txt 

Now you have your requirements file ready to go.

Now you need the Procfile which tells Heroku where our app starts, so create a Procfile file and add the following:

web: gunicorn app:app 

A bounce step: You can add a . gitignore file to your project so that no-use files don’t get uploaded to the repository.

From your Heroku dashboard, create a new app. Once you do, it will direct you to the Deploy page. Then, open the Settings tab in a new window and copy the domain of the app which will be something like https://appname.herokuapp.com/ and paste it in the URL variable inside credentials.py.

Now, go back to the Deploy tab and proceed with the steps:

Note: Windows and macOS users can follow the steps described here.

Log in to Heroku:

$ heroku login 

Please note that this method sometimes gets stuck in waiting for login, if this happens to you, try to log in using:

$ heroku login -i 

Initialize a Git repository in our directory:

$ git init $ heroku git:remote -a {heroku-project-name} 

Deploy the app:

$ git add . $ git commit -m "first commit" $ git push heroku master 

At this point, you will see the building progress in your terminal. If everything went okay, you will see something like this:

remote: -----> Launching... remote: Released v6 remote: https://project-name.herokuapp.com/ deployed to Heroku remote: remote: Verifying deploy... done. 

Now go to the app page (the link of the domain you copied before) and add to the end of the link /setwebhook so that the address will be something like https://appname.herokuapp.com/setwebhook. If you see webhook setup ok, that means you are ready to go!

Now Go Talk to Your Bot

A live version of the bot

Finishing Touches, Tips, and Tricks

Now you have your Telegram bot up and running, 24/7, without any need for your intervention. You can add whatever logic you want to the bot, so, for example, you can make your bot more realistic by adding a “typing” status and sending a photo status as follows:

The next code snippet from the respond() function:

 if text == "/start": # print the welcoming message bot_welcome = """ Welcome to coolAvatar bot, the bot is using the service from http://avatars. adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name. """ # send the welcoming message bot.sendChatAction(chat_id=chat_id, action="typing") sleep(1.5) bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id) else: try: # clear the message we got from any non alphabets text = re.sub(r"\W", "_", text) # create the api link for the avatar based on http://avatars.adorable.io/ url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip()) # reply with a photo to the name the user sent, # note that you can send photos by url and telegram will fetch it for you bot.sendChatAction(chat_id=chat_id, action="upload_photo") sleep(2) bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id) except Exception: # if things went wrong bot. sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id) 

As you can see in the snippet, we added a typing action when we are about to send the information about the bot which is in text format, and added an upload photo action when we are about to send a photo to make the bot more realistic. More actions can be found here.

You can also change the bot image and description from the BotFather channel to make it more friendly.

Many more simple examples of telegram bots can be found on the python-telegram-bot page on GitHub.

You can build upon our bot and make it the next super AI bot—all you need to do is to integrate your logic in the respond() function. For example, your logic can be in a separate module and can be called inside of the respond() function like so:

. ├── app.py ├── telebot │ ├── credentials.py │ ├──ai.py │ | . │ | you can build your engine here │ | . │ └── __init__.py └── botenv 

And inside of ai.py :

def generate_smart_reply(text): # here we can do all our work return "this is a smart reply from the ai!" 

Import it now in the app.py :

import re from time import sleep from flask import Flask, request import telegram From telebot.ai import generate_smart_reply from telebot.credentials import bot_token, bot_user_name,URL 

Then just call it inside of the respond() code.

def respond(): # retrieve the message in JSON and then transform it to Telegram object update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.message.chat.id msg_id = update.message.message_id # Telegram understands UTF-8, so encode text for unicode compatibility text = update.message.text.encode('utf-8').decode() # for debugging purposes only print("got text message :", text) # here call your smart reply message reply = generate_smart_reply(text) bot. sendMessage(chat_id=chat_id, text=reply, reply_to_message_id=msg_id) 

Now you can have your bot work the way you want—go ahead and create the next big thing!

I hope you had fun building your first Telegram bot.

Additional Resources

  • Building a Chatbot using Telegram and Python
  • Setting your Telegram Bot WebHook the easy way
  • Python-telegram-bot Repository
  • Deploying with Git on Heroku
  • Python Telegram Bot documentation

Related: Create a WhatsApp Chatbot, Not an App

How to connect Telegram chatbot | SendPulse

Chatbot is an automated multifunctional assistant that can show information to subscribers and collect information on demand according to pre-prepared scenarios.

Follow the step-by-step instructions to create your first Telegram messenger chatbot or connect an existing one to the SendPulse service for further customization.

nine0002 If you already have a bot, skip the first step and go straight to the second.

How to create a new bot in Telegram

Open the Telegram messenger, log in to your account or create a new one.

Step 1. Enter @BotFather in the search box and select a bot.

The official Telegram bot will have a blue confirmation sign next to the name in the form of a checkmark.

Step 2. Click "Run" to activate the BotFather bot.

In response, you will receive a list of commands for managing bots.

Step 3. Select or type and send the command /newbot .

Step 4. Give the bot a name - clients will see this name when communicating with the bot. And the nickname of the bot - you can use it to find the bot in Telegram. The nickname must be unique, not repeat the existing ones in the database, and end with the word "bot". nine0003

After you select a suitable name, the bot will be created. You will receive a message with a link to the bot t.me/ , recommendations for setting up an avatar, a description of the bot, and a list of commands for setting up the bot.

You will need a token to connect the bot to SendPulse. Copy the value of the token and go to the last point.

Where to find the key for an existing bot

Step 1. Go to the @BotFather bot and enter the command /token .

You will see buttons with created bots.

Step 2. Select the bot you want to connect.

Copy the value of the token.

How to connect a bot to Sendpulse

Go to the Chatbots section of your SendPulse account. If you did not have connected channels before, click on the "Connect Channels" button. nine0003

If you have already connected bots, go to the "Manage Bots" section and click "Add Bot". You can also select "Connect" next to the desired channel.

In the "Telegram" section, enter the access key - the token received in the created bot. Click Connect.

Click the "Subscribe to bot" button. This way you can test every message and thread and send them to yourself before implementation.

nine0002

You will be redirected to the "Telegram" application, click on the "Start" button and you will subscribe to your bot.

After successfully connecting the chatbot, you will receive a welcome chain, the bot will appear in your list of bots, and you can start creating welcome and trigger chains, mass mailings.

Subscribers are not automatically imported. After connecting, you will be able to collect an audience using the subscription widget or by sharing a link to the t.me/ bot directly. You can also manually upload a file with previously collected subscribers. nine0003

Connect Telegram chatbot

Updated: 09. 08.2022

Creating a Telegram chatbot in the constructor

Publication date: 8/15/2022

6 minutes

Reading

Products from this article:

This article will be useful for those who want to create their own bot Telegram on your own without development skills, knowledge of programming languages ​​and complex commands. . To launch, you only need a well-thought-out work script and settings that everyone can handle. nine0003

Why you need a bot in Telegram

It can be used to automate routine business processes. You can even replace a full-fledged website with a telegram channel. A chatbot is useful when you need a convenient source of help information or a semi-automated user support line.

Simple bots in Telegram work with the help of commands: they give several ready-made items to the chat and continue the dialogue depending on the user's choice. But the possibilities are not limited to this. For example, SaluteBot is able to analyze the text in the message, which allows you to have a real conversation. nine0003

How to create a telegram bot

To make a chat bot without programming skills, use the visual constructor in Studio. It's free and easy: the interface contains blocks with messages and buttons, from which you compose the desired scenario.

But in order for the bot to work in Telegram, you need to set up the integration of several systems: Studio, Telegram and Jivo.

Therefore, the step-by-step instruction looks like this:

  1. Creating a bot in Telegram. nine0134
  2. Registration on the Jivo platform.
  3. Jivo integration with Telegram.
  4. Creating a bot in Studio.
  5. Developing a bot script in the Studio constructor.
  6. Bot testing and debugging.

Let's analyze each stage in detail.

Creating a bot in Telegram

You can create your own chat bot in Telegram for free in a few simple steps:

  1. Go to the dialogue with the chat development tool - https://telegram. me/BotFather. nine0134
  2. Press the "Start" button or enter the /start command in the dialog.
  3. Next, enter the /newbot command to make a new bot.
  4. Specify a name - how the chat will be displayed in the contact list.
  5. The last one is the system name: this is what will be the nickname after the @ sign.

The name can be anything: it's not scary if it duplicates the existing ones. But the system name must be unique. If the username is already taken, you will see a prompt: “Sorry, this username is already taken. Please try something different. nine0003

After successful creation, you will receive a token. Save it, you will need it for further integration. If you closed the window and need to find the token again, write the /token command in the dialog.

Registration in Jivo

To develop a chat in Telegram on the Studio platform, you need an account in the Jivo service. When registering, enter your email address and set a password. You can enter any data in the "Site Address" field.

Jivo integration with Telegram

Log in to the Jivo platform, in the side menu open the "Management" section, the "Communication channels" block. nine0003

In the list of services, find Telegram and click the "Add" button, then "Connect Telegram". In the window that opens, enter the token that you received when creating the bot.

If the token is correct, a pop-up message will appear stating that the bot was successfully connected. In the "Notifications" menu, configure where you want to receive all dialogs and which email to send the message to if there are no free operators.

Creating a bot in Studio

In the previous steps, we set up a platform for conversations and a Jivo service to integrate the chat and the constructor. Next, we have to develop a script, that is, a set of commands and logic by which the bot will communicate with users. nine0003

We will create the script in Studio: go through a free registration and log in to your account.

Then follow the instructions:

  1. Click "Create Project" on the main screen.
  2. If you want to order the development of a bot, select "SaluteBot Turnkey" in the list of tools and submit an online application.
  3. If you create a bot yourself, then select "SaluteBot Constructor" in the list of tools. Further we are talking about the independent design of SaluteBot. nine0134
  4. Select a pre-made template or "New Project".
  5. Give it a name and click the "Create Project" button.
  6. Enter a name for the bot.
  7. Select a language.
  8. Select the scenario type.
  9. Click the "Add Jivo account" button and enter the data for authorization in the Jivo service.
  10. Go to your Jivo account to link it to Studio.

Several options are available in the scenario type selection menu:

  • Ready scenario - includes a basic assembly of screens and commands with answers to frequent requests. You can use the script as is or customize it to suit your business logic: add and remove any blocks.
  • Graph is scripting in the constructor.
  • Code - scripting with code, suitable for developers. It is important to remember that in Code you can build a chatbot only for a website, not for instant messengers, so we do not consider this type in this article. nine0134

Let's take a look at the Graph script type: with its help, you can create a diagram of the chatbot in the constructor yourself.

Scenario development

You can start editing the scenario from the basic settings page, which we reviewed in the previous step. In the "Bot script" block, click the button with the "Go to project" tooltip.

The editor will open:

Before you start developing the map, we recommend that you make a list of requests that you want to answer using the bot. Write down what messages the bot should send to user questions, what options for the development of the conversation are possible. This will make it easier to build dialogs and the logic of the bot. nine0003

The script consists of blocks with the following options:

  • Writing a text response. This is the simplest block, when the user should receive a message with a ready-made text in response. The bot's answers can be varied: if you specify several phrases in the block, the answer will be selected randomly.
  • Data request. The user must send data in a certain format in the message. The bot determines if the value is a phone, email, or a number. nine0134
  • Condition check. You can add a branch to the script to build a dialogue based on the customer's response.
  • Translate the dialogue to an employee. When the bot has collected all the necessary information or finds it difficult to answer, it can transfer the dialogue to the operator.
  • Arbitrary code call. Chat data can be stored and processed in third-party systems. Example: the client indicates in the message the order number, which is sent to the CRM system, and then the details of this order are returned to the telegram dialog. Another example is updating the customer's personal data: from the chat, they are transferred to the CRM system. nine0134

If you want to quickly get started with your bot, select a pre-made industry template from the SaluteBot Constructor Project Creation screen. For example, for e-commerce, the template "Receiving and processing online orders" is suitable.

The template includes blocks about choosing a product, making a purchase directly in the telegram channel, clarifying the status of an order, transferring to an operator:

The script can be adapted to your business: edit messages and buttons, add or remove screens and blocks. nine0003

Health check

After setting up the script, click the Save and Collect buttons in the lower right corner.

Wait for the successful build message, and then check if your telegram bot is working. To do this, go to the dialog, click the "Start" button or enter the / start command. Write some message and make sure that the bot responds according to the scheme that you have compiled. If you get incorrect answers or forgot to add some custom situation, adjust the script in the constructor. nine0003

Telegram bots for business

Let's see why online stores, information business, advertising agencies and representatives of other areas need bots.

Infobusiness

Chatbot can take care of all the important steps of working with the user, namely:

  • assistance in creating a profile;
  • advertising and product descriptions;
  • sending free warm-up materials;
  • customer support until the order is placed.

Event industry

Routine tasks can be transferred to the telegram channel:

  • assistance in booking seats for the event;
  • providing information about the address, speakers;
  • display of the current event schedule;
  • feedback collection.

Sales

For the sales department, the bot can do the following:

  • collect customer contacts;
  • determine the primary need in order to transfer to the right consultant; nine0134
  • aggregate basic information about a future transaction;
  • send promotional or informational materials that the customer receives free of charge per contact.

Helpdesk

Here, a chatbot can help reduce the burden on the technical support team. The main thing is to carefully work out the script. The goal is to find routine and recurring requests and transfer them to the first automatic line, which operates around the clock and free of charge. Here's what you can automate:

  • providing information about the order - status, composition, amount;
  • answers to frequently asked questions;
  • changing customer data in a profile or order;
  • submission of standard appeals.

Clinics

Using a bot, medical institutions can manage client records in a telegram channel without the participation of an operator.


Learn more