Telegram股票机器人报TypeError:‘in <string>’需字符串左操作数
修复Telegram股票机器人的TypeError错误
问题场景
开发Telegram股票机器人时,通过yfinance API获取雅虎财经股票价格,运行代码触发TypeError错误,错误位于stock_request函数的判断语句处。
错误信息
File "c:\Users\USER\Desktop\Python\Telegram Bot\Stocks bot2\main.py", line 47, in stock_request if len(request) < 2 or request[0].lower not in 'price': ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: 'in <string>' requires string as left operand, not builtin_function_or_method
原始代码
import os import telebot from dotenv import load_dotenv import yfinance as yf load_dotenv() API_KEY = os.getenv('API_KEY') bot = telebot.TeleBot(API_KEY) @bot.message_handler(commands=['Greet']) def greet(message): bot.reply_to(message, "Hello! How are you?") @bot.message_handler(commands=['hello']) def hello(message): bot.send_message(message.chat.id, "Hello!") @bot.message_handler(commands=['wsb']) def get_stocks(message): response = "" stocks = ['tsla', 'sq', 'pltr'] stock_data = [] for stock in stocks: data = yf.download(tickers=stock, period='2d', interval='1d') data = data.reset_index() response += f"-----{stock}\-----\n" stock_data.append([stock]) columns = ['stock'] for index, row in data.iterrows(): stock_position = len(stock_data) - 1 price = round(row['Close'], 2) format_date = row['Date'].strftime('%m/%d') response += f"{format_date}: {price}\n" stock_data[stock_position].append(price) columns.append(format_date) print() response = f"{columns[0] : <10}{columns[1] : ^10}{columns[2] : >10}\n" for row in stock_data: response += f"{row[0] : <10}{row[1] : ^10}{row[2] : >10}\n" response += "\nStock Data" print(response) bot.send_message(message.chat.id, response) def stock_request(message): request = message.text.split() if len(request) < 2 or request[0].lower not in 'price': return False else: return True @bot.message_handler(func=stock_request) def send_price(message): request = message.text.split()[1] data = yf.download(tickers=request, period= '5m', interval='1m') if data.size > 0: data = data.reset_index() data["format_date"] = data['Datetime'].dt.strftime('%m/%d %I:%M %p') data.set_index('format_date', inplace=True) print(data.to_string()) bot.send_message(message.chat.id, data['Close'].to_string(header=False)) else: bot.send_message(message.chat.id, "No Data!?") bot.polling()
用户尝试的无效修改
曾尝试将判断语句改为if 'price' not in len(request) < 2 or request[0].lower :,问题未解决。
修复方案
错误原因
request[0].lower未加括号,此时是字符串的lower方法对象,而非执行方法后得到的小写字符串,导致无法用in进行字符串判断。- 原逻辑错误:
request[0].lower() not in 'price'是检查字符串是否为'price'中的单个字符,而非判断是否等于完整的'price'。
修改后的stock_request函数
def stock_request(message): request = message.text.split() if len(request) < 2 or request[0].lower() != 'price': return False else: return True
解释
- 添加括号调用
lower()方法,获取小写后的字符串,解决TypeError问题。 - 用
!= 'price'替代not in 'price',符合业务逻辑:判断用户输入的第一个词是否为完整的'price'(如用户输入price TSLA触发查询)。
内容的提问来源于stack exchange,提问作者Lehends01
相关产品推荐
相关产品推荐

