Encountering indentation error when importing the telegram library in Python bot

I’ve been developing a Python bot for tracking stock prices, but I’m facing indentation errors during the import of the telegram module. My code seems correctly formatted, yet Python keeps returning this error message:

IndentationError: expected an indented block after function definition on line 13 (telegram.py, line 16)

Here’s the code for my bot:

from vnstock import *
import datetime
from datetime import date, timedelta
import telegram.ext
from telegram.ext import CommandHandler, Updater, MessageHandler, Filters

print('Bot is up and running...')

# Handle the /start command
def start(update, context):
    update.message.reply_text(text="Hello! You can use /sum [ticker] to get stock information.")

# Function to get the last trading day
def get_last_trading_day():
    current_day = datetime.datetime.now()

    if current_day.weekday() < 5 and current_day.time() < datetime.time(hour=9, minute=15):
        last_day = current_day - timedelta(days=1)
    elif current_day.weekday() == 6:
        last_day = current_day - timedelta(days=2)
    elif current_day.weekday() == 5:
        last_day = current_day - timedelta(days=1)
    else:
        last_day = current_day

    return last_day

# Handle the /sum command
def sum(update, context):
    stock_ticker = context.args[0].upper()
    try:
        previous_day = get_last_trading_day().strftime('%Y-%m-%d')

        if get_last_trading_day().weekday() == 0:
            start_date = get_last_trading_day() - timedelta(days=4)
        else:
            start_date = get_last_trading_day() - timedelta(days=2)

        second_day = start_date.strftime('%Y-%m-%d')

        # Fetch stock data
        stock_data = stock_historical_data(stock_ticker, second_day, previous_day)

        curr_price = stock_data.iloc[0, 3]
        volume = stock_data.iloc[0, 4]
        high_price = stock_data.iloc[0, 1]
        low_price = stock_data.iloc[0, 2]
        previous_close = stock_data.iloc[1, 3]

        price_diff = curr_price - previous_close
        percent_diff = (price_diff / previous_close) * 100

        price_diff = round(price_diff, 0)
        percent_diff = round(percent_diff, 2)

        if price_diff > 0:
            price_change_display = f'+{price_diff:.0f}'
            percentage_display = f'+{percent_diff:.2f}'
        else:
            price_change_display = f'{price_diff:.0f}'
            percentage_display = f'{percent_diff:.2f}'

        response_message = f"Latest update for {stock_ticker}:
"
        response_message += f"Current Price: {curr_price}
"
        response_message += f"Volume: {volume}
"
        response_message += f"High: {high_price}
"
        response_message += f"Low: {low_price}
"
        response_message += f"Change: {price_change_display}, {percentage_display}%
"

        update.message.reply_text(text=response_message)

    except:
        update.message.reply_text(text=f"Could not fetch information for {stock_ticker}. Please check the ticker and try again.")

# Message handler function
def handle_text(update, context):
    user_text = str(update.message.text).lower()
    response_text = 'I am not available for casual chat. Please use /sum [ticker] for information.'
    update.message.reply_text(response_text)

# Main function to run the bot
def run_bot():
    TOKEN = '......'
    bot = telegram.Bot(token=TOKEN)
    updater = Updater(TOKEN, use_context=True)
    dp = updater.dispatcher

    dp.add_handler(CommandHandler('sum', sum))
    dp.add_handler(CommandHandler('start', start))
    dp.add_handler(MessageHandler(Filters.text, handle_text))

    updater.start_polling(5)
    updater.idle()

run_bot()

I’m unsure why I’m getting this indentation error. The formatting seems correct, but it doesn’t agree with Python. Can anyone help me out?

Your Python file is named telegram.py, which is causing the problem. When you import the telegram library, Python loads your file instead of the actual telegram module. That’s why you’re getting the indentation error - your file structure doesn’t match what the library expects.

I’ve hit this exact issue before when building telegram bots. Just rename your file to stock_bot.py or main.py and it’ll work fine. This trips up tons of developers because Python always checks your current directory first before looking at installed packages.

Classic mistake! The error points to “telegram.py, line 16” - you named your file telegram.py, which conflicts with the actual Telegram module. Python’s trying to import your file instead of the real library. Rename it to bot.py or something else and that’ll fix the indentation error. We’ve all been there!

I had the same problem with telegram bots - turned out to be invisible characters messing things up. Since the error’s hitting telegram.py line 16, Python can’t parse your file properly. Copy your entire code into Notepad, then paste it into a fresh Python file. This kills any hidden characters from copy-pasting between different sources. Also make sure your file isn’t named telegram.py - that’ll conflict with the actual telegram module. Check your Python version too. Some telegram library versions need specific Python versions and cause weird import issues if they don’t match.