Python实现通过微信企业号发送文本消息的Class
前文《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/LinuxBashShellScriptForOps/blob/master/projects/WeChatOps/OpsDevBestPractice/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--
本文转自 urey_pp 51CTO博客,原文链接:http://blog.51cto.com/dgd2010/1837376,如需转载请自行联系原作者