标签:python 微信企业号发送报警 微信企业号发送文本消息
前文《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用"|"隔开),内容是什么,例如:
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
脚本内容如下:
#!/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--
本文出自 “通信,我的最爱” 博客,请务必保留此出处http://dgd2010.blog.51cto.com/1539422/1837376
标签:python 微信企业号发送报警 微信企业号发送文本消息
原文地址:http://dgd2010.blog.51cto.com/1539422/1837376