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()

但是因为爱词霸的接口只有一天一条,所以可以自己爬取别的数据,原理一样。

猜你喜欢

转载自blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/84644179