python微信聊天機(jī)器人改進(jìn)版(定時(shí)或觸發(fā)抓取天氣預(yù)報(bào)、勵(lì)志語(yǔ)錄等,向好友推送)
最近想著做一個(gè)微信機(jī)器人,主要想要實(shí)現(xiàn)能夠每天定時(shí)推送天氣預(yù)報(bào)或勵(lì)志語(yǔ)錄,勵(lì)志語(yǔ)錄要每天有自動(dòng)更新,定時(shí)或當(dāng)有好友回復(fù)時(shí),能夠隨機(jī)推送不同的內(nèi)容。于是開(kāi)始了分析思路。博主是采用了多線程群發(fā),因?yàn)槲⑿艑?duì)頻繁發(fā)送消息過(guò)快還會(huì)出現(xiàn)發(fā)送失敗的問(wèn)題,因此還要加入time.sleep(1),當(dāng)然時(shí)間根據(jù)自身情況自己定咯。本想把接入寫(xiě)詩(shī)機(jī)器人,想想自己的渣電腦于是便放棄了,感興趣的可以嘗試一下。做完會(huì)有不少收獲希望對(duì)你有幫助。
(1)我們要找個(gè)每天定時(shí)更新天氣預(yù)報(bào)的網(wǎng)站,和一個(gè)更新勵(lì)志語(yǔ)錄的網(wǎng)站。當(dāng)然如果你想更新其他內(nèi)容,相信高智商的你這些都是小意思啦。博主是隨便找了2個(gè)網(wǎng)站進(jìn)行抓取。
第一步:抓取某網(wǎng)站天氣預(yù)報(bào)信息,為我所用,因溫度氣候和生活指數(shù)在兩個(gè)頁(yè)面,于是將2個(gè)頁(yè)面的數(shù)據(jù)抓取并進(jìn)行整合:
這里抓取第一個(gè)頁(yè)面內(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
這里抓取第二頁(yè)面內(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)典唯美勵(lì)志語(yǔ)錄,為了每次發(fā)送或者回復(fù)都有信息感,博主抓取了10個(gè)數(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)開(kāi)始我們的重頭戲,博主選擇的是wxpy庫(kù),需要導(dǎo)入的庫(kù)如下:
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è)置多個(gè)的啦,博主只設(shè)置了早上:
def main():
print("程序開(kāi)始運(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ī)獲取勵(lì)志唯美語(yǔ)錄'
send_queue = Queue()
fris = bot.friends().search('') # 這里填空會(huì)向所有好友的發(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é)束")
然后,開(kāi)始向好友發(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í)間可以設(shè)置大一點(diǎn),防止微信發(fā)送頻繁,導(dǎo)致發(fā)送失敗
continue # 這里不建議加continue,依個(gè)人微信情況而定吧
send_queue.task_done()
這里開(kāi)始監(jiān)聽(tīng)消息,并向朋友回送,一定要過(guò)濾掉群消息和公眾號(hào)消息,具體為什么后面告訴你:
@bot.register()
def rcv_message(msg):
sender = str(msg.sender)
if '<MP:'in str(sender) or '<Group:' in str(sender): # 這里過(guò)濾掉群消息和公眾號(hào)消息
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ā)送錯(cuò)誤,信息:%s" % ret)
return ("主人不在所以我智商為0了,請(qǐng)嘗試下回復(fù)(唯美)隨機(jī)獲取勵(lì)志唯美語(yǔ)句")
下面接入圖靈機(jī)器人,讓實(shí)現(xiàn)智能聊天回復(fù):
def robot_tuling(text):
url = "http://www.tuling123.com/openapi/api"
api_key = "a3c47b29c497e87ab0b6e566f32" # 這里我已經(jīng)修改,需要自己申請(qǐng)一個(gè)咯
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"] == "親愛(ài)的,當(dāng)天請(qǐng)求次數(shù)已用完。":
return "主人不在所以我智商為0了,嘗試下回復(fù)(唯美)隨機(jī)獲取勵(lì)志唯美語(yǔ)句"
return result["text"]
好了,所有工作完成,看看效果,記得屏蔽了公眾號(hào),不然會(huì)有下面效果:



總結(jié)
以上所述是小編給大家介紹的python微信聊天機(jī)器人改進(jìn)版(定時(shí)或觸發(fā)抓取天氣預(yù)報(bào)、勵(lì)志語(yǔ)錄等,向好友推送),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
相關(guān)文章
Django 實(shí)現(xiàn)xadmin后臺(tái)菜單改為中文
今天小編就為大家分享一篇Django 實(shí)現(xiàn)xadmin后臺(tái)菜單改為中文,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11
python實(shí)現(xiàn)七段數(shù)碼管和倒計(jì)時(shí)效果
今天小編就為大家分享一篇python實(shí)現(xiàn)七段數(shù)碼管和倒計(jì)時(shí)效果,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11
win32com操作word之Application&Documents接口學(xué)習(xí)
這篇文章主要為大家介紹了win32com操作word之Application&Documents接口學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
python定時(shí)任務(wù)apscheduler的詳細(xì)使用教程
APScheduler的全稱是Advanced?Python?Scheduler,它是一個(gè)輕量級(jí)的?Python定時(shí)任務(wù)調(diào)度框架,下面這篇文章主要給大家介紹了關(guān)于python定時(shí)任務(wù)apscheduler的詳細(xì)使用教程,需要的朋友可以參考下2022-02-02
python超簡(jiǎn)單解決約瑟夫環(huán)問(wèn)題
這篇文章主要介紹了python超簡(jiǎn)單解決約瑟夫環(huán)問(wèn)題的方法,詳細(xì)描述的約瑟夫環(huán)問(wèn)題的描述與Python解決方法,需要的朋友可以參考下2015-05-05
在Linux命令行終端中使用python的簡(jiǎn)單方法(推薦)
下面小編就為大家?guī)?lái)一篇在Linux命令行終端中使用python的簡(jiǎn)單方法(推薦)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-01-01
Pycharm 創(chuàng)建 Django admin 用戶名和密碼的實(shí)例
今天小編就為大家分享一篇Pycharm 創(chuàng)建 Django admin 用戶名和密碼的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
基于python requests selenium爬取excel vba過(guò)程解析
這篇文章主要介紹了基于python requests selenium爬取excel vba過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08

