[英]How do I make a python bot with selenium that checks when a new message has arrived from a Telegram channel?
我應該首先提到我對 python 和 selenium 很陌生,所以我對它們中的任何一個都不太了解。
到目前為止,我所做的是查看 class ,其中包含所有消息的文本im_message_text
,並獲得列表中的最后一個。
注意“強”標簽只是標題存儲在文本消息旁邊的位置,這是我用來比較所有內容的地方:
def getItemsInfo1(self):
try:
iteminfo1 = WebDriverWait(self.driver, 4).until(
EC.presence_of_element_located((By.CLASS_NAME, 'im_message_text')))
list3 = self.driver.find_elements_by_class_name("im_message_text")
list33 = list3[-1]
list4 = list33.find_element_by_tag_name("strong")
list4txt = list4.text
return list4txt
except:
print("Nothing is found")
我從這里做的是我制作另一個相同的代碼,它在開始時有一個time.sleep(1)
以給出消息出現的時間,然后我使用以下 while 循環比較這兩個代碼:
while Main.getItemsInfo1() == Main.getItemsInfo2():
print("No new messages. Try number ", count)
print(Main.getItemsInfo1(), Main.getItemsInfo2())
count += 1
到目前為止,雖然一旦有新消息代碼 output 突出顯示這兩種方法有不同的文本,它仍然沒有結束 while 循環,它繼續說沒有任何新消息。
有誰知道如何提供幫助?
您甚至不需要使用電報 web 或 selenuim,讓我們讓它更容易:
from telethon import TelegramClient, events
client = TelegramClient(PHONE_NUMBER, API_ID, API_HASH)
@client.on(events.NewMessage("chanel name"))
def new_message_listener(event):
new_message = event.message.message
media_status = event.message.media
## DO what you like with new_messsage
只要記住更改TelegramClient
中的變量,您就可以從 Telegram 網站接收 API_ID、API_HASH。
它們應該是這樣的:
api_id = 1027347
api_hash = "c0e2cfefac982659a52da625b81e2a99"
while Main.getItemsInfo1() == Main.getItemsInfo2():
print("No new messages. Try number ", count)
print(Main.getItemsInfo1(), Main.getItemsInfo2())
count += 1
當您調用 getItemsInfo1() 時,您將再次調用該方法,因此不能保證在 print 語句中獲取的值與在 while 中的值相同,因此請使用以下內容:
info1= Main.getItemsInfo1()
info2= Main.getItemsInfo2()
while info == Info2:
print("No new messages. Try number ", count)
info1= Main.getItemsInfo1()
info2= Main.getItemsInfo2()
print(info1,info2)
count += 1
上面的代碼將確保您具有相同的值,因為您將值存儲到變量然后驗證它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.