
A Telegram bot is a software program that receives messages through the Telegram Bot API and sends useful replies or actions back to a chat. This beginner Telegram bot tutorial shows how to create a Telegram bot with BotFather, Ruby, and long polling, then deploy it so it keeps running.
You do not need to be a master programmer. With a basic grasp of code and APIs, you can build your first Telegram bot, add commands, return random responses, and turn a small experiment into useful software.
I’ve been obsessed with science fiction since I was a young teen, so coding has always appealed to me. The idea that a program could behave differently from one run to the next already felt like science fiction. That curiosity fueled my first bots, including one that combined words into scary-sounding place names and another that painted simple block-color images.

The best beginner projects give you an immediate result. A bot can answer a command, fetch a feed, route a support request, control a smart-home service, or reply using nothing but Shakespeare quotes. The project stays small enough to understand, but it can grow as far as your imagination and the APIs around it.
That is why I decided to write this tutorial. A Telegram bot is a good entry point for aspiring coders looking for something instantly rewarding and potentially valuable. Compared with building a bot against a more complicated social-media API, Telegram makes the initial setup unusually direct: the registration conversation, token, command handling, and message reply are all visible as you build.

Telegram is a practical home for that experiment because BotFather handles registration and the Telegram Bot API provides a direct way to receive updates and send messages. Telegram reported more than one billion monthly active users in 2025, but scale is not the main reason to start here. The useful part is the short path from an idea to a working chat interface.
A customer-facing bot could also include automation that combines helpful resources with live chat. It can create genuinely useful automated support, answer inquiries, collect email addresses with consent, or act as a control panel for another system. Meeting an audience in an app they already use reduces friction and encourages adoption, but the bot still needs a clear purpose and responsible data handling.
My first Telegram experiment used HNRSS to find Hacker News submissions matching a search query. That same pattern can power alerts, summaries, support routing, or a small agent that moves information between systems.

In this guide, you will learn how to:
- register a bot with BotFather and protect its token
- create a small Ruby project with Bundler
- use the maintained
telegram-bot-rubylibrary - listen for commands and send replies
- return a random response from an array
- track the project with Git
- deploy the bot to a Raspberry Pi or cloud server
Before you begin, install Ruby, Bundler, Git, and a maintained code editor. macOS and Linux already include a terminal. On Windows, Windows Subsystem for Linux provides a straightforward Bash environment, while RubyInstaller is another supported way to install Ruby.
Bundler helps manage Ruby gems, which add extra functionality to an application without forcing you to write every API interface yourself. A purpose-built text editor highlights Ruby syntax, keeps the Gemfile and bot.rb together, and makes code mistakes more obvious than a plain document editor.
Install Telegram Desktop
Install Telegram on the same computer where you will write the code. Keeping the chat app, editor, and terminal together makes the test loop fast: change the file, run the bot, send a command, and inspect the reply.

You can also test from a phone, but Telegram Desktop makes it easier to copy your bot username and move between BotFather, your editor, and the running terminal. Download the desktop app from Telegram’s official site, sign in, and keep it open while you work.
Create the bot with BotFather
Telegram bot creation begins inside Telegram itself. Search for @BotFather, Telegram’s official bot-management account, and open the verified conversation. Send /start to see the available commands.

Send /newbot. BotFather asks for two things: a display name and a username. The display name is what people see in the chat list. The username must be unique and normally ends in bot, such as hello_example_bot.

Choose a short name that explains the bot’s job. A useful username is easy to type, easy to remember, and specific enough that another developer has not already claimed it.

BotFather then issues a bot token. The token authenticates your code to the Telegram Bot API. Treat it like a password: do not paste it into a public repository, screenshot it, or send it to another person. If it leaks, revoke it in BotFather and generate a replacement.
After giving the /newbot command and completing the name prompts, the token is associated with that particular bot. Every bot has its own API key, also called an API token. Anyone who obtains it could hijack the bot and make it carry out actions under that identity, so copy it straight into secure storage rather than leaving it in the chat or editor.

This tutorial loads the token from an environment variable instead of hard-coding it in bot.rb. In your terminal, set it for the current session:
export TELEGRAM_BOT_TOKEN='paste-your-token-here'
On Windows PowerShell, use $env:TELEGRAM_BOT_TOKEN='paste-your-token-here'. For a permanent deployment, store the value in your hosting provider’s secret manager or service environment, not in Git.
Set up the Ruby project
Create a directory and two files:
mkdir telegram-bot
cd telegram-bot
touch Gemfile bot.rb

Open the folder in your preferred editor. Add this to Gemfile:
source 'https://rubygems.org'
gem 'telegram-bot-ruby', '~> 2.8'
The maintained telegram-bot-ruby project follows the current Telegram Bot API and provides the client used below.
Install the dependency:
bundle install

Bundler records compatible gem versions in Gemfile.lock. Commit both the Gemfile and lockfile so the same dependency set can be installed on your server.
Code your first Telegram bot
Open bot.rb. The program needs to load the library, read the token, listen for messages, identify a command, and send a reply. Start with this complete version:

require 'telegram/bot'
token = ENV.fetch('TELEGRAM_BOT_TOKEN')
Telegram::Bot::Client.run(token) do |bot|
bot.listen do |message|
next unless message.respond_to?(:text) && message.text
reply = case message.text
when '/start'
'All I can do is say hello. Try /greet.'
when '/greet'
"Hello, #{message.from.first_name}!"
else
"I do not know what #{message.text.inspect} means."
end
bot.api.send_message(chat_id: message.chat.id, text: reply)
end
end
ENV.fetch reads the token from the environment and stops immediately if it is missing. Telegram::Bot::Client.run creates the API client. The bot.listen block uses long polling to receive updates, then the case statement selects a reply for each command.
The listener is one big loop, which can look confusing at first but becomes easy to pick apart. When the bot receives a message, the library passes it into the message variable. The case statement reads the message text, chooses the response action, and stores the bot’s reply. Finally, send_message sends that text to the same chat before the loop starts again. This is the actual code path your bot follows for every command.
Long polling is ideal for a first bot because you can run it from a terminal without a public HTTPS endpoint. Telegram also supports webhooks, where Telegram sends each update to your server. The two update methods are mutually exclusive, so choose one at a time.
Save the file and run:
bundle exec ruby bot.rb
Open your bot in Telegram and send /start, followed by /greet. As long as the process remains open, the bot can receive and answer messages.

Customize your bot
The basic pieces are now in place. The when lines are inputs your bot recognizes, and the strings beneath them are outputs it sends back. Add another branch to support a new command, or change the reply without touching the rest of the listener.
The parts to pay attention to when customizing are the command values and the text returned underneath them. These are the inputs your bot accepts and the messages it sends back as responses. If you wanted to say something different for /greet, you would change the value in that branch. You can add another command without changing the token setup or the listening loop.
To return a random greeting, replace the /greet branch with:
when '/greet'
greetings = ['bonjour', 'hola', 'hallo', 'sveiki', 'namaste', 'salaam', 'szia', 'halo', 'ciao']
"#{greetings.sample.capitalize}, #{message.from.first_name}!"
Ruby’s Array stores the greetings, and sample returns one element at random. This tiny change demonstrates the pattern you will use for richer behavior: accept an input, run some logic, and produce a response.

Turn your bot into something useful
You can add as many commands, responses, and features as the project needs. The Telegram Bot API supports buttons, files, photos, locations, payments, and more. Ruby libraries can connect the bot to external services or your own database.
- Pull data from another service. Use an API client for tools such as Airtable or Slack, or parse feeds with Ruby’s RSS library.
- Store user input. A support bot can capture a request, attach the chat ID, and save a record. The Sequel toolkit provides a clean Ruby interface for relational databases.
- Build a text adventure. Projects inspired by Colossal Cave Adventure turn chat commands into rooms, inventory, and choices.
- Build an agent. The same request, decision, action, and reply loop is a useful foundation for AI agent development, especially when the agent needs controlled tools and clear handoffs.
Read current bot repositories on GitHub and compare how they structure commands, error handling, persistence, and tests. Recreate one small behavior at a time instead of copying a large bot you do not yet understand.
Other bot source code can reveal reusable programming patterns. Trace how each command is recognized, where data is stored, and how API failures are handled. Then recreate one behavior as practice. Most of the interesting functionality comes from connecting a conversational interface to a specific set of data or features.
Run your bot continuously
Right now, your bot runs on your computer. If the terminal closes, the computer sleeps, or the network disappears, the process stops and users receive no reply. Deployment moves the same code to a computer designed to stay online.
Start by tracking the project with Git. Create an empty repository on the Git host you prefer, then run:
git init
git add Gemfile Gemfile.lock bot.rb
git commit -m 'Build first Telegram bot'
git branch -M main
git remote add origin YOUR_REPOSITORY_URL
git push -u origin main

Never add your bot token to the repository. If you accidentally commit it, revoke the token even if you remove it in a later commit. Git history can retain the secret.

Deploy with a Raspberry Pi
A Raspberry Pi is a practical host for experiments at home or in an office. Install a current Raspberry Pi OS image, connect the device to a reliable network, install Ruby, Bundler, and Git, then clone the repository. Store the token in the service environment.
The small computer uses very little power, so it can stay on without turning a bot experiment into a full server project. A basic setup needs the board, a suitable power supply, storage, and a network connection. A separate keyboard, mouse, and monitor are optional once remote access is configured. This keeps the physical deployment path inexpensive and easy to understand.

For reliability, run the bot as a systemd service instead of leaving it attached to an SSH window. A service can start at boot, restart after a failure, and keep logs in one place. The exact service file depends on your username and project path, so verify those values before enabling it.
Deploy with a cloud server
A small Linux virtual machine from AWS, DigitalOcean, or another provider works the same way. Create the server, connect over SSH, install the runtime, clone the repository, set TELEGRAM_BOT_TOKEN as a protected environment variable, and run the program through a service manager.
Popular cloud deployment choices include Amazon Web Services, DigitalOcean, and application hosting platforms. You do not need to own the computer that runs the bot. You are renting the memory, storage, network connection, and processing power of another machine, then administering it remotely. Once connected, the important surface is still a Bash terminal.
On a Debian or Ubuntu server, the setup normally begins with:
sudo apt update
sudo apt install git ruby-full build-essential
gem install bundler
git clone YOUR_REPOSITORY_URL telegram-bot
cd telegram-bot
bundle install
Do not paste a provider password into a Git prompt. Use an SSH key or a scoped access token for private repositories. A public repository can be cloned without credentials, but it still must not contain your Telegram token.

Once the service is running, send /start from Telegram and check the server logs. Test the restart path too. A bot that starts only during the first SSH session is not truly deployed.
The actual deployment is complete only when the bot’s source files, gem dependencies, token environment, service account, restart policy, and logs are all in place. You should be able to reboot the host, reconnect later, and confirm the bot is still running. This separates a development environment that works while your computer is awake from a production environment that can serve users continuously.
Test and troubleshoot the bot
Test one layer at a time. First confirm that TELEGRAM_BOT_TOKEN is present in the same shell that runs Ruby. Next run bundle exec ruby bot.rb and send /start in a direct chat with the correct bot username. If nothing arrives, check that the token belongs to that bot and that an old webhook is not still configured. Telegram cannot deliver updates through long polling while a webhook is active.
Log failures without logging secrets. It is useful to record the update ID, chat ID, command name, response status, and exception class. It is not useful to print the bot token, complete user messages, or personal data that the bot does not need. A small project is a good place to establish secure habits before the bot handles real customer or employee information.
Be careful with older Ruby examples. Code that starts with require 'telegram_bot', creates TelegramBot.new(token: token), or calls bot.get_updates(fail_silently: true) belongs to a different, archived gem. The same applies to helpers such as message.get_command_for(bot), message.reply, reply.text, and reply.send_with(bot). Do not mix those methods with telegram-bot-ruby. The maintained client uses Telegram::Bot::Client.run, bot.listen, and bot.api.send_message.
Commands should be predictable. Start each one with a slash, keep names short, and return a helpful response for unknown input. BotFather can publish the command list so Telegram shows suggestions in the chat interface. If a command performs a consequential action, confirm the user’s intent before executing it and return an explicit success or failure message.
Long-running work needs more care than a greeting. A slow API request can block the listener, and a transient network failure can interrupt a response. Add timeouts, retries with limits, and clear error handling as the bot grows. Store durable state in a database instead of relying on Ruby variables that disappear when the process restarts.
Keep development and production separate. Use a second bot token for experiments, test new commands locally, and deploy only committed code. If you want more practice before connecting external systems, choose one of these small programming project ideas and implement it as a single command. For a deeper comparison of repository hosts, see this guide to Bitbucket and GitHub.
On a fresh server, whether it is a Raspberry Pi or a cloud server, install Ruby, Bundler, and Git before downloading the files. Older instructions may show sudo apt-get update, sudo apt-get upgrade, an RVM installer, and sudo apt-get install bundler. Those commands are not automatically wrong, but they tie the deployment to a particular Linux distribution and Ruby manager. Use the package instructions for the server you actually created.
Likewise, avoid treating nohup ruby bot.rb & as the finished production setup. It can keep the bot alive after an SSH session ends, but it does not give you the restart policy, structured logs, service ownership, or boot behavior of a real service manager. When the service is configured, you are free to close the terminal window knowing the bot can restart and quietly beep boop in the background.
Telegram bot FAQ
How do I create a Telegram bot?
Open the verified @BotFather account, send /newbot, choose a display name and unique username, then store the issued token securely. Connect your code with the Telegram Bot API and send a test message.
What does “bot Telegram” mean?
Searches for “bot Telegram” usually refer to a Telegram bot: a program that receives updates and sends messages through Telegram’s Bot API.
Should I use long polling or a webhook?
Use long polling for a first project or a small service that can keep one process running. Use a webhook when you already have a public HTTPS application that can receive and verify incoming requests. Telegram allows only one update method at a time.
Where should I store the Telegram bot token?
Use an environment variable or the secret manager supplied by your hosting provider. Never commit the token to Git or expose it in an image, log, or support message.
How do I host a Telegram bot?
Run it on an always-on Raspberry Pi, virtual machine, container platform, or application host. Use a service manager so the process starts after a reboot and restarts after a failure.
You now have the full path from BotFather to a continuously running Ruby bot: registration, secure token handling, commands, replies, customization, source control, and deployment. The bot can keep quietly beep booping while you decide what useful job it should do next.