Developing Secure Bots Using The Telegram APIs J Simpson May 30, 2019 Telegram is an alternative messaging network that privileges privacy and security. It’s also a flexible platform, enabling developers to build chat bot applications using the Telegram Bot API. Telegram bots are a popular choice for chatbot-related applications. This popularity has raised some concern, as Telegram bots have been discovered not to be that secure. For this tutorial, we’re going to learn how to utilize the Telegram Bot API to program a Telegram bot. Then we’ll take a look at securing that bot, so your messaging is sure to remain secure. How To Program Secure Telegram Bots First off, let’s define what a Telegram bot is, in case you’re new to the popular messaging API. What Is A Telegram Bot? A Telegram bot is any third-party application that runs inside the Telegram environment, an alternative messaging platform that privileges privacy and security. Telegram bots connect to the users using text messaging and in-line button callbacks, which are usually encoded in JSON. Bot apps can be anything from a search engine to a multimedia library to a simple conversation app. Telegram bots don’t require additional installation, running on any platform that supports Telegram. Operating Systems That Support Telegram Windows iOS Linux Android Telegram Bot Applications Telegram bots are almost endlessly open-ended. They’re just simple programs that run in the Telegram environment. Telegram offers some examples of some common Telegram bot applications, however, to help developers get started with the Telegram API. Some typical Telegram bot applications include: Customized notifications and news: Telegram bots can be useful for creating customized publications Interacting with other applications: Telegram bots can integrate with other favorite apps like Gmail, IMDB, Wiki, YouTube, or GitHub, among others Accept payments: Telegram bots can offer paid services or accept payments, acting as a kind of virtual storefront Create customized tools: Telegram bots can be used to create weather alerts, translations, or custom alerts Single or Multiplayer Games: Telegram bots can take advantage of HTML5’s rich features to build simple arcade games, puzzles, real-time strategy games, or first-person shooters, for example Social programs: Telegram bots can be used to find conversation partners based on location or shared interests, for example Now that we’ve seen what Telegram bots can do let’s learn how to build a Telegram bot. Then we’ll look at what it takes to make that bot secure. How To Build Your First Telegram Bot Due to some recent security concerns around Telegram, you might be wondering, “Why should I use the Telegram API?” First and foremost, Telegram is still one of the most popular APIs out there. There are over 200,000,000 active monthly users, with a 50% annual growth rate. Due to Telegram’s popularity, there’s plenty of help and documentation should you run into any problems. It’s also incredibly easy to create bots using Telegram, making it an excellent choice for developers who are new to using APIs. We’re going to learn how to build a Telegram bot from scratch. Then we’ll look at how to add additional commands, as well as some of the programming languages that are commonly used for creating bots using the Telegram API. Once we’ve set up our first Telegram bot, we’ll learn how to make it secure so that you can use your bot with a clear conscience. To start, you’re going to need: A Bash terminal: MacOS and Linux usually come with a built-in Bash terminal. Windows users might have to install one, however. If you’re using a Windows machine that hasn’t had the Windows 10 Anniversary Update, you can use a Windows emulator or create a virtual Linux machine](https://www.labnol.org/software/run-linux-with-windows/19746/). Ruby: Check the Ruby documentation to see which specific version of Ruby you’ll need for your OS. Homebrew is a popular choice for Mac users. Windows users can use this Ruby Installer Bundler: A bundler helps manage Ruby gems, which add additional functionality to your apps. Bundler helps create an interface for the Telegram API for your bot. Once you’ve installed Ruby, run gem install bundler using the terminal A text editor: You can use commonplace text editors like Notepad or Text Edit. Text editors like Atom are specifically built to catch syntax errors in code, however, which makes it slightly preferable for programming purposes. Now that we’re set up let’s dive in and start building our first Telegram bot! Step 1: Download The Telegram App For Desktop Telegram is mainly known as a mobile app. You’ll want to install the Telegram Desktop app, however, for a fluid workflow. Otherwise, you’d have to unlock your phone every time you need to check your code. Step 2: Chat With The BotFather To Get Your API Key Receiving your Telegram API is a particularly meta experience. You’ll need to chat with a Telegram bot to receive your API key. This is known as the BotFather. First, you need to search for the username ‘Botfather’ in your Desktop app and start a conversation with him. To start a conversation with the Botfather, type /start. You’ll see a list of commands to help you create, manage, and edit bots. Since we’re building our first Telegram bot, you’ll want /newbot. This is part of what makes Telegram such an accessible API for creating new bots. Most other APIs require quite a bit more implementation to get up and to run. The Telegram API is about as close to plug-and-play as developers are likely to find while remaining powerful and versatile. After you’ve created your bot, you’ll need to give it a name and username. This is the name users will see in their chat client. It’s best when it’s short and memorable, the same as any other handle. After you’ve created your bot’s username and handle, you’ll be given your API key. This is how Telegram keeps track of code written for a particular bot. Think of it as a fingerprint for your bot. Now that you’re set up and running let’s start writing our first code! Step 3: Setting Up Your Bot’s Gems and Directory Start by opening terminal. Then type the command mkdir telegram-bot. This creates the directory where your bot’s files will be stored. Open the directory using the command cd telegram-bot. Once you’re there, type the following. touch Gemfile touch bot.rb atom .touch Gemfile touch bot.rb atom . This creates two blank files. One specifies the gems needed for your bot. The other specifies where your bot’s code will be stored. The final code opens both in Atom. In Atom, open the Gemfile in the sidebar, then paste the following. source 'https://rubygems.org' gem 'telegram_bot' This lets Bundler know to fetch the Telegram API interface from rubygems.org. To finalize the gem setup, go back to your terminal and type bundle. This will show you the contents of your bundle. Now we’re all set up and ready to start writing our first code. Step 4: Writing Your First Code In Telegram The code you’ll be writing will be running continuously inside bot.rb. It’s empty at first, so you’ll start by linking to the Telegram gem you just created. It looks a little something like this. Require 'telegram_bot' Token = 'Your_Api_key' Bot = TelegramBot.new{token: token} Bot.get_updates{fail_silently: true} do [message] Puts "@#"message.from.username": #{message.txt}" Command = message.get_command_for(bot) message.reply do [reply] case command when /start/i reply.text = "All I can do is say hello. Try the /greet command." when /greet/i reply.text = "Hello, #[message.from.first_name}. else reply.text = "I have no idea what #{command.inspect} means." end End Now your bot is up and running. What it can do is relatively limited, however. Now let’s flesh our bot out a little bit. Step 5: Customizing Your Bot Now your bot should be up and running. It can’t do very much, though. Luckily, all the pieces are in place to flesh out what your bot is capable of. To start, look at the when command/i commands and the text between the reply.txt lines. These are your inputs, as well as what your bot returns. If you want your bot to say something different in the greeting, change the text of the reply.txt beneath the /greet command. One possible alternative might be: when /greet/i greetings = ['bonjour', 'hola', 'hallo', 'sveiki', 'namaste', 'salaam', 'szia', 'halo', 'ciao'] reply.text = "#{greetings.sample.capitalize}, #{message.from.first_name}!" You might consider adding different variations on the greeting, for instance, or adding some kind of randomized texts to make your bot more interesting. Step 6: Making Your Bot Amazing Now that we’ve learned how to customize your bot, it’s time to make it actually start doing stuff. Start off by thinking about what you’d like your bot to do. Once you’ve dreamed up what you’d like your bot to be capable of, you’ll start hitting the search engines and StackOverflow for guidance on how to implement these tasks. Some possible actions for your bot might include: Calling additional APIs: Integrating additional APIs you might integrate into your Telegram bot are when things truly begin to get interesting. Twitter, Slack, Airtable, or RSS all make it possible for your Telegram bot to interface with external apps. Store user information in a database: Being able to store data makes your Telegram bot even more useful. One potential application of this might be if users interact with your website during off-hours. You might add their email address to a database to interact with them during business hours. The Sequel gem makes creating and interacting with databases a snap in Telegram Create a text adventure: Telegram bots can easily make simple games such as text adventures. Some of the earliest text-based adventure games have already been reimagined as Telegram bots. Step 7: Getting Your Bot Online Now that your bot can do things, it’s time to get it off of your system and out into the world! Moving your bot from the text editor to a server is called ‘deployment.’ There are a lot of different ways you can get your bot on a server. We’re going to use one called Bitbucket. Bitbucket allows you to use git, which allows you to make and track changes Uploading your bot’s files into Bitbucket lets you access them when you’re logged into the host. To start, log into Bitbucket and create a new repository. Open terminal while in the same directory as your bot’s source code. Then type the following: git init git add . git commit -m 'initial commit' Next, follow the instructions on Bitbucket. You’re going to connect your existing repository. Now you’ve only got to type your Bitbucket password and Presto! Your code’s now online. Step 8: Choose Deployment Method There’s a wide array of different approaches to deploying your Telegram bot. Let’s look at a couple of the most common to determine which deployment method will be best for your specific needs. Raspberry Pi A raspberry pi is a cheap, easy way to get your Telegram bot up and running. They can cost as little as $7 plus the cost of an SD card. They don’t use much power, so running it 24/7 won’t break the bank. While there are Raspberry pi bundles that will try and sell you a keyboard, mouse, and case, you only need a USB charger, SD card, ethernet cable, and a computer to interact with it. Cloud-based Server It’s no longer necessary to have a physical server to run a bot. Cloud-based servers are omnipresent, and most will be powerful enough to host a Telegram bot. Popular Cloud-Based Servers Include: Amazon Web Services (AWS) Digital Ocean Heroku Heroku and DigitalOcean are particularly quick and easy to get up and running. Now that you’ve settled on how you’re going to host your Telegram bot let’s look at how to make that happen. Step 9: Deploy Your Bot You’re going to need to install Ruby, Bundler, and Git wherever you’re running your server. You’re going to type: sudo apt-get update sudo apt-get upgrade curl -L https://get.rvm.io | bash -s stable --ruby sudo apt-get install bundler sudo apt-get install git Now you’re going to make a new directory to store your bot’s files and then download the files from Bitbucket using the following commands: mkdir bots cd bots git clone https://benjbrandall@bitbucket.org/benjbrandall/telegram-bot.git Now you’re going to install the gem dependencies by typing bundle. Then type nohup ruby bot.rb & and your bot should be ready to run around the clock, even after the SSH session has been terminated. Congratulations! You’ve made your first Telegram bot. Now let’s take one last look at how to make sure your Telegram bot is secure. Securing Your Telegram Bot At the beginning of 2019, security firm Forcepoint issued a statement pointing out some security concerns about Telegram bots. Forcepoint discovered that Telegram bots don’t use the same encryption protocol as Telegram itself. Telegram bots don’t employ the MTProto protocol, the encryption algorithm used by Telegram. This makes it much easier for third parties to intercept messaging from Telegram bots. Instead, Telegram bots use HTTPS web encryption. HTTPS web encryption is okay, but there’s a reason messaging apps rely on additional encryption methods to ensure their security. We’re going to show you a few different ways to make sure your Telegram bots are safe and secure. Keep Your API Key/Token Private As we mentioned earlier, a Telegram bot’s API key is its fingerprint. Whoever has access to that key can control that bot, using it for whatever they wish. The first and easiest way to make sure your Telegram bot is secure is to keep your API key safe. That way no one can use your Telegram bot for nefarious means. Harden set.php, unset.php, and hook.php The set.php, unset.php, and hook.php files also enable whoever has access to them to control your bot. set.php: registers your link to hook.php so that Telegram knows where to send your updates unset.php: disconnects that link, which allows the user to reset the bot to a different path hook.php: is where your Telegram updates are sent Here are a few ways to help make sure these three files are as secure as possible. Change The Filenames To Make Them More Secure You can rename these files to whatever you wish to make them harder to access. You wouldn’t just use the default password for a new computer system or software, would you? Change the name of these three files to make them harder to guess. You can make the file names as straightforward or as complicated as you wish. Just make sure to write down the new file names and keep them someplace secure, so you’re sure to remember their new names. Add Secret Parameters You can add a secret parameter inside your code to make them more secure. It might look a little something like this: https://mybot.net/hook.php?secret=AihezooSahc0aiquu3aigai2Phee2ien Then, inside the hook.php file, include the following code: if (!isset($_GET['secret']) || $_GET['secret'] !== 'AihezooSahc0aiquu3aigai2Phee2ien') { die("I'm safe =)"); } Remember to include this parameter inside the set.php file where you mention the webhook URL. Use Telegram Bot Manager The Telegram Bot Manager is a library that makes setting up and securing Telegram bots an absolute breeze. Limit Access To Telegram API IPs Telegram alerts users to know which IPs they’re sending updates from. To help your Telegram bot be as secure as possible, limit access to only the IPs Telegram is sending updates from. In your hook.php file, include the following code: // Set the lower and upper limit of valid Telegram IPs. // https://core.telegram.org/bots/webhooks#the-short-version $telegram_ip_lower = '149.154.167.197'; $telegram_ip_upper = '149.154.167.233'; // Make sure the IP is valid. $lower_dec = (float) sprintf("%u", ip2long($telegram_ip_lower)); $upper_dec = (float) sprintf("%u", ip2long($telegram_ip_upper)); $ip_dec = (float) sprintf("%u", ip2long($_SERVER['REMOTE_ADDR'])); if ($ip_dec < $lower_dec || $ip_dec > $upper_dec) { die("Hmm, I don't trust you..."); } You can also limit IP access on the server side. Here are a few examples. Using Apache Here’s a simple way to limit IP access without having to list each IP address. Order Allow,Deny Allow from 149.154.167.192/26 Using Nginx This command also limits a range of IPs, rather than having to list each one individually. location /mybot { allow 149.154.167.192/26; deny all; } And there you have it! You’ve set up a Telegram bot and made it secure. Now you’re able to take advantage of this powerful API and its broad user base. Telegram bots are a simple, easy way to get started with chatbots; operate a simple web store; or create exciting games to engage with your audience, without having to know a ton about how to code. The latest API insights straight to your inbox