We re Sorry We re Not Able to Process Your Request Right Now Please Try Again Later On Paypal
I've been obsessed with science fiction since I was a young teen, and then coding has always appealed to me. I was fascinated by the idea that information technology 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 commencement forays into lawmaking, and resulted in a ton of fun bots. For instance, this one that describes scary-sounding places by combining words at random, and this one that paints PNGs in block colors.
Information technology's goose egg fancy. I'g hardly a master programmer, and you don't have to be either. With a basic grasp of coding and APIs, you lot can create genuinely useful software for fun and turn a 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 besides include automation that combines helpful resources with alive chat, like in the example below from orat.io:
Telegram is a swell 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 cosmos 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) past leveraging a pop and functional platform.
The first bot I made for Telegram used RSS to find Hacker News submissions that lucifer a search query:
Take a play effectually with the bot — it's live here!
With the cognition from this guide and a little further reading, y'all could make a support chatbot for your company, an RSS feed reader, a control panel for your smart abode, or a bot that replies using simply Shakespeare quotes. Little programming projects like this are smashing 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:
- How to write a Telegram bot from scratch
- How to add new commands to the bot'due south vocabulary
- Bones concluding commands for creating files and navigating through folders
- A little bit of the Ruby programming language
- How to expand Ruby with gems
- How to make your bot return random responses from a list
- A few easy git commands to help you manage and transfer your code files
- How to deploy the bot to a server and run it 24/7
Before starting, you'll need:
- A fustigate terminal. This comes packaged with macOS and Linux, just non most installs of Windows. If you lot're following this tutorial on a Windows machine that doesn't accept Windows 10's Ceremony Update, you can use an emulator or emulate Linux in a virtual machine.
- Cerise. Refer to Blood-red'due south official documentation for Os-specific guides. I personally use Homebrew on macOS, only Windows users can install it with this tool.
- Bundler. Bundler helps manage Ruby gems, which add actress functionality to your apps. Y'all'll need information technology to add an interface to the Telegram API to your bot. Only run
jewel install bundler
in your concluding to install it. - A text editor. You lot could theoretically use Notepad or TextEdit, just most would recommend a purpose-congenital editor like Cantlet, which highlights syntax and helps makes code mistakes more obvious.
With that in place, allow'south get going.
Pace 1: Download the Telegram app for desktop
Telegram is predominantly a mobile app, just for development purposes you're going to want to have it installed on the same machine yous're using for writing code. This mode, you can rapidly test it without unlocking your phone every time. And, you'll be able to copy and paste your Telegram bot's API primal straight into your text editor.
Time to take hold of that API fundamental!
Footstep 2: Chat with the BotFather to go your API cardinal
Telegram bot creation is a novel procedure because much of it is centered around your own interactions with a Telegram bot. That bot is the BotFather. Within your Telegram desktop app, you need to search his username and get-go a conversation with him.
Requite the start command to BotFather past typing /starting time
.
You'll encounter a listing of commands that aid you create, edit, and manage your bots. Since it'due south your first time, yous'll want /newbot
.
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 neat tool Telegram bots can be!
Afterward giving the /newbot
command, you get to selection a proper noun and username for your bot. The name is what your users volition see the bot as in their contacts listing, and the username is how they'll find it. Think of the username like a Twitter handle; it has to be unique, and information technology's best if it's short and memorable.
With that done, you lot'll be given your bot's API key. The API primal is how Telegram knows the code you write is associated with this item bot. Every bot has its ain API fundamental, and y'all shouldn't share it with anyone or they could hijack your bot and take it carry out their evil deeds.
That concludes our chat with BotFather for at present — onto the code!
Step 3: Setting up the bot's gems and directory
Open final, and do mkdir telegram-bot
. This creates a new directory for your bot'southward files. It's best to continue them bars to ane folder so it's like shooting fish in a barrel to manage. Navigate to the directory with cd telegram-bot
so practise the post-obit:
affect Gemfile
impact bot.rb
atom .
This creates ii bare files, i for specifying the gems you lot'll need and ane where the bot'southward code will alive. The last command opens both of these files in Atom.
Click the Gemfile in Cantlet's sidebar, and paste the following in:
source 'https://rubygems.org' gem 'telegram_bot'
This tells Bundler to grab the Ruby interface to the Telegram API from rubygems.org.
To consummate the gem setup, go back to your terminal and type bundle
. Here's what you lot should see:
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 exist running constantly on the server is inside bot.rb. It's empty right at present, but hither we're going to link in the Telegram gem nosotros merely bundled and create a bot.
It'southward not much code to write. Past the time you're done, this is what you'll take:
In Telegram, this is what the code above does:
Let's look at what each part of the code does and write it as we go.
crave 'telegram_bot' token = 'TOKEN' bot = TelegramBot.new(token: token)
(Supersede the TOKEN with the API token yous copied from BotFather)
Ruby makes it quite easy to guess what lawmaking volition do. The iii lines above add together the Telegram bot functionality to your file and then create a new bot object from the TelegramBot course, 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'due south like shooting fish in a barrel to option apart.
bot.get_updates(fail_silently: true) do |bulletin| puts "@#{message.from.username}: #{message.text}" command = message.get_command_for(bot) bulletin.answer do |respond| case command when /start/i reply.text = "All I can do is say how-do-you-do. Effort the /greet command." when /greet/i answer.text = "Hello, #{message.from.first_name}. 🤖" else respond.text = "I have no idea what #{command.inspect} means." end puts "sending #{reply.text.inspect} to @#{message.from.username}" respond.send_with(bot) end stop
The starting time line tells the bot to keep listening for commands. And, when information technology receives a command to pass it to the message
variable. The puts
line logs the command to your terminal so you can run across what's going on while the bot runs.
The bot'southward response actions are stored in a case argument. The case statement's input is fed through from the message
variable after it'southward been cleaned up by the gem's get_command_for
method. The bot'south reply text is set depending on the command stored and so finally sent with send_with
earlier the loop restarts.
With this setup, you tin at present find your bot on Telegram and send the /showtime
and /greet
commands, and watch it in action.
To do this, salvage the changes in Atom and run scarlet bot.rb
in the concluding. As long as that terminal is open and running, your bot will send responses!
Customizing your shiny new bot
The bot you merely made is fine, merely information technology's not very interesting. The bones $.25 are there, which means you tin can swap them out and extend them easily.
The parts to pay attending 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 dissimilar as a response to the /greet
command, you lot'd change the value of reply.text
underneath the greet control line (when /greet/i
). Here's a variation you could try:
when /greet/i greetings = ['bonjour', 'hola', 'hallo', 'sveiki', 'namaste', 'salaam', 'szia', 'halo', 'ciao'] reply.text = "#{greetings.sample.capitalize}, #{message.from.first_name}!"
Here, I've created an assortment with a few dissimilar means to say hello, and and then added 1 to the message at random by using the sample method.
Turning your bot into something awesome
You can add as many commands, responses, and features to your bot equally you like. Nigh of it is imagination, and a lot of Googling equally you get. If you lot want to learn a lot of things that are applicable to this bot, start with Acquire Ruby the Hard Way to get to grips with the basics of the linguistic communication. With a bit of practice and a healthy reliance on StackOverflow, you'll exist able to:
- Connect other APIs to pull data from sources like Airtable, Slack, RSS, or Twitter. This is where the really exciting functionality comes in — y'all can create a bot that acts as a conversational interface to a ready of information or features, like a bot that returns search results from Twitter or posts to Slack.
- Store user input in a database. You could create a Telegram bot that offers automated support to users or responds to inquiries, and stores their emails addresses in a database. The Sequel precious stone makes it piece of cake to create, write, edit, and read databases.
- Build a text run a risk. Colossal Cave Adventure, 1 of the first last games, has been ported over to Telegram as a bot. Check it out here, and come across the source hither.
If you need inspiration, you can read other people'south bot source lawmaking, and check a listing of Telegram bots — try to figure out how they piece of work and recreate them every bit do.
Running your bot 24/7
Correct now, your bot is running in your terminal on your computer. That'southward fine until you need to restart your estimator, your wi-fi drops, or your estimator goes to sleep. When that happens, information technology terminates the bot's process and users won't become 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 environs (a server) is known equally deployment. In that location are a few options for deploying your bot, but in both cases we're going to start past uploading the files to Bitbucket. Bitbucket lets yous utilise git, a version control system that helps yous to safely brand and track changes to your bot's code. Past uploading your bot's files to Bitbucket, yous tin utilize Bitbucket every bit a way to grab the bot's files when you're logged into the host.
Sign up for Bitbucket and create a new repository.
With final open and in the same directory as your bot'due south source code, type the post-obit:
git init
git add together .
git commit -m 'initial commit'
At present, follow the instructions shown by Bitbucket after making the new repository. Mine are:
After inbound those two highlighted commands in my concluding and providing my Bitbucket password when requested, the files are uploaded. With your code living in the cloud, it's time to option a way to deploy.
Deploying with a Raspberry Pi

A Raspberry Pi is a great investment if you're planning on creating and deploying bots — you tin get 1 from as little every bit $seven plus the toll of an SD carte. It uses very petty power, so y'all tin keep it on all the time and non worry well-nigh the cost. It might exist tempting to buy a bundle that comes with a keyboard, mouse, and case simply all you need is a USB charger, SD card, ethernet cablevision and the computer itself. Y'all probably have most of these things in your part already.
Deploying with a cloud server
You don't need to ain the estimator 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 deject include Amazon Web Services (AWS), DigitalOcean, and Heroku.
Out of the iii, the most entry-level are DigitalOcean and Heroku. Click hither to get a DigitalOcean account that comes with $10 of credit — enough to run a server for two months while you examination it out.
When y'all sign upwardly for DigitalOcean and create a new droplet, y'all'll learn how to connect to the server via SSH and launch the console.
From here, it'south the aforementioned process as you lot did on your local machine regardless of the server you're using. In the terminate, it's just a fustigate terminal. With some kind of server prepare, allow's move onto the actual deployment.
The deployment process
On a fresh server — whether that's a Raspberry Pi or a cloud server similar Digital Ocean — you'll demand to install Cerise, Bundler, and Git:
sudo apt-get update
sudo apt-get upgrade
curl -Fifty https://get.rvm.io | fustigate -s stable --ruby
sudo apt-go install bundler
sudo apt-get install 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
Retrieve to supercede the URL to a higher place (https://benjbran…) with the URL of your bot's repository on Bitbucket. Y'all'll find the whole clone command through Bitbucket, and then you won't take 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 yous're accessing your server via SSH, you'll demand to run the bot with nohup ruby bot.rb &
to make sure the bot doesn't end working when the SSH session is terminated. Now you're free to close the terminal window, safe in the noesis that your bot is quietly beep booping away in the groundwork. 🤖
That concludes your starting time stab at a Telegram bot. Along the way, y'all learned about the last, Ruby, gems, the Telegram API, and how to deploy a bot to a server. Whatsoever questions or suggestions? You can message me on Twitter.
Source: https://www.process.st/telegram-bot/
Postar um comentário for "We re Sorry We re Not Able to Process Your Request Right Now Please Try Again Later On Paypal"