Try ModdyAI for FREE!

Create your own AI-powered moderator — no coding required. Prefer building your own tools? Use our API to integrate moderation into your workflow effortlessly.

Try for Free

Python Telegram Bot for Beginners: How to Build a Stock Price Alert Bot

Published on June 4, 2025 5 min read


Cover for the article

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.

Screenshot of Telegram Bot Father interface

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.

This API key is your bot's identity; don't share it publicly.

Diagram of Telegram Bot creation process

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.

pip install pyTelegramBotAPI==3.7.7

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()

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


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:


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.