时间:2022-05-06 09:21:26 | 栏目:Python代码 | 点击:次
本文将介绍如何使用python3给企业微信发送消息。我的环境是linux + python3.6.10。
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/8/20 上午12:42 # @Author : wangying # @Site : # @File : 企业微信.py # @Software: PyCharm #!/root/.virtualenvs/wechat/bin/python # usage: send message via wechat import requests, sys, json import urllib3 urllib3.disable_warnings() ###填写参数### # Corpid是企业号的标识 Corpid = "ww32a580fceb30f350" # Secret是管理组凭证密钥 Secret = "QyBTbg1QL9lmNwaErqv1DMV0Y_G3lZre268E0hpTDqk" # 应用ID Agentid = "1000004" # token_config文件放置路径 Token_config = r'/tmp/zabbix_wechat_config.json' ###下面的代码都不需要动### def GetTokenFromServer(Corpid, Secret): """获取access_token""" Url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken" Data = { "corpid": Corpid, "corpsecret": Secret } r = requests.get(url=Url, params=Data, verify=False) print(r.json()) if r.json()['errcode'] != 0: return False else: Token = r.json()['access_token'] file = open(Token_config, 'w') file.write(r.text) file.close() return Token def SendMessage(Partyid, Subject, Content): """发送消息""" # 获取token信息 try: file = open(Token_config, 'r') Token = json.load(file)['access_token'] file.close() except: Token = GetTokenFromServer(Corpid, Secret) # 发送消息 Url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s" % Token Data = { "toparty": Partyid, "msgtype": "text", "agentid": Agentid, "text": {"content": Subject + '\n' + Content}, "safe": "0" } r = requests.post(url=Url, data=json.dumps(Data), verify=False) # 如果发送失败,将重试三次 n = 1 while r.json()['errcode'] != 0 and n < 4: n = n + 1 Token = GetTokenFromServer(Corpid, Secret) if Token: Url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s" % Token r = requests.post(url=Url, data=json.dumps(Data), verify=False) print(r.json()) return r.json() if __name__ == '__main__': # 部门id Partyid = '20' # 消息标题 Subject = '自应用程序代码测试' # 消息内容 Content = 'str(sys.argv[3])' Status = SendMessage(Partyid, Subject, Content) print(Status)
需要修改的地方,其中Corpid,Secret,Agentid我会在后面的截图指出来要填的值。
下行是linux环境下python3的可执行路径,如果是windows,那么这行就不需要,只要将python的路径加入到path即可
#!/root/.virtualenvs/wechat/bin/python
# Corpid是企业ID
Corpid = "ww34d7fed41a8d5dxx"
# Secret是管理组凭证密钥
Secret = "8QwzOi0xCvbp1ZnCbnQJ1d6uEIv-Lrbcjp93UrHFxxx"
# Agentid是应用ID
Agentid = "1000002"
# Token_config里面存放token信息,这个自己随便填就行,只要自己有写的权限
Token_config = r'/tmp/zabbix_wechat_config.json'
创建应用
Agentid,Secret就出来了
这个就是脚本中的Corpid
我这个python脚本是通过部门id进行群体发送,所以这个部门id到后面会有用。
直接运行:python manage.py runserver