任務三:使用微信機器人和極光API推送消息
- 一、微信機器人推送消息
-
使用微信機器人的本質其實就是使用Web端微信,所以有不少的限制,比如 近幾個月申請的新微信號是不能登錄的 (親測證實),要注意。
-
在python中使用微信可以使用wxpy庫,也可以使用itchat庫
-
使用代碼發送消息的步驟與自己操作微信給好友發消息步驟相同。
-
- 登錄微信
-
- 找到對應好友
-
- 發送消息
-
使用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()
運行效果如下圖: