老鱼Python数据分析——篇十八:消息推送(二)

任务三:使用微信机器人和极光API推送消息

一、微信机器人推送消息

使用微信机器人的本质其实就是使用Web端微信,所以有不少的限制,比如 近几个月申请的新微信号是不能登录的 (亲测证实),要注意。

在python中使用微信可以使用wxpy库,也可以使用itchat库

使用代码发送消息的步骤与自己操作微信给好友发消息步骤相同。

  1. 登录微信
  1. 找到对应好友
  1. 发送消息

使用wxpy库的完整代码如下:

from wxpy import Bot
from threading import Timer
from service.tq_message import get_tq
# 推送天气到微信
def push_tq_to_wx(name="四维鱼"):
    try:
        # 初始化机器人(默认windows系统)
        bot = Bot()
        # 判断操作系统
        systype = str(sys.platform)
        if(systype.find("win")<0):
            bot = Bot(console_qr=2, cache_path="botoo.pkl")
        # 得到当前天气
        msg = get_tq()
        # 给好友发送消息
        friend = bot.friends().search(name)[0]
        friend.send(msg)
    except:
        print("今天的天气发送失败!")

if __name__ == "__main__":
	push_tq_to_wx()

运行程序会弹出一个二维码,使用微信扫描登录
使用微信扫描登录
登录之后效果如下图:
在这里插入图片描述
: 使用itchat库的完整代码如下:

import sys, itchat
from threading import Timer
from service.tq_message import get_tq
from itchat.content import *

# 登录时的回调函数
def inwx():
    print("登录微信")
# 退出时的回调函数
def outwx():
    print("退出微信")
# 保持登录
def wx_login():
    # 登录
    itchat.auto_login(hotReload=True, loginCallback=inwx, exitCallback=outwx)
    # 保持运行
    # itchat.run()
# 使用itchat发送消息
def tomsg(username="filehelper"):
    msg = get_tq()
    print(msg)
    touser = username
    if(username!="filehelper"):
        touser = itchat.search_friends(name=username)[0]["UserName"]
    itchat.send_msg(msg, toUserName=touser)
	# 每10秒发送一次
    t = Timer(10, tomsg, ["四维鱼"])
    t.start()

if __name__ == "__main__":
    wx_login()
    tomsg("四维鱼")

结果如下图所示:
在这里插入图片描述

二、极光API推送消息
1.使用极光API首先需要到极光官网注册账号,开通平开发平台的推送服务(免费申请)。
2.登录后的界面
在这里插入图片描述
3.进入开发者平台,创建应用
在这里插入图片描述
4.注意下图红框中的两个数据
在这里插入图片描述
5.配置完成后,需要扫描二维码下载JPushSDK的APP
6.其他的设置,大家自行花5分钟左右了解就OK了
完整代码如下:
import jpush
from service.tq_message import *
from jpush import common

# 初始化推送对象
key = "xxxxxxxxxxxxxxxxxxxxxxxxx"    # 对应AppKey 
secret = "f13a9f23174eaa8a91bd86d7"  # 对应Master Secret
mypush = jpush.JPush(key, secret)
mypush.set_logging("DEBUG")

def push_tq():
    global mypush
    push = mypush.create_push()
    push.audience = jpush.all_  # 接收者为所有人
    push.notification = jpush.notification(get_tq())   # 内容为当前天气
    push.platform = jpush.all_  # 接收平台为所有
    try:
        rep = push.send()
    except common.Unauthorized: # AppKey,Master Secret 错误
        raise common.Unauthorized("Unauthorized")
    except common.APIConnectionException:   # 包含错误的信息:比如超时,无网络等情况
        raise common.APIConnectionException("conn error")
    except common.JPushFailure: # 请求出错,参考业务返回码
        print("JPushFailure")
    except:
        print("Exception")

if __name__ == "__main__":
    push_tq()

运行效果如下图:
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章