http://chenx1242.blog.51cto.com/10430133/1954634 文章里面有一个python脚本可以用来给微信企业号发信息,如果你不喜欢那篇文章里面“title+content”的样式,可以使用如下的脚本:
#coding:utf-8
import urllib2
import json
import sys
def getMsg():
#为了避免发送中文消息报错,使用utf8方式编码
reload(sys)
sys.setdefaultencoding('utf8')
#这个方法生成想要发送的消息
msg = '''
小伙,你渴望力量么?
不!我渴望奶子!
'''
return msg
if __name__ == '__main__':
#微信公众号上应用的CropID和Secret
CropID='这里填写Cropid值'
Secret='这里填写应用对应的secret'
#获取access_token
GURL="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s" % (CropID,Secret)
result=urllib2.urlopen(urllib2.Request(GURL)).read()
dict_result = json.loads(result)
Gtoken=dict_result['access_token']
#生成通过post请求发送消息的url
PURL="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s" % Gtoken
#企业号中的应用id
Agentid="这里填写应用的agentid"
#部门成员id,微信接收者,默认为@all,即所有人,如果只需要几个人,就用“|”隔开
UserID="@all"
#生成post请求信息
post_data = {}
msg_content = {}
msg_content['content'] = getMsg()
post_data['touser'] = UserID
post_data['msgtype'] = 'text'
post_data['agentid'] = Agentid
post_data['text'] = msg_content
post_data['safe'] = '0'
#由于字典格式不能被识别,需要转换成json然后在作post请求
#注:如果要发送的消息内容有中文的话,第三个参数一定要设为False
json_post_data = json.dumps(post_data,False,False)
#通过urllib2.urlopen()方法发送post请求
request_post = urllib2.urlopen(PURL, json_post_data)
#read()方法查看请求的返回结果
print request_post.read()
执行效果如下:
在手机设备端获得的效果如下:
这里有几个地方要注意一下:
1)如果执行脚本提示 {"errcode":301002,"errmsg":"not allow operate another agent with this accesstoken."},这个说明应用的agentid与Secret 不符合,导致无法授权到对应的应用;
2)详细说明一下脚本里面的几个值:
参数 | 必须 | 说明 |
touser | 否 | UserID列表(消息接收者,多个接收者用‘|’分隔)。特殊情况:指定为@all,则向关注该企业应用的全部成员发送 |
toparty | 否 | PartyID列表,多个接受者用‘|’分隔。当touser为@all时忽略本参数,这个参数在2017年6月份之后新的企业号里面已经废除掉了。 |
totag | 否 | TagID列表,多个接受者用‘|’分隔。当touser为@all时忽略本参数 |
msgtype | 是 | 消息类型,此时固定为:text |
agentid | 是 | 企业应用的id,整型。可在应用的设置页面查看 |
content | 是 | 消息内容 |
safe | 否 | 表示是否是保密消息,0表示否,1表示是,默认0 |
感谢 !
转载于:https://blog.51cto.com/chenx1242/1954659