前文《Python实现获取微信企业号access_token的Class》提供了获取微信企业号的access_token,本文中的代码做实际发送文本消息。
编程要点和调用方法:
支持发送中文,核心语句“payload = json.dumps(self.data, encoding='utf-8', ensure_ascii=False)”,关键字“python json 中文”
这个Class只有一个公共方法send()。
使用方法:import这个class,然后调用send方法即可,方法参数只需要两个,给谁(多UserID用"|"隔开),内容是什么,例如:
1
2
3
import odbp_sendMessage
msg = odbp_sendMessage.WeiXinSendMsgClass()
msg.send("dingguodong", "Python 大魔王!")
运行效果图如下:
手机端效果:
Python脚本内容可以从github上获取:https://github.com/DingGuodong/L ... odbp_sendMessage.py
脚本内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""
Created by PyCharm.
File: LinuxBashShellScriptForOps:odbp_sendMessage.py
User: Guodong
Create Date: 2016/8/12
Create Time: 14:49
"""
import odbp_getToken
class WeiXinSendMsgClass(object):
def __init__(self):
self.access_token = odbp_getToken.WeiXinTokenClass().get()
self.to_user = ""
self.to_party = ""
self.to_tag = ""
self.msg_type = "text"
self.agent_id = 2
self.content = ""
self.safe = 0
self.data = {
"touser": self.to_user,
"toparty": self.to_party,
"totag": self.to_tag,
"msgtype": self.msg_type,
"agentid": self.agent_id,
"text": {
"content": self.content
},
"safe": self.safe
}
def send(self, to_user, content):
if to_user is not None and content is not None:
self.data['touser'] = to_user
self.data['text']['content'] = content
else:
print
raise RuntimeError
import requests
import json
url = "https://qyapi.weixin.qq.com/cgi-bin/message/send"
querystring = {"access_token": self.access_token}
payload = json.dumps(self.data, encoding='utf-8', ensure_ascii=False)
headers = {
'content-type': "application/json",
'cache-control': "no-cache",
}
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
return_content = json.loads(response.content)
if return_content["errcode"] == 0 and return_content["errmsg"] == "ok":
print "Send successfully! %s " % return_content
else:
print "Send failed! %s " % return_content
tag:python,微信企业号发送报警,微信企业号发送文本消息
--end--
运维网声明
1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网 享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com