python微信聊天機器人改進版,定時或觸發抓取天氣預報、勵志語錄等,向好友推送


  最近想着做一個微信機器人,主要想要實現能夠每天定時推送天氣預報或勵志語錄,勵志語錄要每天有自動更新,定時或當有好友回復時,能夠隨機推送不同的內容。於是開始了分析思路。博主是采用了多線程群發,因為微信對頻繁發送消息過快還會出現發送失敗的問題,因此還要加入time.sleep(1),當然時間根據自身情況自己定咯。本想把接入寫詩機器人,想想自己的渣電腦於是便放棄了,感興趣的可以嘗試一下。做完會有不少收獲希望對你有幫助。

  (1)我們要找個每天定時更新天氣預報的網站,和一個更新勵志語錄的網站。當然如果你想更新其他內容,相信高智商的你這些都是小意思啦。博主是隨便找了2個網站進行抓取。

  第一步:抓取某網站天氣預報信息,為我所用,因溫度氣候和生活指數在兩個頁面,於是將2個頁面的數據抓取並進行整合:

  這里抓取第一個頁面內容,為溫度,風向,日期,隨便把第二天天氣的也一並抓取了:

def get_content(self, html_str):
        html = etree.HTML(html_str) weather_ts = html.xpath("//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 += '風向' + 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 += '風向' + weather_t.xpath("./li[2]/p[3]/i/text()")[0] all_w = today_w + '--' + tomorrow_w
     return all_w

  這里抓取第二頁面內容,包括穿衣指數,紫外線指數:

    def get_content1(self, html_str):
        html = etree.HTML(html_str) living_ins =html.xpath("//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

  第二步:抓取某網經典唯美勵志語錄,為了每次發送或者回復都有信息感,博主抓取了10個數據,並進行隨機返回:

def Soul(): html = etree.HTML(res) soul_sen = html.xpath("//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庫,需要導入的庫如下:

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)

  現在先設置定時器,你可以設置多個的啦,博主只設置了早上:

 schedule.every().day.at("10:01").do(send) while True: schedule.run_pending() time.sleep(1)

  接着,我們先獲取抓取內容,微信好友數據,引入創建多線程:

def send():

    wea_ls = '早上好,今天又是元氣滿滿的一天\n' + WeatherSpider('101271610').run() +'您可以:'+ '\n回復"成都"獲取成都天氣\n回復"唯美"隨機獲取勵志唯美語錄' send_queue = Queue() fris = bot.friends().search('') # 這里填空會向所有好友的發送,或者填你想要單獨發送的人 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)  t.start() for q in [send_queue]: q.join() print("主線程結束")

 

  然后,開始向好友發送數據:

def more_thread(send_queue, wea_ls):
    while True: try: friend = send_queue.get() friend.send(wea_ls) print("發送成功,a:",friend) except Exception as ret: time.sleep(1) # 如果你發送的好友很多,時間可以設置大一點,防止微信發送頻繁,導致發送失敗 continue # 這里不建議加continue,依個人微信情況而定吧   send_queue.task_done()

  這里開始監聽消息,並向朋友回送,一定要過濾掉群消息和公眾號消息,具體為什么后面告訴你:

@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 = '發送人:'+ sender +" 內容:"+ msg.text + ' ' + now
    print(rev_save)
    with open('wechat.md','a') as f:  # 這里我們要把朋友發送的消息進行保存,方便查看以免遺漏重要消息
        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("發送錯誤,信息:%s" % ret)
            return ("主人不在所以我智商為0了,請嘗試下回復(唯美)隨機獲取勵志唯美語句") 

  下面接入圖靈機器人,讓實現智能聊天回復:

def robot_tuling(text):
    url = "http://www.tuling123.com/openapi/api"
    api_key = "a3c47b29c497e87ab0b6e566f32"   # 這里我已經修改,需要自己申請一個咯
    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"] == "親愛的,當天請求次數已用完。":
        return "主人不在所以我智商為0了,嘗試下回復(唯美)隨機獲取勵志唯美語句"
    return result["text"]

 

   好了,所有工作完成,看看效果,記得屏蔽了公眾號,不然會有下面效果:

 

 

 

 

 

 

關注公眾號「互聯網專欄」,后台回復:wechat,獲取本文全套代碼!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM