1. 程式人生 > >Python中使用wxpy定時機器人給微信好友傳送每日一文

Python中使用wxpy定時機器人給微信好友傳送每日一文

效果

前言

愛詞霸每日一文API

http://open.iciba.com/dsapi/

我們要獲取的就是content以及note的內容

實現

安裝庫

開啟cmd,輸入:

pip install wxpy

然後再輸入:

pip install requests

這裡已經安裝過

程式碼

開啟ILE,新建檔案bot.py

from __future__ import unicode_literals
from threading import Timer
from wxpy import *
import requests
import random
bot = Bot()
# linux執行登陸請呼叫下面的這句
#bot = Bot(console_qr=2,cache_path="botoo.pkl")
def get_news():
 
    """獲取金山詞霸每日一句,英文和翻譯"""
    url = "http://open.iciba.com/dsapi/"
    r = requests.get(url)
    content = r.json()['content']
    note = r.json()['note']
    return content, note
 
def send_news():
    try:
        contents = get_news()
        # 你朋友的微信名稱,不是備註,也不是微信帳號。
        my_friend = bot.friends().search('朋友微信名稱')[0]
        my_friend.send(contents[0])
        my_friend.send(contents[1])
        my_friend.send(u"晚安")
        # 每86400秒(1天),傳送1次
        t = Timer(86400, send_news)
        # 為了防止時間太固定,於是決定對其加上隨機數
        ran_int = random.randint(0,100)
        t = Timer(86400+ran_int,send_news)
 
        t.start()
    except:
 
        # 你的微信名稱,不是微信帳號。
        my_friend = bot.friends().search('你的微信名')[0]
        my_friend.send(u"今天訊息傳送失敗了")
 
if __name__ == "__main__":
    send_news()

執行

儲存程式碼並按F5執行程式碼,此時會彈出掃描二維碼登入網頁版問微信的照片,用手機微信掃描並登入,此時會將電腦端微信擠下線。

然後就能傳送訊息了。

也可以將上面的程式碼進行修改,將時間設定為更短,比如30秒

t = Timer(30, send_news)
t.start()

但是因為愛詞霸的介面只有一天一條,所以可以自己爬取別的資料,原理一樣。