You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Telegram Bot导入模块时触发IndentationError错误求助

解决Telegram Bot导入模块时的IndentationError错误

我正在开发一款返回股票价格信息的Telegram Bot,之前能正常导入telegram模块,但运行代码时出现如下错误:

Exception has occurred: IndentationError
expected an indented block after function definition on line 13 (telegram.py, line 16)
File "D:\Telegram Bot\tele_stock_bot2.py", line 4, in
import telegram.ext
IndentationError: expected an indented block after function definition on line 13 (telegram.py, line 16)

我的代码如下:

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

print('Bot started ...')

# Define a function to handle the /start command
def start_command(update, context):
    update.message.reply_text(text="Hi! Try /sum [ticker]]")




# Define a function to get the last trading day
def last_trading_day():
    today = datetime.datetime.now() # Get today's date AND TIME
    
    # If today is weekday and the current time is before 9:15 AM, get yesterday's date
    if today.weekday() < 5 and today.time() < datetime.time(hour=9, minute=15):
        last_trading_day = today - timedelta(days=1)   

    elif today.weekday() == 6: # If today is Sunday, get last Friday
        last_trading_day = today - timedelta(days=2)   
    
    elif today.weekday() == 5: # If today is Saturday, get last Friday
        last_trading_day = today - timedelta(days=1)
    # Otherwise, get today
    else:
        last_trading_day = today - timedelta(days=0)

    return last_trading_day

# Define a function to handle the /sum command
def sum_command(update, context):
    ticker = context.args[0].upper()     # Get the stock ticker from user input
    try:
        #today = datetime.datetime.now().strftime('%Y-%m-%d')
        
        T_0 = last_trading_day.strftime('%Y-%m-%d')
    
        #define last_trading_day()[1] aka T-1
        if last_trading_day.weekday() == 0: # If last trading day is Monday, get last Friday
            start_date = last_trading_day - timedelta(days = 4)
        else: # Otherwise, get last trading day minus one
            start_date = last_trading_day - timedelta(days = 2)

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


        # Get the stock data:
        stock_data = stock_historical_data(ticker, T_minus_2, T_0)
       
        price = stock_data.iloc[0, 3]
        vol = stock_data.iloc[0, 4]
        high = stock_data.iloc[0, 1]
        low = stock_data.iloc[0, 2]
        close_prev = stock_data.iloc[1,3]
        price_change = price - close_prev
        perc_change = (price_change / close_prev)*100
        price_change = round(price_change,0)
        perc_change = round(perc_change,2)
        if price_change >0:
            price_change_str = f'+{price_change:.0f}'
            perc_change_str = f'+{perc_change:.2f}'
        else:
            price_change_str = f'{price_change:.0f}'
            perc_change_str = f'{perc_change:.2f}'

        message = f"Latest information for {ticker}:\n"
        message += f"Price: {price}\n"
        message += f"Volume: {vol}\n"
        message += f"High: {high}\n"
        message += f"Low: {low}\n"
        message += f"Change: {price_change_str} , {perc_change_str}%\n"
        

        update.message.reply_text(text=message)
    
    except:
        update.message.reply_text(text=f"Error retrieving information for {ticker}. Please check the ticker and try again.")


def handle_message(update, context):
    text = str(update.message.text).lower
    response = 'I\'m not here to chitchat. Use /sum [ticker] command plz'
    update.message.reply_text(response)

# Set up the Telegram bot
def main():
    API_KEY = '......'
    bot = telegram.Bot(token=API_KEY)
    updater = Updater(API_KEY, use_context=True)
    dp = updater.dispatcher

    # Add handlers for the /overview and /start commands
    dp.add_handler(CommandHandler('sum', sum_command))
    dp.add_handler(CommandHandler('start', start_command))
    dp.add_handler(MessageHandler(Filters.text, handle_message))

    # Start the bot
    updater.start_polling(5)
    updater.idle()

main()

我不理解为何会出现该错误,因为对应行并未缩进,恳请帮忙解决。


问题原因

错误提示指向telegram.py文件的第16行,而非你的代码文件,说明项目目录中存在一个和官方telegram模块同名的本地文件telegram.py。Python导入模块时会优先加载本地同名文件,而这个本地文件里的函数定义后没有缩进代码,触发了IndentationError。

解决步骤

  1. 重命名本地telegram.py:找到项目目录下的telegram.py,改成其他名称(比如my_telegram_helper.py),避免和官方模块冲突。
  2. 删除__pycache__文件夹:项目目录里的__pycache__文件夹缓存了错误的模块文件,删除它确保Python重新加载官方模块。
  3. 修复代码中的调用问题:你的代码里还有几处函数调用错误:
    • 将T_0 = last_trading_day.strftime('%Y-%m-%d')改为T_0 = last_trading_day().strftime('%Y-%m-%d')
    • 将if last_trading_day.weekday() == 0:改为if last_trading_day().weekday() == 0:
    • 将start_date = last_trading_day - timedelta(days = 4)改为start_date = last_trading_day() - timedelta(days = 4)
    • 将start_date = last_trading_day - timedelta(days = 2)改为start_date = last_trading_day() - timedelta(days = 2)
    • 将text = str(update.message.text).lower改为text = str(update.message.text).lower()(lower是方法,需要加括号调用)

内容的提问来源于stack exchange,提问作者Ebayama Zon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 17:15:37