![](/img/trans.png)
[英]What is Updater, Dispatcher, context in python-telegram-bot?
[英]Telegram bot - Updater
此代碼應該從 yahoo finance 的 2 個索引中獲取價格,並在聊天中發送文本時將它們發送給用戶:
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()
`
但是,它給出了一個錯誤:
\stocks.py", line 21, in <module>
updater = telegram.Updater(token, use_context=True)
AttributeError: module 'telegram' has no attribute 'Updater'. Did you mean: 'Update'?
我已經嘗試更新電報庫並安裝更新程序,但它沒有用。
我還嘗試了代碼的其他變體:
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()
但由於更新程序,它給出了類似的錯誤:
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)
telegram
package 中沒有 class Updater
。有telegram.Update
和telegram.ext.Updater
,兩者之間幾乎沒有關系。 本教程更詳細地解釋了這一點。
另請注意,您使用的版本 <= 13.15 的python-telegram-bot
庫。 該版本不再受支持。 如果您是python-telegram-bot
的新手,我建議您從v20開始。
免責聲明:我目前是python-telegram-bot
的維護者
您應該從exe
模塊導入更新程序。 from telegram.exe import Updater
你必須從 telegram.ext 導入更新程序
從 telegram.ext 導入更新器
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.