How to make telegram bot

How to make telegram bot

Bots FAQ

If you are new to Telegram bots, we recommend checking out our Introduction to Bots first.
You may also find the Bot API Manual useful.

Creating Telegram bots is super-easy, but you will need at least some skills at computer programming. In order for a bot to work, set up a bot account with @BotFather, then connect it to your backend server via our API.

Unfortunately, there are no out-of-the-box ways to create a working bot if you are not a developer. But we’re sure you’ll soon find plenty of bots created by other people to play with.

Here are two sample bots, both written in PHP:

Many members of our community are building bots and publishing sources.
We’re collecting them on this page »

Ping us on @BotSupport if you’ve built a bot and would like to share it with others.

The bot API is still pretty young. There are many potential features to consider and implement. We’ll be studying what people do with their bots for a while to see which directions will be most important for the platform.

All bot developers are welcome to share ideas for our Bot API with our @BotSupport account.

1. All bots, regardless of settings, will receive:

2. Bot admins and bots with privacy mode disabled will receive all messages except messages sent by other bots.

3. Bots with privacy mode enabled will receive:

Note that each particular message can only be available to one privacy-enabled bot at a time, i.e., a reply to bot A containing an explicit command for bot B or sent via bot C will only be available to bot A. Replies have the highest priority.

Bots talking to each other could potentially get stuck in unwelcome loops. To avoid this, we decided that bots will not be able to see messages from other bots regardless of mode.

There are currently two ways of getting updates. You can either use long polling or Webhooks. Please note that it’s not possible to get updates via long polling while an outgoing Webhook is set.

The getUpdates method returns the earliest 100 unconfirmed updates. To confirm an update, use the offset parameter when calling getUpdates like this:

All updates with update_id less than or equal to offset will be marked as confirmed on the server and will no longer be returned.

If you’ve set up your webhook successfully, but are not getting any updates, please remember:

Please check out this new WEBHOOK GUIDE to learn all there is to know about webhooks!

Please take a look at this self-signed certificate guide we made just for you. If you’ve read it and still have a question, ping us on botsupport.

If you’d like to make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL you give us, e.g. www.example.com/your_token. Since nobody else knows your bot’s token, you can be pretty sure it’s us.

This is possible if you’re using webhooks. The upside is that you need less requests, the downside — that in this case it’s not possible to know that such a request was successful or get its result.

Whenever you receive a webhook update, you have two options:

1. Issue POST to https://api.telegram.org/bot /method

2. Reply directly and give method as JSON payload in the reply

You may also want to look at our sample HelloBot, it offers a PHP implementation of this.

Use the getFile method. Please note that this will only work with files of up to 20 MB in size.

Bots can currently send files of any type of up to 50 MB in size, so yes, very large files won’t work for now. Sorry. This limit may be changed in the future.

Yes, file_ids can be treated as persistent.

When sending messages inside a particular chat, avoid sending more than one message per second. We may allow short bursts that go over this limit, but eventually you’ll begin receiving 429 errors.

If you’re sending bulk notifications to multiple users, the API will not allow more than 30 messages per second or so. Consider spreading out notifications over large intervals of 8—12 hours for best results.

Also note that your bot will not be able to send more than 20 messages per minute to the same group.

Unfortunately, at this moment we don’t have methods for sending bulk messages, e.g. notifications. We may add something along these lines in the future.

In order to avoid hitting our limits when sending out mass notifications, consider spreading them over longer intervals, e.g. 8-12 hours. The API will not allow bulk notifications to more than

30 users per second, if you go over that, you’ll start getting 429 errors.

If you’ve got questions that are not answered on this page, ping us at @BotSupport in Telegram.
We welcome any suggestions for the Bot Platform and API.

Making (and deploying) an Interactive Telegram Bot in Node.js

This tutorial will go through a straightforward set of steps to get a responsive telegram bot up and running from scratch

How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

I spent a considerable amount of time figuring out how to make a functional telegram bot. I mean sure, the official introduction is good, but theres a lot of stuff about what bots are, and a few scattered instructions about the API, but not enough of structure for a beginner to get up and running quickly.

So, heres how to make a responsive telegram bot in Node.js with the least amount of hassle:

If you want to learn how to make a Telegram bot in Go, you can read my other post

Set up your bot

You don’t need to write any code for this. In fact, you don’t even need your computer! Go to the telegram app on your phone and…

    Search for the “botfather” telegram bot (he’s the one that’ll assist you with creating and managing your bot)

    Type /help to see all possible commands the botfather can handle

    Click on or type /newbot to create a new bot.

    Congratulations! You have created your first bot. You should see a new API token generated for it (for example, in the previous picture, you can see my newly generated token is 777845702:AAFdPS_taJ3pTecEFv2jXkmbQfeOqVZGER ). Now you can search for your newly created bot on telegram :

    Go ahead and start chatting with your bot!

    Well, that’s pretty disappointing. Our bot seems to be stupid, in the sense that it can’t really reply or say anything back. Let’s take care of that by building our bot server which runs on the back end.

    Set up you bot server

    Every time you message a bot, it forwards your message in the form of an API call to a server. This server is what processes and responds to all the messages you send to the bot.

    We are going to go with webhooks for this tutorial. Each webhook is called with an update object. Lets create our server to handle this update.

    We will be creating our server using node.js, but you can use whatever suits you to make your server. Once you have node and npm installed :

    First, initialize your project

    After following the instructions, you will end up with a package.json file.

    Next, install you dependencies by running :

    Make a new file index.js :

    You can run this server on your local machine by running node index.js

    If all goes well, you should see the message “Telegram app listening on port 3000!” printed on your console.

    But, this is not enough. The bot cannot call an API if it is running on your local machine. It needs a public domain name. This means we have to deploy our application.

    Deploy your service

    You can deploy your server any way you want, but I find it really quick and easy to use a service called now.

    Install now on your system :

    Add a start script to your package.json file.

    My original package.json file looks like :

    Add a start script, to get :

    Once you’ve added the script, run the command :

    (remember to run in in the root of your project folder, wherever the package.json file is located)

    If this is your first time using “now”, you will see some instructions for signing in, but after that you should see something like this :

    Great! This means your server is deployed on https://my-telegram-bot-tanvxponxj.now.sh (or whatever link you see instead), and your API would be present on https://my-telegram-bot-tanvxponxj.now.sh/new-message (as defined in index.js )

    Now, all we need to do is let telegram know that our bot has to talk to this url whenever it receives any message. We do this through the telegram API. Enter this in your terminal :

    …and you’re pretty much done! Try chatting with your newly made bot and see what happens!

    Bots: An introduction for developers

    Bots are third-party applications that run inside Telegram. Users can interact with bots by sending them messages, commands and inline requests. You control your bots using HTTPS requests to Telegram’s Bot API.

    Telegram keeps evolving and adding new features, so this document may contain outdated information.
    We expect to finish updating the FAQ, Bot Manuals, and other documents by the end of Summer 2022.

    To name just a few things, you could use bots to:

    Get customized notifications and news. A bot can act as a smart newspaper, sending you relevant content as soon as it’s published.

    Accept payments from Telegram users. A bot can offer paid services or work as a virtual storefront. Read more »
    Demo Shop Bot, Demo Store

    Create custom tools. A bot may provide you with alerts, weather forecasts, translations, formatting or other services.
    Markdown bot, Sticker bot, Vote bot, Like bot

    Build single- and multiplayer games. A bot can offer rich HTML5 experiences, from simple arcades and puzzles to 3D-shooters and real-time strategy games.
    GameBot, Gamee

    Build social services. A bot could connect people looking for conversation partners based on common interests or proximity.

    Do virtually anything else. Except for dishes — bots are terrible at doing the dishes.

    At the core, Telegram Bots are special accounts that do not require an additional phone number to set up. Users can interact with bots in two ways:

    Messages, commands and requests sent by users are passed to the software running on your servers. Our intermediary server handles all encryption and communication with the Telegram API for you. You communicate with this server via a simple HTTPS-interface that offers a simplified version of the Telegram API. We call that interface our Bot API.

    A detailed description of the Bot API is available on this page »

    There’s a… bot for that. Just talk to BotFather (described below) and follow a few simple steps. Once you’ve created a bot and received your authentication token, head down to the Bot API manual to see what you can teach your bot to do.

    You may also like to check out some code examples here »

    Telegram bots are unique in many ways — we offer two kinds of keyboards, additional interfaces for default commands and deep linking as well as text formatting, integrated payments and more.

    Users can interact with your bot via inline queries straight from the text input field in any chat. All they need to do is start a message with your bot’s username and then type a query.

    Having received the query, your bot can return some results. As soon as the user taps one of them, it is sent to the user’s currently opened chat. This way, people can request content from your bot in any of their chats, groups or channels.

    Check out this blog to see a sample inline bot in action. You can also try the @sticker and @music bots to see for yourself.

    We’ve also implemented an easy way for your bot to switch between inline and PM modes.

    You can use bots to accept payments from Telegram users around the world.

    Bots can offer their users HTML5 games to play solo or to compete against each other in groups and one-on-one chats. The platform allows your bot to keep track of high scores for every game played in every chat. Whenever there’s a new leader in the game, other playing members in the chat are notified that they need to step it up.

    Since the underlying technology is HTML5, the games can be anything from simple arcades and puzzles to multiplayer 3D-shooters and real-time strategy games. Our team has created a couple of simple demos for you to try out:

    You can also check out the @gamee bot that has more than 20 games.

    Traditional chat bots can of course be taught to understand human language. But sometimes you want some more formal input from the user — and this is where custom keyboards can become extremely useful.

    Whenever your bot sends a message, it can pass along a special keyboard with predefined reply options (see ReplyKeyboardMarkup). Telegram apps that receive the message will display your keyboard to the user. Tapping any of the buttons will immediately send the respective command. This way you can drastically simplify user interaction with your bot.

    We currently support text and emoji for your buttons. Here are some custom keyboard examples:

    For more technical information on custom keyboards, please consult the Bot API manual (see sendMessage).

    There are times when you’d prefer to do things without sending any messages to the chat. For example, when your user is changing settings or flipping through search results. In such cases you can use Inline Keyboards that are integrated directly into the messages they belong to.

    Unlike with custom reply keyboards, pressing buttons on inline keyboards doesn’t result in messages sent to the chat. Instead, inline keyboards support buttons that work behind the scenes: callback buttons, URL buttons and switch to inline buttons.

    When callback buttons are used, your bot can update its existing messages (or just their keyboards) so that the chat remains tidy. Check out these sample bots to see inline keyboards in action: @music, @vote, @like.

    Commands present a more flexible way to communicate with your bot. The following syntax may be used:

    A command must always start with the ‘/’ symbol and may not be longer than 32 characters. Commands can use latin letters, numbers and underscores. Here are a few examples:

    Messages that start with a slash are always passed to the bot (along with replies to its messages and messages that @mention the bot by username). Telegram apps will:

    If multiple bots are in a group, it is possible to add bot usernames to commands in order to avoid confusion:

    This is done automatically when commands are selected via the list of suggestions. Please remember that your bot needs to be able to process commands that are followed by its username.

    In order to make it easier for users to navigate the bot multiverse, we ask all developers to support a few basic commands. Telegram apps will have interface shortcuts for these commands.

    Users will see a Start button when they first open a conversation with your bot. Help and Settings links will be available in the menu on the bot’s profile page.

    You can use bold, italic or fixed-width text, as well as inline links in your bots’ messages. Telegram clients will render them accordingly.

    Bots are frequently added to groups in order to augment communication between human users, e.g. by providing news, notifications from external services or additional search functionality. This is especially true for work-related groups. Now, when you share a group with a bot, you tend to ask yourself “How can I be sure that the little rascal isn’t selling my chat history to my competitors?” The answer is — privacy mode.

    A bot running in privacy mode will not receive all messages that people send to the group. Instead, it will only receive:

    On one hand, this helps some of us sleep better at night (in our tinfoil nightcaps), on the other — it allows the bot developer to save a lot of resources, since they won’t need to process tens of thousands irrelevant messages each day.

    Privacy mode is enabled by default for all bots, except bots that were added to the group as admins (bot admins always receive all messages). It can be disabled, so that the bot receives all messages like an ordinary user (the bot will need to be re-added to the group for this change to take effect). We only recommend doing this in cases where it is absolutely necessary for your bot to work — users can always see a bot’s current privacy setting in the group members list. In most cases, using the force reply option for the bot’s messages should be more than enough.

    Telegram bots have a deep linking mechanism, that allows for passing additional parameters to the bot on startup. It could be a command that launches the bot — or an authentication token to connect the user’s Telegram account to their account on some external service.

    Following a link with the start parameter will open a one-on-one conversation with the bot, showing a START button in the place of the input field. If the startgroup parameter is used, the user is prompted to select a group to add the bot to. As soon as a user confirms the action (presses the START button in their app or selects a group to add the bot to), your bot will receive a message from that user in this format:

    PAYLOAD stands for the value of the start or startgroup parameter that was passed in the link.

    Some bots need extra data from the user to work properly. For example, knowing the user’s location helps provide more relevant geo-specific results. The user’s phone number can be very useful for integrations with other services, like banks, etc.

    Bots can ask a user for their location and phone number using special buttons. Note that both phone number and location request buttons will only work in private chats.

    When these buttons are pressed, Telegram clients will display a confirmation alert that tells the user what’s about to happen.

    BotFather is the one bot to rule them all. It will help you create new bots and change settings for existing ones.

    Use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authentication token for your new bot.

    The name of your bot is displayed in contact details and elsewhere.

    The Username is a short name, to be used in mentions and t.me links. Usernames are 5-32 characters long and are case insensitive, but may only include Latin characters, numbers, and underscores. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.

    The token is a string along the lines of 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw that is required to authorize the bot and send requests to the Bot API. Keep your token secure and store it safely, it can be used by anyone to control your bot.

    If your existing token is compromised or you lost it for some reason, use the /token command to generate a new one.

    The remaining commands are pretty self-explanatory:

    Edit bots

    Edit settings

    Manage games

    Please note, that it may take a few minutes for changes to take effect.

    Millions choose Telegram for its speed. To stay competitive in this environment, your bot also needs to be responsive. In order to help developers keep their bots in shape, Botfather will send status alerts if it sees something is wrong.

    We will be checking the number of replies and the request/response conversion rate for popular bots (

    300 requests per minute: but don’t write this down as the value may change in the future). If we get abnormally low readings, you will receive a notification from Botfather.

    By default, you will only get one alert per bot per hour. Each alert has the following buttons:

    We will currently notify you about the following issues:

    1.

    Your bot is sending much fewer messages than it did in the previous weeks. This is useful for newsletter-style bots that send out messages without prompts from the users. The larger the value, the more significant the difference.

    2.

    Your bot is not replying to all messages that are being sent to it (the request/response conversion rate for your bot was too low for at least two of the last three 5-minute periods). To provide a good user experience, please respond to all messages that are sent to your bot. Respond to message updates by calling send… methods (e.g. sendMessage).

    3.

    Your bot is not replying to all inline queries that are being sent to it, calculated in the same way as above. Respond to inline_query updates by calling answerInlineQuery.

    4.

    Your bot is not replying to all callback queries that are being sent to it (with or without games), calculated in the same way as above. Respond to callback_query updates by calling answerCallbackQuery.

    Please note that the status alerts feature is still being tested and will be improved in the future.

    That’s it for the introduction. You are now definitely ready to proceed to the BOT API MANUAL.

    If you’ve got any questions, please check out our Bot FAQ »

    How to Build Your First Telegram Bot: A Guide for Absolute Beginners

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    I’ve been obsessed with science fiction since I was a young teen, so coding has always appealed to me. I was fascinated by the idea that it is possible to write a program that behaves randomly — to me, that was already deep in the realms of sci-fi!

    That obsession fueled my first forays into code, and resulted in a ton of fun bots. For example, this one that describes scary-sounding places by combining words at random, and this one that paints PNGs in block colors.

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    It’s nothing fancy. I’m hardly a master programmer, and you don’t have to be either. With a basic grasp of coding and APIs, you can create genuinely useful software for fun and profit. In this tutorial, we’ll look at creating a Telegram bot from scratch.

    A Telegram bot could be used with the Intercom API to provide a way for support agents to reach their customers that use Telegram. It could also include automation that combines helpful resources with live chat, like in the example below from orat.io:

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    Telegram is a great home for customer-facing bots, with over 200,000,000 active monthly users and an annual growth rate of 50%. It’s a platform that your audience might already use, which reduces friction and encourages adoption. Plus, making bots for Telegram is super easy — the easiest bot creation experience I’ve had so far.

    That’s why I decided to write this tutorial — it could be a good entry point for aspiring coders to looking something instantly rewarding (and potentially valuable) by leveraging a popular and functional platform.

    The first bot I made for Telegram used RSS to find Hacker News submissions that match a search query:

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    Have a play around with the bot — it’s live here!

    With the knowledge from this guide and a little further reading, you could make a support chatbot for your company, an RSS feed reader, a control panel for your smart home, or a bot that replies using only Shakespeare quotes. Little programming projects like this are great fun and infinitely extensible. The more you read around and dream up features, the further you can push your bot.

    In this guide, you’ll learn:

    Before starting, you’ll need:

    With that in place, let’s get going.

    Step 1: Download the Telegram app for desktop

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    Telegram is predominantly a mobile app, but for development purposes you’re going to want to have it installed on the same machine you’re using for writing code. This way, you can quickly test it without unlocking your phone every time. And, you’ll be able to copy and paste your Telegram bot’s API key straight into your text editor.

    Time to grab that API key!

    Step 2: Chat with the BotFather to get your API key

    Telegram bot creation is a novel process because much of it is centered around your own interactions with a Telegram bot. That bot is the BotFather. Inside your Telegram desktop app, you need to search his username and start a conversation with him.

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    Compared to the process for building a Twitter bot, a Mastodon bot, or any other kind of bot I’ve experimented with, Telegram makes the initial setup super easy. I guess that proves what a great tool Telegram bots can be!

    After giving the /newbot command, you get to pick a name and username for your bot. The name is what your users will see the bot as in their contacts list, and the username is how they’ll find it. Think of the username like a Twitter handle; it has to be unique, and it’s best if it’s short and memorable.

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    With that done, you’ll be given your bot’s API key. The API key is how Telegram knows the code you write is associated with this particular bot. Every bot has its own API key, and you shouldn’t share it with anyone or they could hijack your bot and have it carry out their evil deeds.

    That concludes our chat with BotFather for now — onto the code!

    Step 3: Setting up the bot’s gems and directory

    This creates two blank files, one for specifying the gems you’ll need and one where the bot’s code will live. The last command opens both of these files in Atom.

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    Click the Gemfile in Atom’s sidebar, and paste the following in:

    This tells Bundler to grab the Ruby interface to the Telegram API from rubygems.org.

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    That’s it for the gem setup, now we’re finally getting onto the code.

    Coding your first Telegram bot

    The actual code that is going to be running constantly on the server is inside bot.rb. It’s empty right now, but here we’re going to link in the Telegram gem we just bundled and create a bot.

    It’s not much code to write. By the time you’re done, this is what you’ll have:

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    In Telegram, this is what the code above does:

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    Let’s look at what each part of the code does and write it as we go.

    (Replace the TOKEN with the API token you copied from BotFather)

    Ruby makes it quite easy to guess what code will do. The three lines above add the Telegram bot functionality to your file and then create a new bot object from the TelegramBot class, authenticated with your token so the program knows where to send the data.

    The next part is one big loop. It looks confusing at first, but it’s easy to pick apart.

    The first line tells the bot to keep listening for commands. And, when it receives a command to pass it to the message variable. The puts line logs the command to your terminal so you can see what’s going on while the bot runs.

    The bot’s response actions are stored in a case statement. The case statement’s input is fed through from the message variable after it’s been cleaned up by the gem’s get_command_for method. The bot’s reply text is set depending on the command stored and then finally sent with send_with before the loop restarts.

    With this setup, you can now find your bot on Telegram and send the /start and /greet commands, and watch it in action.

    To do this, save the changes in Atom and run ruby bot.rb in the terminal. As long as that terminal is open and running, your bot will send responses!

    Customizing your shiny new bot

    The bot you just made is fine, but it’s not very interesting. The basic bits are there, which means you can swap them out and extend them easily.

    The parts to pay attention to when customizing are the when /command/i lines, and the text between the quotes on the reply.txt lines. These are the inputs your bot accepts, and the messages it sends back as responses.

    So, if you wanted to say something different as a response to the /greet command, you’d change the value of reply.text underneath the greet command line ( when /greet/i ). Here’s a variation you could try:

    Here, I’ve created an array with a few different ways to say hello, and then added one to the message at random by using the sample method.

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    Turning your bot into something awesome

    You can add as many commands, responses, and features to your bot as you like. Most of it is imagination, and a lot of Googling as you go. If you want to learn a lot of things that are applicable to this bot, start with Learn Ruby the Hard Way to get to grips with the basics of the language. With a bit of practice and a healthy reliance on StackOverflow, you’ll be able to:

    If you need inspiration, you can read other people’s bot source code, and check a list of Telegram bots — try to figure out how they work and recreate them as practice.

    Running your bot 24/7

    Right now, your bot is running in your terminal on your computer. That’s fine until you need to restart your computer, your wi-fi drops, or your computer goes to sleep. When that happens, it terminates the bot’s process and users won’t get a response from it.

    The process of moving your bot from a development environment (your computer where you used Atom to write the bot) to a production environment (a server) is known as deployment. There are a few options for deploying your bot, but in both cases we’re going to start by uploading the files to Bitbucket. Bitbucket lets you use git, a version control system that helps you to safely make and track changes to your bot’s code. By uploading your bot’s files to Bitbucket, you can use Bitbucket as a way to grab the bot’s files when you’re logged into the host.

    Sign up for Bitbucket and create a new repository.

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    With terminal open and in the same directory as your bot’s source code, type the following:

    Now, follow the instructions shown by Bitbucket after making the new repository. Mine are:

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    After entering those two highlighted commands in my terminal and providing my Bitbucket password when requested, the files are uploaded. With your code living in the cloud, it’s time to pick a way to deploy.

    Deploying with a Raspberry Pi

    Deploying with a cloud server

    You don’t need to own the computer that your bot is running on, you can use the memory and power of someone else’s machine to run the bot remotely. Popular solutions for deploying in the cloud include Amazon Web Services (AWS), DigitalOcean, and Heroku.

    When you sign up for DigitalOcean and create a new droplet, you’ll learn how to connect to the server via SSH and launch the console.

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    From here, it’s the same process as you did on your local machine regardless of the server you’re using. In the end, it’s just a bash terminal. With some kind of server set up, let’s move onto the actual deployment.

    The deployment process

    On a fresh server — whether that’s a Raspberry Pi or a cloud server like Digital Ocean — you’ll need to install Ruby, Bundler, and Git:

    Then make a new directory for your bot, navigate there, and download the files from Bitbucket with the following commands:

    mkdir bots
    cd bots
    git clone https://[email protected]/benjbrandall/telegram-bot.git

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    Remember to replace the URL above (https://benjbran…) with the URL of your bot’s repository on Bitbucket. You’ll find the whole clone command through Bitbucket, so you won’t have to do that bit manually.

    Next, type bundle to install the gem dependencies, and then ruby bot.rb to start the bot running permanently.

    Note: if you’re accessing your server via SSH, you’ll need to run the bot with nohup ruby bot.rb & to make sure the bot doesn’t stop working when the SSH session is terminated. Now you’re free to close the terminal window, safe in the knowledge that your bot is quietly beep booping away in the background. 🤖

    That concludes your first stab at a Telegram bot. Along the way, you learned about the terminal, Ruby, gems, the Telegram API, and how to deploy a bot to a server. Any questions or suggestions? You can message me on Twitter.

    How to make a bot: a guide to your first Python chat bot for Telegram

    Table of contents:

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    Step #0: A little bit of Telegram Bot API theory

    Here’s a a simple question to start our guide: how do you develop Telegram chatbots?

    The answer is very easy: you use HTTP API both for reading the messages sent by users and for messaging back. This calls for using URL which looks like:

    A token is a unique string of characters required to authenticate a bot in the system. It is generated during the bot’s creation and looks like this:

    METHOD_NAME (and this is obvious from its name) is a method, for example, getUpdates, sendMessage, getChat, etc.

    To executie requests, you can use both GET and POST requests. A lot of methods require additional parameters (while using the sendMessage method, for example, it’s necessary to state chat_id and text). The parameters can be passed as a URL query string, application/x-www-form-urlencoded, and application-json (except for uploading of files).

    Another requirement is UTF-8 encoding.

    After sending an API request you will receive a JSON response. For example, if we fetch data with “getMe” method, we’ll receive something like this:

    If ‘ok’ is true, the request was successful and the result will be displayed in the ‘result’ field. If ‘ok’ is false, you will see an error message in the ‘description’ field.

    You can find a list of all Telegram Bot API data types and methods here.

    The next question: how to receive the users’ messages?

    There are two ways to do this.

    You can manually make requests via the getUpdates method. In the response, you will get an array of Update objects. This method acts as long polling technology (you make a request, process the data and then start over again). To avoid reprocessing the same data, it’s recommended to use the offset parameter.

    The second way is to use webhooks. You have to use the setWebhook method only once. After that, Telegram will send all the updates on the specified URL as soon as they arrive.

    The only limitation is that you need HTTPS (however, self-signed certificates are also permitted).

    But how do you choose an optimal method for receiving messages?

    The getUpdates method is best suited if:

    The webhook method is the best choice if:

    In this guide, I will use the getUpdates method.

    Now, how to make a bot program?

    @BotFather is used to create Telegram bots. It also allows a basic configuration (description, profile photo, inline support, etc.).

    There are plenty of libraries that can simplify working with Telegram Bot API. To name a few:

    At their core, all these libraries are HTTP requests wrappers. A great deal of them is written using OOP and reflects all the Telegram Bot API data types in classes.

    In this Telegram bot tutorial, I’m going to create a Python chatbot with the help of pyTelegramBotApi library.

    Step #1: Implement the exchange rates requests

    Let’s write a Python script which is going to implement the logic for specific currency exchange rates requests. We’re going to use PrivatBank API.

    An example of a response:

    Let’s create a pb.ру file and write the following code:

    We have implemented three methods:

    Step #2: Create a Telegram bot using @BotFather

    Contact the @BotFather bot to receive a list of Telegram chat commands.

    Now use the /newbot command and wait for instructions to select a name and username. Upon successfully creating your bot, you’ll receive the following message:

    Let’s configure the bot’s settings. Specify description and about text (/setdescription and /setabouttext commands), profile photo (/setuserpic), turn on inline mode (/setinline), add commands prompts (/setcommands).

    You will need to use two commands: /help and /exchange. Let’s describe them in /setcommands.

    Now when the setup is over, you can proceed to writing the code. Before moving on, I would highly recommend reading about the API and looking into the library documentation to better understand the information below.

    Step #3: Configure and initialize the bot

    Let’s begin with creating a config.py file for configuration purposes:

    Here we have: the bot’s token and the time zone it will operate in (you’ll need this in the future to specify the time for message updating. Telegram API doesn’t allow you to find out a user’s time zone, therefore the update time should be displayed with a time zone prompt).

    Let’s create a bot.py file, import all the necessary libraries, config files and the previously created pb.py. If some of the libraries are absent, install them via pip.

    Let’s create the bot using the pyTelegramBotAPI library. For this purpose, you should pass the token into a constructor:

    Step #4: Write the /start command handler

    Now your Python chat bot is initialized and constantly requests the getUpdates method. The none_stop parameter is responsible for polling to continue even if the API returns an error while executing the method.

    Then it’s possible to call any Telegram Bot API methods from a bot variable.

    Let’s start with writing a /start command handler and add it before the bot.polling(none_stop=True) line:

    As you can see, pyTelegramBotApi uses Python decorators to initialize handlers for various Telegram commands. You can also catch messages using regexp, their content-type and with lambda functions.

    In our case, if commands=[‘start’] condition is true, the start_command function will be called. A message object (deserialized Message type) will be passed into this function. Afterward, you simply execute send_message into the same chat with the specified message.

    Whew, that was easy, wasn’t it?

    Step #5: Create the /help command handler

    Let’s spice up our /help command handler with an inline button linking to your Telegram account. Let’s name the button “Message the developer”.

    As you can see in the example above, I’ve used an additional parameter (reply_markup) for the send_message method. The method received InlineKeyboardMarkup consisting of a single InlineKeyboardButton with the text: “Message the developer” and url=’telegram.me/artiomtb’.

    The above looks like this:

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    Step #6: Add the /exchange command handler

    The /exchange command handler displays a currency choice menu and inline bot keyboard consisting of 3 buttons: USD, EUR, and RUR (these are the currencies supported by the banking API).

    Let me explain what callback-data in InlineKeyboardButton is. When a user clicks this button you’ll receive CallbackQuery (its data parameter will contain callback-data) in getUpdates. In such a way, you will know exactly which button a user has pressed and handle it as appropriate.

    BTW, this is how the /exchange response looks like:

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    Step #7: Write an inline button click handler

    pyTelegramBotAPI offers using the @bot.callback_query_handler decorator which will pass the CallbackQuery object into a nested function.

    Let’s implement the get_ex_callback method:

    The answer_callback_query method is required to remove the loading state, which appears upon clicking the button. Let’s send a message into send_exchange_query. You’ll have to pass it the Message and the currency code (you can get it from query.data. If it was, for example, get-USD, then pass USD).

    Let’s implement send_exchange_result:

    This is also pretty straightforward.

    Let’s first send the typing state into the chat, so that the bot will display the “typing” indicator while the banking API receives a request. Now let’s call the get_exchange method from a pb.py file, which will receive the currency code (e.g. USD). You’ll also have to call two new methods into send_message: serialize_ex, a currency serializer, and get_update_keyboard (which returns the keyboard to “Update” and “Share” buttons).

    Let’s write in get_update_keyboard the current exchange rates in callback_data using JSON format. JSON is intentionally compressed because the maximum allowed file size is 64 bytes.

    t key means type and e key means exchange. The rest is done using the same principle.

    The “Share” button will have the switch_inline_query parameter. Pressing the button will prompt the user to select one of their chats, open that chat and insert the bot‘s username and the specified inline query in the input field.

    Next, let’s present the serialize_ex method and auxiliary serialize_exchange_diff required to show the difference between the current and the old exchange rates upon clicking the “Update” button.

    This is how the bot’s answer looks like upon clicking USD button:

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    Step # 8: Implement the update button handler

    Now you’re ready to implement the “Update” button handler. After complementing the iq_callback method it will look as follows:

    If callback-data begins with get-’ (get-USD, get-EUR and so on) then let’s call get_ex_callback as we did before. Otherwise let’s try to parse JSON and receive its t key. If it equals ‘u’ then call the edit_message_callback method. Let’s implement it:

    How does it work?

    The get_ex_from_iq_data method parses JSON from callback_data:

    get_edited_signature generates “updated …” text:

    This is how the message looks like upon updating if the exchange rates haven’t changed:

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    And this is how it looks when the exchange rates have changed:

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    Step #9: Implement the inline mode

    Implementing inline means that writing @ + bot’s name in any chat will activate the search for the entered text and offer the results. By clicking one of them the bot will send the result on your behalf (marked “via bot”).

    Voila, you have implemented the inline query handler.

    The library will pass the InlineQuery object into the query_text function. Inside you use the answer_inline_query function which should receive inline_query_id and an array of objects (the search results).

    Let’s use get_exchanges from pb.py to search for several currencies that suit the search query. Let’s pass this array into the get_iq_articles method which will return the array from InlineQueryResultArticle:

    Now when you enter @exchnagetestbot + space in any chat you’ll see the following:

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    Let’s type usd and the result will be instantly filtered:

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    Let’s click the offered result:

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    The “Update” button is also operational:

    How to make telegram bot. Смотреть фото How to make telegram bot. Смотреть картинку How to make telegram bot. Картинка про How to make telegram bot. Фото How to make telegram bot

    Good job! You’ve successfully implemented the inline mode!

    Wrapping up

    Hit the subscribe button below to get more tech news or message us directly if you need some help with your business bot.

    Источники информации:

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *