【Python撩妹合集】微信聊天機器人,推送天氣早報、睡前故事、精美圖片分享


 

  福利時間,福利時間,福利時間

  如果你還在為不知道怎么撩妹而煩惱,不知道怎么勾搭小仙女而困惑,又或者不知道怎么討女朋友歡心而長吁短嘆。

  那么不要猶豫徘徊,往下看。接下來我會分享怎么使用 Python 實現微信自動聊天,微信每日天氣早報、睡前故事及精美圖片推送。

  學會之后,迎娶白富美,走上人生巔峰就指日可待啦。(✪ω✪)

 

  不信咱先看看效果展示:

  (皮皮是我家貓的名字,所有我把命令設成這樣子的)

  

 

  

  

  

  如此貼心的舔狗,哪個小姐姐會選擇拒絕呢。

   

 

 

  目錄:

一、Python 登錄微信

二、獲取天氣早報信息

三、獲取睡前故事

四、獲取精美壁紙

五、整合數據,配置定時任務

六、自動聊天機器人(圖靈機器人)

七、Git 地址

 

一、Python 登錄微信

  Python 中有個 itchat 包,這是個開源的微信個人號接口,非常簡單就可以實現在 python 對微信的操作。

  下面貼一下基本的登錄、對話代碼

import itchat

itchat.auto_login(hotReload=True)  # 登錄,會下載二維碼給手機掃描登錄,hotReload設置為True表示以后自動登錄
itchat.send('hello my love', toUserName='filehelper') #發送信息給微信文件助手
        
friends = itchat.search_friends(name='好友昵稱')  # 獲取微信好友列表
userName = friends[0]['UserName']
itchat.send('hello my love', toUserName=userName)  # 發送信息給指定好友
        
itchat.run()  # 讓itchat一直運行

  (之后展示的代碼是對 itchat 的進行簡單封裝后的應用,可能會導致閱讀有些麻煩,見諒,文章最后面我會貼上全部的代碼 git)

  詳細了解 itchat 的應用可以看 這里

 

二、獲取天氣早報信息

  獲取每日天氣信息:

  我的天氣信息是在 阿凡達數據 中申請的免費數據接口,里面也有很多好玩有趣的數據,最好自己去注冊個賬號。 

common = Common() #這是個我自己封裝的工具類
key = 'cc186c9881b94b42b886a6d634c632' #這個我修改了 嘻嘻

# 數據提供類 class DataUtil(): # 獲取天氣信息 def getWeatherData(self, cityname): # 阿凡達數據 url = ' http://api.avatardata.cn/Weather/Query?key=' + key + '&cityname=' + cityname results = common.get(url) text = self.parseInfo_afd(results) print(text) return text # 簡單的數據修飾封裝 def parseInfo_afd(self, jsons): # 將string 轉換為字典對象 jsonData = json.loads(jsons) textInfo = '早上好,今天又是元氣滿滿的一天喲.\n' data = jsonData['result']['weather'][0]['date'] week = jsonData['result']['weather'][0]['week'] nongli = jsonData['result']['weather'][0]['nongli'] city_name = jsonData['result']['realtime']['city_name'] lowTemperature = jsonData['result']['weather'][0]['info']['dawn'][2] highTemperature = jsonData['result']['weather'][0]['info']['day'][2] weather = jsonData['result']['weather'][0]['info']['day'][1] wind = jsonData['result']['weather'][0]['info']['day'][4] textInfo = textInfo + '今天是' + data + '號\n' textInfo = textInfo + '農歷:' + nongli + ',星期' + week + '\n' textInfo = textInfo + city_name + '氣溫:' + lowTemperature + '-' + highTemperature + '度,' + weather + ' ' + wind + '\n\n' textInfo = textInfo + '穿衣指數:' + jsonData['result']['life']['info']['chuanyi'][0] + ' - ' + jsonData['result']['life']['info']['chuanyi'][1] + '\n\n' textInfo = textInfo + '運動指數:' + jsonData['result']['life']['info']['yundong'][0] + ' - ' + jsonData['result']['life']['info']['yundong'][1] + '\n\n' textInfo = textInfo + '感冒指數:' + jsonData['result']['life']['info']['ganmao'][0] + ' - ' + jsonData['result']['life']['info']['ganmao'][1] + '\n\n' textInfo = textInfo + '紫外線指數:' + jsonData['result']['life']['info']['ziwaixian'][0] + ' - ' + jsonData['result']['life']['info']['ziwaixian'][1] + '\n\n' textInfo = textInfo + 'by:小可愛的貼心秘書' + '\n\n' return textInfo

 

三、獲取睡前故事

  睡前故事的來源是出自《從你的全世界路過--張嘉佳》,這本書中都是些愛情相關的小故事。

  

  我們用 night.n 來區分每晚發送的故事。

# 提取故事的第一天
readBookStartDay = datetime.datetime(2019, 2, 17)

class DataUtil():
def getBookInfo(self, filePath): #文件路徑, radioList = [] #微信每次最多只能發送的字符是有限制的,我每25行發送一次信息 row = 0 tempInfo = textInfo = '睡前故事:張嘉佳 - 《從你的全世界路過》.\n\n' readFlag = False #是否讀取 today = datetime.datetime.now() dayCount = (today - readBookStartDay).days + 1 for line in open(filePath): if (line.find('night.' + str(dayCount)) > -1): # 開始讀數據 readFlag = True continue if (line.find('night.' + str(dayCount+1)) > -1): # 讀完一天數據結束 break if readFlag: row += 1 tempInfo += line # 微信每次最多只能發送的字符是有限制的,我每25行發送一次信息 if row == 25: radioList.append(tempInfo) tempInfo = '' row = 0 tempInfo += '\n晚安\n' + 'by:小可愛的貼心秘書' + '\n' radioList.append(tempInfo) # common.txtToMp3(radioList) #文字生成語音 發送語音 print(radioList) return radioList

 

四、獲取精美壁紙

  壁紙我們從 必應 的官網抓取,必應的官網壁紙還是比較精美的。

  至於具體的壁紙抓取 分析,相信聰明的你們肯定是知道的,我就直接貼代碼咯。

class DataUtil():
    def getBingPhoto(self, index):
        # index 對應的是 必應 index天的壁紙
        url = ' http://www.bing.com/HPImageArchive.aspx?format=js&idx=' + index + '&n=1&nc=1469612460690&pid=hp&video=1'
        html = urllib.request.urlopen(url).read().decode('utf-8')

        photoData = json.loads(html)
        # 這是壁紙的 url
        photoUrl = 'https://cn.bing.com' + photoData['images'][0]['url']
        photoReason = photoData['images'][0]['copyright']
        photoReason = photoReason.split(' ')[0]
        photo = urllib.request.urlopen(photoUrl).read()

        # 下載壁紙刀本地
        with open('./bing.jpg', 'wb') as f:
            # img = open_url(photoUrl)
            if photo:
                f.write(photo)
        print("圖片已保存")

        # 把壁紙的介紹寫到壁紙上
        # 設置所使用的字體
        font = ImageFont.truetype("simhei.ttf",35)
        imageFile = "./bing.jpg"
        im1 = Image.open(imageFile)
        # 畫圖,把壁紙的介紹寫到壁紙上
        draw = ImageDraw.Draw(im1)
        draw.text((im1.size[0]/2.5, im1.size[1]-50), photoReason, (255, 255, 255), font=font)  # 設置文字位置/內容/顏色/字體
        draw = ImageDraw.Draw(im1)  # Just draw it!
        # 另存圖片
        im1.save("./bing.jpg")

 

五、整合數據,配置定時任務

  數據都獲取到了,也登錄了微信,現在我們就需要把這些信息發送給需要的人了。

  這里需要注意的是:

  1. 微信每條信息是有長度限制的

  2. 微信在線需要單獨占用一個線程,所以發送信息需要在另一個線程執行。

  3. 定時任務的配置......想詳細了解看 這里

  

wechat = WeChat() #這里是封裝的 itchat
# 開啟微信登錄線程,需要單獨占個線程
_thread.start_new_thread(wechat.login, ( ))

# 配置定時任務
# 開啟早間天氣預報 定時任務
schedule.every().day.at("7:20").do(wechat.dailyInfo)
# 開啟睡前故事 定時任務
schedule.every().day.at("21:30").do(wechat.readStory)
while True:
    schedule.run_pending()
    time.sleep(1)

  微信登錄方法

class WeChat():

    def login(self):
        itchat.auto_login(hotReload=True)  # 登錄,會下載二維碼給手機掃描登錄,hotReload設置為True表示以后自動登錄
        itchat.send('hello my love', toUserName='filehelper') #發送信息給微信文件助手

        friends = itchat.search_friends(name='好友昵稱')  # 獲取微信好友列表
        userName = friends[0]['UserName']
        itchat.send('hello my love', toUserName=userName)  # 發送信息給指定好友

        itchat.run()  # 讓itchat一直運行

  微信每日天氣預報方法

class WeChat():
# 推送每日早報
    def dailyInfo(self):
        print('dailyInfo do')
        jiujiang = dataUtil.getWeatherData('九江')
        # wechat.sendMessage(jiujiang, 'filehelper')
        yfei = wechat.getFriend('好友昵稱')
        wechat.sendMessage(jiujiang, yfei)

  微信發送睡前故事 和 精美壁紙方法

# 推送睡前故事
    def readStory(self):
        print('readStory do')
        stroy = dataUtil.getBookInfo('./從你的全世界路過.txt')
        dataUtil.getBingPhoto('0')
        # wechat.sendMessage(stroy, 'filehelper')
        # itchat.send_image('./bing.jpg',  'filehelper')
        yfei = wechat.getFriend('好友昵稱')

        for txt in stroy:
            wechat.sendMessage(txt, yfei)

        # 發送壁紙
        itchat.send_image('./bing.jpg', toUserName=yfei)

 

六、自動聊天機器人(圖靈機器人)

   聊天機器人我們要考慮倆個問題:

  1.怎么微信自動回復信息?(itchat 提供的注解)

  2.自動回復什么內容?(調用圖靈機器人)

  第一個問題,Itchat 提供了注解,可以自動回復信息,詳細可以了解  這里

  需要注意的是,自動回復方法,不能包含在 類 中,不然無法生效。

# 聊天助手開關
OPEN_FLAG = 0
# 回復信息
@itchat.msg_register(['Text'])
def text_reply(msg):
    global OPEN_FLAG
    msgText = msg['Text']
    # print(msgText)
    if msgText == "皮皮過來":
        OPEN_FLAG = 1
        print('開啟皮皮語音助手*')
        return '開啟皮皮語音助手*'
    if msgText == "皮皮退下":
        OPEN_FLAG = 0
        print('關閉皮皮語音助手*')
        return '關閉皮皮語音助手*'
    if OPEN_FLAG == 1:
        # 為了保證在圖靈Key出現問題的時候仍舊可以回復,這里設置一個默認回復
        defaultReply = '不想說話了!' + "*"
        # 如果圖靈Key出現問題,那么reply將會是None
        reply = get_response(msg['Text']) + "*"
        # 有內容一般就是指非空或者非None,你可以用`if a: print('True')`來測試
        return reply or defaultReply

  

  第二個問題,圖靈機器人 去 這里 申請注冊就行了,聰明的你肯定會的。

  申請到了之后,只需要調用接口就好了。

KEY = '71f9d9d2dd364ad8b28bd565270176'
# 圖靈機器人
def get_response(msg):
    # 構造了要發送給服務器的數據
    apiUrl = 'http://www.tuling123.com/openapi/api'
    data = {
        'key': KEY,
        'info': msg,
        'userid': 'wechat-robot',
    }
    try:
        r = requests.post(apiUrl, data=data).json()
        return r.get('text')
    # 為了防止服務器沒有正常響應導致程序異常退出,這里用try-except捕獲了異常
    # 如果服務器沒能正常交互(返回非json或無法連接),那么就會進入下面的return
    except Exception as e:
        print('插入時發生異常' + e)
        # 將會返回一個None
        return

  大致思路就是這么簡單咯

 

七、Git 地址

  https://github.com/zwwjava/python_capture/tree/master/venv/Include/wechat

  入口文件: autoSendMessage.py

 


免責聲明!

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



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