Search code examples
pythontypeerrortelegram-botyfinance

TypeError: 'in <string>' requires string as left operand, not builtin_function_or_method


Hi everyone I have been watching & following along this youtube video: https://www.youtube.com/watch?v=NwBWW8cNCP4&t=313s which creates a telegram bot to retrieve stock price from yfinance API from Yahoo Finance website. I was following along the video and after I run my code I encountered this TypeError

Here is my code:

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

This is the error message I got:


 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
PS C:\Users\USER\Desktop\Python\Telegram Bot\Stocks bot2>

Does anyone know how can I resolve this?

What I have done:

if 'price' not in len(request) < 2 or request[0].lower :

and making

len(request) < 2 or request[0].lower

return a True or False value


Solution

  • Change:

    if len(request) < 2 or request[0].lower not in 'price':
    

    to:

    if len(request) < 2 or request[0].lower() not in 'price':
    

    Without the parentheses, request[0].lower is just a bound method. To actually call it, to obtain a string, you need to add parentheses: request[0].lower().