日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python自动发微信api_调用微信API发送微信消息python脚本

發布時間:2023/12/10 python 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python自动发微信api_调用微信API发送微信消息python脚本 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

前陣子部署zabbix監控系統,做了個微信報警,下面分享下微信調API發消息的腳本。要用微信發消息,自己首先要有微信企業號,如果沒有申請也容易

準備工作:

1.申請微信企業號

2.在企業號后臺創建應用

3.關注微信企業號

腳本用Python3寫的,內容如下:

#!/usr/local/python3.5/bin/python3.5

import json

import sys

import os

import time

import urllib.request

tkapi = ‘https://qyapi.weixin.qq.com/cgi-bin/gettoken‘

msgapi = ‘https://qyapi.weixin.qq.com/cgi-bin/message/send‘

corpid = ‘微信企業號corpid‘

corpsecret = ‘微信企業號corpsecret‘

agentid = ‘微信企業號創建的應用ID‘

tokentmp = ‘token.txt‘

url = "%s?corpid=%s&corpsecret=%s" % (tkapi,corpid,corpsecret)

senduser = sys.argv[1]

msg = sys.argv[2]

nowtime = int(time.time())

def gettoken():

try:

res = urllib.request.urlopen(url)

if res.status == 200:

result = res.read()

result = str(result, encoding = "utf-8")

jresult = json.loads(result)

errcode = jresult[‘errcode‘]

if errcode == 0:

token = jresult[‘access_token‘]

token = token.strip(‘\r‘)

token = token.strip(‘\n‘)

f = open(tokentmp,‘w‘)

log = "%s:%s" % (nowtime,token)

f.write(log)

f.close()

return(‘0‘,token)

else:

return(‘1‘,‘get token fail‘)

else:

return(‘1‘,‘get token return http code error‘)

except Exception as e:

#print(Exception,":",e)

return(‘1‘,‘get token http request fail‘)

def sendmsg(token,senduser,msg):

SendMsgUrl = "%s?access_token=%s" % (msgapi,token)

data = {‘touser‘:senduser,‘msgtype‘:‘text‘,‘agentid‘:agentid,‘text‘:{‘content‘:msg}}

data = json.dumps(data)

data = data.replace(‘-n‘,‘\\n‘)

data = bytes(data,‘utf8‘)

try:

request = urllib.request.Request(SendMsgUrl)

res1 = urllib.request.urlopen(request,data)

if res1.status == 200:

result1 = res1.read()

result1 = str(result1, encoding = "utf-8")

jresult1 = json.loads(result1)

errcode1 = jresult1[‘errcode‘]

if errcode1 == 0:

return(‘0‘,errcode1)

else:

return(‘1‘,‘send msg fail‘)

else:

return(‘1‘,‘send msg return http code error‘)

except:

return(‘1‘,‘send msg http request fail‘)

if os.path.exists(tokentmp):

tk = open(tokentmp,‘r‘).readline()

tk = str(tk)

tkstrs = tk.split(‘:‘)

lasttime = int(tkstrs[0])

if nowtime - lasttime < 3600:

token = tkstrs[1]

stat = ‘0‘

else:

(stat,token) = gettoken()

else:

(stat,token) = gettoken()

if stat == ‘0‘:

(stat1,msgresult) = sendmsg(token,senduser,msg)

if stat1 == ‘0‘:

print(‘send message success‘)

else:

print(‘get token success,send message fail errinfo:‘+msgresult)

else:

print(‘get token fail errinfo:‘+token)

腳本使用方法:

python3.5 wenxin.py 消息接收人 消息內容

python3.5 wenxin.py opsfans ‘微信測試消息‘

消息內容換行符為‘-n‘python水平有限,大牛勿噴

總結

以上是生活随笔為你收集整理的python自动发微信api_调用微信API发送微信消息python脚本的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。