python微信聊天機(jī)器人改進(jìn)版(定時或觸發(fā)抓取天氣預(yù)報、勵志語錄等,向好友推送)
最近想著做一個微信機(jī)器人,主要想要實(shí)現(xiàn)能夠每天定時推送天氣預(yù)報或勵志語錄,勵志語錄要每天有自動更新,定時或當(dāng)有好友回復(fù)時,能夠隨機(jī)推送不同的內(nèi)容。于是開始了分析思路。博主是采用了多線程群發(fā),因?yàn)槲⑿艑︻l繁發(fā)送消息過快還會出現(xiàn)發(fā)送失敗的問題,因此還要加入time.sleep(1),當(dāng)然時間根據(jù)自身情況自己定咯。本想把接入寫詩機(jī)器人,想想自己的渣電腦于是便放棄了,感興趣的可以嘗試一下。做完會有不少收獲希望對你有幫助。
(1)我們要找個每天定時更新天氣預(yù)報的網(wǎng)站,和一個更新勵志語錄的網(wǎng)站。當(dāng)然如果你想更新其他內(nèi)容,相信高智商的你這些都是小意思啦。博主是隨便找了2個網(wǎng)站進(jìn)行抓取。
第一步:抓取某網(wǎng)站天氣預(yù)報信息,為我所用,因溫度氣候和生活指數(shù)在兩個頁面,于是將2個頁面的數(shù)據(jù)抓取并進(jìn)行整合:
這里抓取第一個頁面內(nèi)容,為溫度,風(fēng)向,日期,隨便把第二天天氣的也一并抓取了:
def get_content(self, html_str): html = etree.HTML(html_str) weather_ts = html.xpath("http://div[@id='7d']/ul") today_w = '' tomorrow_w = '' for weather_t in weather_ts: today_w += weather_t.xpath("./li[1]/h1/text()")[0] + ' ' today_w += weather_t.xpath("./li[1]/p[1]/text()")[0] + ' ' today_w += weather_t.xpath("./li[1]/p[2]/i/text()")[0] + ' ' today_w += '風(fēng)向' + weather_t.xpath("./li[1]/p[3]/i/text()")[0] tomorrow_w += weather_t.xpath("./li[2]/h1/text()")[0] + ' ' tomorrow_w += weather_t.xpath("./li[2]/p[1]/text()")[0] + ' ' tomorrow_w += '風(fēng)向' + weather_t.xpath("./li[2]/p[3]/i/text()")[0] all_w = today_w + '--' + tomorrow_w return all_w
這里抓取第二頁面內(nèi)容,包括穿衣指數(shù),紫外線指數(shù):
def get_content1(self, html_str): html = etree.HTML(html_str) living_ins =html.xpath("http://div[@class='livezs']/ul") today_living = '' for living_in in living_ins: today_living += living_in.xpath("./li[1]/span/text()")[0] today_living += living_in.xpath("./li[1]/em/text()")[0] + ':' today_living += living_in.xpath("./li[1]/p/text()")[0] + ' ' today_living += living_in.xpath("./li[2]/a/em/text()")[0] + ' ' today_living += living_in.xpath("./li[2]/a/p/text()")[0] + ' ' today_living += living_in.xpath("./li[3]/em/text()")[0] + ':' today_living += living_in.xpath("./li[3]/p/text()")[0] + ' ' today_living += living_in.xpath("./li[4]/a/em/text()")[0] + ' ' today_living += living_in.xpath("./li[4]/a/p/text()")[0] + ' ' today_living += living_in.xpath("./li[6]/em/text()")[0] + ':' today_living += living_in.xpath("./li[6]/p/text()")[0] return today_living
第二步:抓取某網(wǎng)經(jīng)典唯美勵志語錄,為了每次發(fā)送或者回復(fù)都有信息感,博主抓取了10個數(shù)據(jù),并進(jìn)行隨機(jī)返回:
def Soul(): url = 'http://www.59xihuan.cn/' headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)"} res = requests.get(url, headers=headers).content html = etree.HTML(res) soul_sen = html.xpath("http://div[@class='mLeft']") soul_dict = {} for soul_s in soul_sen: soul_dict[1] = soul_s.xpath('./div[1]/div[2]/div[2]/text()')[0].strip() soul_dict[2] = soul_s.xpath('./div[2]/div[2]/div[2]/text()')[0].strip() soul_dict[3] = soul_s.xpath('./div[3]/div[2]/div[2]/text()')[0].strip() soul_dict[4] = soul_s.xpath('./div[4]/div[2]/div[2]/text()')[0].strip() soul_dict[5] = soul_s.xpath('./div[5]/div[2]/div[2]/text()')[0].strip() soul_dict[6] = soul_s.xpath('./div[6]/div[2]/div[2]/text()')[0].strip() soul_dict[7] = soul_s.xpath('./div[7]/div[2]/div[2]/text()')[0].strip() soul_dict[8] = soul_s.xpath('./div[8]/div[2]/div[2]/text()')[0].strip() soul_dict[9] = soul_s.xpath('./div[9]/div[2]/div[2]/text()')[0].strip() soul_dict[10] = soul_s.xpath('./div[10]/div[2]/div[2]/text()')[0].strip() i = random.randint(1,10) return soul_dict[i]
(2)開始我們的重頭戲,博主選擇的是wxpy庫,需要導(dǎo)入的庫如下:
import time import json import requests import datetime import threading from queue import Queue import schedule import wxpy from weather import WeatherSpider from soul import Soul bot = wxpy.Bot(cache_path=True)
現(xiàn)在先設(shè)置定時器,你可以設(shè)置多個的啦,博主只設(shè)置了早上:
def main(): print("程序開始運(yùn)行...") schedule.every().day.at("10:01").do(send) while True: schedule.run_pending() time.sleep(1)
接著,我們先獲取抓取內(nèi)容,微信好友數(shù)據(jù),引入創(chuàng)建多線程:
def send(): wea_ls = '早上好,今天又是元?dú)鉂M滿的一天\n' + WeatherSpider('101271610').run() +'您可以:'+ '\n回復(fù)"成都"獲取成都天氣\n回復(fù)"唯美"隨機(jī)獲取勵志唯美語錄' send_queue = Queue() fris = bot.friends().search('') # 這里填空會向所有好友的發(fā)送,或者填你想要單獨(dú)發(fā)送的人 for fri in fris: send_queue.put(fri) t_list = [] for i in range(3): t_msend = threading.Thread(target=more_thread, args=(send_queue, wea_ls)) t_list.append(t_msend) for t in t_list: t.setDaemon(True) #把子線程設(shè)置為守護(hù)線程,該線程不重要主線程結(jié)束,子線程結(jié)束 t.start() for q in [send_queue]: q.join() #讓主線程等待阻塞,等待隊(duì)列的任務(wù)完成之后再完成 print("主線程結(jié)束")
然后,開始向好友發(fā)送數(shù)據(jù):
def more_thread(send_queue, wea_ls): while True: try: friend = send_queue.get() friend.send(wea_ls) print("發(fā)送成功,a:",friend) except Exception as ret: time.sleep(1) # 如果你發(fā)送的好友很多,時間可以設(shè)置大一點(diǎn),防止微信發(fā)送頻繁,導(dǎo)致發(fā)送失敗 continue # 這里不建議加continue,依個人微信情況而定吧 send_queue.task_done()
這里開始監(jiān)聽消息,并向朋友回送,一定要過濾掉群消息和公眾號消息,具體為什么后面告訴你:
@bot.register() def rcv_message(msg): sender = str(msg.sender) if '<MP:'in str(sender) or '<Group:' in str(sender): # 這里過濾掉群消息和公眾號消息 return now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') # print(now) recv_save = '' rev_save = '發(fā)送人:'+ sender +" 內(nèi)容:"+ msg.text + ' ' + now print(rev_save) with open('wechat.md','a') as f: # 這里我們要把朋友發(fā)送的消息進(jìn)行保存,方便查看以免遺漏重要消息 f.write(rev_save) f.write('\n') if msg.text == '成都': wea_cd = '成都' + WeatherSpider('101270101').run() return wea_cd elif msg.text == '唯美': return Soul() else: try: return robot_tuling(msg.text) except Exception as ret: fri_me = bot.friends().search('virtual')[0] fri_me.send("發(fā)送錯誤,信息:%s" % ret) return ("主人不在所以我智商為0了,請嘗試下回復(fù)(唯美)隨機(jī)獲取勵志唯美語句")
下面接入圖靈機(jī)器人,讓實(shí)現(xiàn)智能聊天回復(fù):
def robot_tuling(text): url = "http://www.tuling123.com/openapi/api" api_key = "a3c47b29c497e87ab0b6e566f32" # 這里我已經(jīng)修改,需要自己申請一個咯 payload = { "key": api_key, "info": text, } rec = requests.post(url, data=json.dumps(payload)) result = json.loads(rec.content) # print(result["text"]) if result["text"] == "親愛的,當(dāng)天請求次數(shù)已用完。": return "主人不在所以我智商為0了,嘗試下回復(fù)(唯美)隨機(jī)獲取勵志唯美語句" return result["text"]
好了,所有工作完成,看看效果,記得屏蔽了公眾號,不然會有下面效果:
總結(jié)
以上所述是小編給大家介紹的python微信聊天機(jī)器人改進(jìn)版(定時或觸發(fā)抓取天氣預(yù)報、勵志語錄等,向好友推送),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
Python網(wǎng)絡(luò)爬蟲四大選擇器用法原理總結(jié)
這篇文章主要介紹了Python網(wǎng)絡(luò)爬蟲四大選擇器用法原理總結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-06-06python中dot函數(shù)運(yùn)算過程總結(jié)
dot函數(shù)為numpy庫下的一個函數(shù),主要用于矩陣的乘法運(yùn)算,其中包括:向量內(nèi)積、多維矩陣乘法和矩陣與向量的乘法,下面這篇文章主要給大家介紹了關(guān)于python中dot函數(shù)運(yùn)算過程的相關(guān)資料,需要的朋友可以參考下2022-09-09淺析Python中壓縮zipfile與解壓縮tarfile模塊的使用
Python?提供了兩個標(biāo)準(zhǔn)庫模塊來處理文件的壓縮和解壓縮操作:zipfile和tarfile,本文將分享?這兩個模塊的使用方法,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-10-10Python實(shí)現(xiàn)雙因素驗(yàn)證2FA的示例代碼
雙因素認(rèn)證(2FA)作為額外安全層為賬號登錄添加了第二層身份驗(yàn)證。確保賬號持有人是可以訪問數(shù)字身份的唯-用戶。如果不使用雙因表認(rèn)證,企業(yè)將承擔(dān)巨大的安全風(fēng)險。本文將用Python實(shí)現(xiàn)雙因素驗(yàn)證2FA,需要的可以參考一下2022-07-07