[Python] Telegram bot - Updater

Discussão em 'Python' iniciado por Stack, Março 8, 2025.

  1. Stack

    Stack Membro Participativo

    This code is supposed to take up prices from 2 indexes from yahoo finance nd send them to the user when a text is sent in the chat:

    import requests
    import telegram
    from bs4 import BeautifulSoup

    def get_price(symbol):
    url = f"https://finance.yahoo.com/quote/{symbol}"
    page = requests.get(url)
    soup = BeautifulSoup(page.content, "html.parser")
    price = soup.find("span", {"data-reactid": "14"}).get_text()
    return price

    def check_price(update, context):
    symbols = ["^DJI", "^GSPC"]
    prices = [get_price(symbol) for symbol in symbols]
    message = "DJI: " + prices[0] + "\n" + "GSPC: " + prices[1]
    context.bot.send_message(chat_id=update.message.chat_id, text=message)

    token = "TOKEN NAME"
    bot = telegram.Bot(token)

    updater = telegram.Updater(token, use_context=True)

    dispatcher = updater.dispatcher

    price_handler = CommandHandler("price", check_price)

    dispatcher.add_handler(price_handler)

    updater.start_polling()


    However, it gives an error:

    \stocks.py", line 21, in <module>
    updater = telegram.Updater(token, use_context=True)
    AttributeError: module 'telegram' has no attribute 'Updater'. Did you mean: 'Update'?


    I have tried updating the telegram libruary and installing Updater, but it didn't work.

    I have also tried other variations of the code:

    import requests
    import telegram
    from telegram import Updater, InlineKeyboardButton, InlineKeyboardMarkup

    def get_price(symbol):
    url = f"https://finance.yahoo.com/quote/{symbol}"
    page = requests.get(url)
    text = page.text

    start = text.find("data-reactid=\"50\"") + len("data-reactid=\"50\"") + 1
    end = text.find("</span>", start)
    price = text[start:end].strip()

    return price

    def main():
    token = "BOT_TOKEN_GOES_HERE"
    updater = Updater(token)
    dp = updater.dispatcher

    def handle_text_message(update, context):
    chat_id = update.message.chat_id
    message = update.message.text

    dji_price = get_price("%5EDJI")
    sp_price = get_price("%5EGSPC")

    bot.send_message(chat_id=chat_id, text=f"DJI Price: {dji_price}\nSP Price: {sp_price}")

    dp.add_handler(MessageHandler(Filters.text, handle_text_message))

    updater.start_polling()
    updater.idle()

    if __name__ == '__main__':
    main()


    But it gives a similar error due to Updater:

    stocks.py", line 3, in <module>
    from telegram import Updater, InlineKeyboardButton, InlineKeyboardMarkup
    ImportError: cannot import name 'Updater' from 'telegram' (C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\__init__.py)

    Continue reading...

Compartilhe esta Página