Python实现通过微信企业号发送文本消息的Class

前文《Python实现获取微信企业号access_token的Class》提供了获取微信企业号的access_token,本文中的代码做实际发送文本消息。

编程要点和调用方法:

  1. 支持发送中文,核心语句“payload = json.dumps(self.data, encoding='utf-8', ensure_ascii=False)”,关键字“python json 中文”

  2. 这个Class只有一个公共方法send()。

  3. 使用方法:import这个class,然后调用send方法即可,方法参数只需要两个,给谁(多UserID用"|"隔开),内容是什么,例如:

import odbp_sendMessage
msg = odbp_sendMessage.WeiXinSendMsgClass()
msg.send("dingguodong", "Python 大魔王!")

运行效果图如下:

wKiom1etlGGiyHoBAAfIStLK3o0028.jpg

手机端效果:

IMG_8148

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--

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值