微信场景分享

在培训过程中,如果遇到技术口人比较多的情况,课程进度比较快,微信自动发送消息的场景其实在这种情况比较适合分享。
场景包括 Python 扩展包的引入以及全局函数的使用。

from __future__ import unicode_literals
from threading import Timer
from wxpy import *
import requests
import time

# 确认客户端
bot = Bot()


# 从金山词霸网站获取信息
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(u'申水')[0]
        my_friend.send(contents[0])
        my_friend.send(contents[1])
        my_friend.send(u"Have a good one!")
        # 每86400秒(1天),发送1次
        t = Timer(86400, send_news)
        my_friend.send("I'm a robot'")
        t = Timer(30, send_news())
        t.start()
    except:

        # 你的微信名称,不是微信帐号。
        my_friend = bot.friends().search('申水')[0]
        my_friend.send(u"今天消息发送失败了")



if __name__ == "__main__":
       send_news()
 

以上代码内容简单对着自己的实际情况简单修改即可复用。
以下是 wxpy 包的 doc 地址,有兴趣大家可以进一步进行研究。
https://wxpy.readthedocs.io/zh/latest/chats.html