赞同 0
分享

用Python脚本给企业微信发送告警消息

简介:今天遇到一个运维同事的一个python编码问题,他的python脚本发送的消息到企业微信后都是ASCII的乱码状态,中文直接不能看了。
  2020.09.22
  Bug Man
  0
  50
  172.17.0.1
  中国.上海
 
 

我是直接在我们项目里面的方法中找到的编码方式,不过这一路上确实学习了很多其他的知识,最关键的点在json.dumps(send_values, ensure_ascii=False).encode('utf8')

解决了编码问题之后python wechart.py user subject content这样运行脚本又报错了:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xc4 in position 1: invalid continuation byte

我用的是win7系统,如果是传入进来的中文必须decode('gbk')解码为UTF-8的编码,如果是文件中的中文字符就不用解码了。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import requests
import json


class WeChat:
    def __init__(self):
        self.CORPID = 'xxx'  # 企业ID,在管理后台获取
        self.CORPSECRET = 'xxx'  # 自建应用的Secret,每个自建应用里都有单独的secret
        self.AGENTID = 'xxx'  # 应用ID,在后台应用中获取

    def _get_access_token(self):
        url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
        values = {'corpid': self.CORPID,
                  'corpsecret': self.CORPSECRET,
                  }
        req = requests.post(url, params=values)
        data = json.loads(req.text)
        return data["access_token"]

    def get_access_token(self):
        try:
            with open('./access_token.conf', 'r') as f:
                t, access_token = f.read().split()
        except:
            with open('./access_token.conf', 'w') as f:
                access_token = self._get_access_token()
                cur_time = time.time()
                f.write('\t'.join([str(cur_time), access_token]))
                return access_token
        else:
            cur_time = time.time()
            if 0 < cur_time - float(t) < 7260:
                return access_token
            else:
                with open('./access_token.conf', 'w') as f:
                    access_token = self._get_access_token()
                    f.write('\t'.join([str(cur_time), access_token]))
                    return access_token

    def send_data(self, User, Subject, Content):
        send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.get_access_token()
        send_values = {
            "touser": User,
            "toparty": 2,
            "msgtype": "text",
            "agentid": self.AGENTID,
            "text": {
                "content": Subject + '\n' + Content
            },
            "safe": "0"
        }
        send_msges = json.dumps(send_values, ensure_ascii=False).encode('utf8')
        respone = requests.post(send_url, send_msges)
        respone = respone.json()
        return respone["errmsg"]


if __name__ == '__main__':
    User = '黄家辉'
    Subject = '测试告警'
    Content = '测试告警中文内容'

    wx = WeChat()
    r = wx.send_data(User, Subject, Content)
    print r

Python脚本传参使用报错

从申请企业微信到做做告警流程

使用Python脚本发送企业微信消息