Python Telegram Bot for Beginners: How to Build a Stock Price Alert Bot
Published on June 4, 2025 • 5 min read

How to Build a Telegram Bot with Python: A Beginner's Guide
Introduction
If you're a beginner developer curious about automation, integrating a Telegram bot using Python is a fantastic place to start. This guide walks you through setting up your own Telegram bot that can send you alerts or information on demand. By exploring how to use Telegram's Bot API with Python, you'll learn key concepts like handling commands, interacting with APIs, and managing messages—all with simple code. Whether you're interested in stock price notifications or custom chat commands, this tutorial will help you build your first Telegram bot efficiently and securely.
Creating Your Telegram Bot and Getting the API Key
The first step to building a Telegram bot is creating it on Telegram and getting an API key, which you'll use to securely communicate with Telegram's servers.
- Sign Up on Telegram: If you haven't already, download Telegram and create a free account.
- Find BotFather: Search for "BotFather" in Telegram. It is Telegram’s official bot for creating and managing bots.
- Create a New Bot: Start a chat with BotFather, enter the command
/newbot
, and follow the prompts to name your bot and create a unique username ending with "bot". - Save Your API Token: BotFather will give you an HTTP API token. Keep it somewhere safe; you'll need it in your Python code.
This API key is your bot's identity; don't share it publicly.
Setting Up Your Python Environment with Telebot
Next, set up your Python environment where your Telegram bot code will run. You can run this locally or use online services like Replit for convenience.
- Choose Your Environment: For this tutorial, Replit is a great option because it enables instant sharing and provides free hosting (though it may sleep after inactivity).
- Install the Required Library: You'll need the
pyTelegramBotAPI
library (make sure it's version 3.7.7 or close to ensure compatibility). You can install it via pip:
pip install pyTelegramBotAPI==3.7.7
- Secure Your API Key: Instead of hardcoding your token in your Python script (which exposes it publicly), store it in an environment variable or
.env
file.
Here's a quick example of how to read your API key securely using the os
module:
import os
API_KEY = os.getenv('API_KEY')
This practice helps keep sensitive information out of your public repo.
Writing and Running Your First Telegram Bot Script
Now that you have your token and environment set up, you can write a simple bot script.
import telebot
import os
API_KEY = os.getenv('API_KEY')
bot = telebot.TeleBot(API_KEY)
# Handler for the /greet command
@bot.message_handler(commands=['greet'])
def greet(message):
bot.reply_to(message, "Hey, how's it going?")
bot.polling()
- The
@bot.message_handler
decorator listens for the/greet
command. - When
/greet
is sent to your bot, it replies with "Hey, how's it going?" bot.polling()
keeps the bot running, listening for incoming messages.
To try this, run your script and message your bot /greet
in Telegram.
Enhancing Your Bot: Fetching Stock Prices with Yahoo Finance
Want to do something useful with your bot? Let's extend it to fetch the latest stock prices.
Using Yahoo Finance API in Python
You can use the yfinance
library for easy stock data retrieval:
pip install yfinance
Implementing the Stock Price Fetch
Add a command /wsb
that sends back the recent stock prices for popular Wall Street Bets favorites like AMC, GameStop, and Nokia.
import yfinance as yf
@bot.message_handler(commands=['wsb'])
def wsb_stocks(message):
stocks = ['AMC', 'GME', 'NOK']
response = 'Stock\tDate\tClose\n'
for stock in stocks:
data = yf.download(stock, period='3d', interval='1d')
for index, row in data.iterrows():
date = index.strftime('%m/%d')
close = round(row['Close'], 2)
response += f'{stock}\t{date}\t{close}\n'
bot.send_message(message.chat.id, response)
When you send /wsb
to your bot, it replies with a neatly formatted stock price summary.
Creating Custom Text Handlers Without Commands
Sometimes, you'd want your bot to respond to messages without using slash commands.
For instance, a user might type "price Tesla" to get Tesla stock info.
Here's how you can set up such a handler:
@bot.message_handler(func=lambda message: message.text and message.text.lower().startswith('price '))
def stock_price(message):
try:
parts = message.text.split()
if len(parts) < 2:
bot.reply_to(message, "Please provide a stock symbol after 'price'.")
return
symbol = parts[1].upper()
data = yf.download(symbol, period='5m', interval='1m')
if data.empty:
bot.send_message(message.chat.id, f"No data found for {symbol}.")
return
latest = data.iloc[-1]
date = latest.name.strftime('%m/%d %I:%M %p')
close = round(latest['Close'], 2)
bot.send_message(message.chat.id, f"{symbol} price at {date} is ${close}")
except Exception as e:
bot.send_message(message.chat.id, "Sorry, something went wrong.")
This listens to any message starting with "price" and sends back the latest stock price.
Conclusion
Building a Telegram bot using Python is an excellent way for beginner developers to automate useful tasks and learn API interactions. We've covered how to set up your bot via BotFather, securely configure your API key, create command handlers, fetch real-time stock data, and even create custom message responses without explicit commands. Try building this Telegram bot and customize it to fit your interests—maybe a crypto price checker or weather alerts!
Happy coding!
Related Resources
- Learn more about Python environment variables to secure secrets.
- Explore Telegram Bot API official documentation for advanced bot features.
Meta Description
Learn how to build a Telegram bot with Python, handle commands, and fetch stock data. A beginner-friendly guide to automate alerts and info retrieval!
Image descriptions:
- Screenshot of Telegram Bot Father interface showing bot creation.
- Diagram illustrating the Telegram bot creation process from BotFather to running your Python script.
Categories: python, bots_development Tags: Telegram bot, Python Telegram bot tutorial, beginner Python projects, stock price bot, pyTelegramBotAPI
This blog post is based on content from a YouTube video. Watch it here. All rights reserved by the original creator.