Enterprise WeChat sends messages--Python

Enterprise WeChat internal message push——Python

I have some automated tasks, the execution results of these automated tasks, both success and failure are sent by email. But the email tool is a bit formal, after all, I just want a notification. Is there a way to receive notifications using WeChat?

I remember that there is a server sauce for WeChat, but it seems to be charged (there are more restrictions for free)
. In fact, individuals can also register a corporate WeChat without the need for business license certification. However, there are some more advanced functions that need to be authenticated with real corporate information, but those functions are not currently available.

Preparation:

    Go to the official website of Enterprise WeChat and register an enterprise; log in the background of Enterprise WeChat, create a "self-built" application, and obtain the three necessary parameters of enterprise ID, agentid, and secret; create multiple test accounts in the address book of Enterprise WeChat; Install the "Enterprise WeChat" APP on the mobile phone, log in to Enterprise WeChat with a test account, and prepare to receive messages.

Program code :

    Work WeChat provides an API development interface, which interacts with the work WeChat background through the GET and POST methods of HTTPS, and completes the operations of obtaining tokens, sending data, and obtaining data.

    The Python code mainly uses the requests library to simply encapsulate the enterprise WeChat API, simulate the GET and POST operations of https, and send enterprise WeChat messages to specified users.

When learning and developing internal applications of enterprise WeChat, I encountered many problems, such as calling api, sending POST requests, POST requests to upload files, and many other problems.

How to register enterprise WeChat?
Create enterprise WeChat application

 

 Click in to view the information, and record several key ids

  • AgentId (each application has a unique agentid) 
  • Secret (secret is the "key" used to ensure data security in enterprise applications. Each application has an independent access key. In order to ensure data security, the secret must not be leaked)

Acquisition of access_token

When using the API of Enterprise WeChat, you must first know the value of the access_token of the application you have developed. We can get the value of access_token through GET request.

access_token is a special id, which must be obtained after calling the interface. ta is time-sensitive and must be obtained again after it expires. See: https://developer.work.weixin.qq.com/document/path/91039

#需要注意的是,在Python中发送POST、GET等请求需要在前面加上requests库,
#还有就是处理字符串的时候需要使用到json库。

import requests
import json

corpid="XXXXXXXXX" #企业id值
corpsecret="XXXXXXXXXXXX" #应用secret值
 
#获取access_token
def get_access_token():
    get_act_url="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={}&corpsecret={}".format(corpid,corpsecret)
    act_res=requests.get(url=get_act_url).json()
    access_token=act_res["access_token"]
    return access_token

Among them, corpid is the company id, which can be seen in the background of the enterprise WeChat web page in "My Company" --> "Company Information" --> "Company ID".

The code is as follows:
1. Create a new config.py file , which is mainly used to store some relatively fixed parameters. For example: who do I want to send to, what is his department, which app to use to send, etc.

access_token='XXXXXXXXXXXXXXXXXXXXXXX'
touser="XXXXXXXXXXXXXXX"# 多个用户用|隔开
toparty="1"# 多个部门用|隔开
totag="1"# 多个标签用|隔开
agentid_ceshi1=1000002# 应用id,可以在应用的设置页面查看,一个应用对应一个agentid
type_image = "image"# 媒体文件类型,分别有图片(image)、语音(voice)、视频(video),普通文件(file)

 2. Create a new access_token.py file

import requests
import config

url = f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={config.cropid}&corpsecret={config.secretid}'

r = requests.get(url)
print(r.json())

 3. Create a new send_text.py file

import requests
import json
import faker
from work_wechat import config # 我在work_wechat这个文件夹下面新建的文件
fk = faker.Faker()


url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={config.access_token}&random=69152"
# python的json可以编码解码
# json.loads():json格式的字符串------------>字典
# json.dumps():字典转---------------------->json格式的字符串
payload = json.dumps({
   "touser": config.touser,
   "toparty": config.toparty,
   "totag": config.totag,
   "msgtype": "text",
   "agentid": config.agentid_ceshi1,
   "text": {
      "content": "已备份成功2,请查收!"
   },
   "safe": 0,
   "enable_id_trans": 0,
   "enable_duplicate_check": 0
})
headers = {
   'User-Agent': fk.user_agent(),
   'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)

 Instructions:
touser: to whom to
party toparty: which department
totag: label (the label defined when the enterprise WeChat manages employees)
agentid: the AgentId that was written down in the notebook above,
the meaning of each parameter, see: https ://developer.work.weixin.qq.com/document/path/90665
4. Run the send_text.py file ,
and then open the enterprise WeChat on the mobile phone (I sent a few, so on my own mobile phone received)

 Implementation of sending text messages

#发送文本消息
def send_text_message(message):
    send_text_url="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}".format(get_access_token())
    data={
        "touser" : "@all", #接收消息的用户
        "msgtype" : "text", #消息类型
        "agentid" : 1000002, #应用id
        "text" : {
            "content" : message #消息内容
            },
        "safe":0, #0为公开信息,1为保密信息
        }
    text_message_res=requests.post(url=send_text_url,data=json.dumps(data)).json()
    return text_message_res

示例:
send_text_message("你好,开发者") #在括号中填入你要发送的消息,一定要加上单引号或双引号,因为这是字符串
#这里是支持使用转义符的

If the errcode in the return value is 0, it means the message is sent successfully. If the sending fails, you can open the website in the return value, and the website will tell you the possible reasons for the sending failure according to your error code.

agentid is the application id, which can be found on the application details interface.

The "touser" in the dictionary data refers to the user id who receives the message, and filling in "@all" means that all users of this application can receive the message. If you want to send a message to a specified user, you need to fill in the user id, separated by "|".

Example:

"touser" : "xiaozhang|xiaowang|xiaoli|xiaoming"
user id view method:

Click the three dots to the right of the user in the address book and select Edit

 On the editing page, you can see the user's account, that is, the user id, and the administrator can also modify the user id

 In addition to using the user id, you can also use the department id and label to perform targeted push. The usage method is the same as above, so I won’t go into details here.

The parameter table is attached, that is, the content of the dictionary data, which can be used according to actual needs.

Realization of sending picture message

When using the API of application message push, we need to provide the media_id value of the picture to send the picture message, so as to obtain the picture we want to send. The sent picture is used as a temporary material, so we need to upload the picture as a temporary material first. After the upload is completed, the api will return us the media_id value corresponding to the picture.

Upload temporary material and get media_id :

def get_media_id(filetype,path):
    upload_file_url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={}&type={}".format(get_access_token(),filetype)
    files = {filetype: open(path, 'rb')}
    file_upload_result = requests.post(upload_file_url, files=files).json()
    return file_upload_result["media_id"]

Among the parameters of the function, "filetype" is the file type, here we can fill in "image" (image must be added with single or double quotes!). path is the file path, you can fill in the absolute path or relative path. The return value of the function is the media_id value we need.

示例:
get_media_id("image","a.jpg") #相对路径
get_media_id("image","C:/users/desktop/a.jpg") #绝对路径

After getting media_id, we can send picture message.

#发送图片消息
def send_picture_message(media_id):
    send_picture_url="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}".format(get_access_token())
    data={
        "touser" : "@all",
        "msgtype" : "image",
        "agentid" : 1000002,
        "image" : {
            "media_id" : media_id
            },
        "safe" : 0,
        }
    picture_message_res=requests.post(url=send_picture_url,data=json.dumps(data)).json()
    return picture_message_res

示例:
send_picture_message(get_media_id("image","a.jpg"))


Possible errors
If error code 48002 appears after sending a message, it is most likely that your address book does not have a sync api.

Solution:

Find "Contacts Sync" in Administrative Tools

Then edit the permission and set it to API to edit the address book.
———————————————
 

Use Python to send corporate WeChat messages 

Preparation:

    Go to the official website of Enterprise WeChat and register an enterprise; log in the background of Enterprise WeChat, create a "self-built" application, and obtain the three necessary parameters of enterprise ID, agentid, and secret; create multiple test accounts in the address book of Enterprise WeChat; Install the "Enterprise WeChat" APP on the mobile phone, log in to Enterprise WeChat with a test account, and prepare to receive messages.

Program code :

    Work WeChat provides an API development interface, which interacts with the work WeChat background through the GET and POST methods of HTTPS, and completes the operations of obtaining tokens, sending data, and obtaining data.

    The Python code mainly uses the requests library to simply encapsulate the enterprise WeChat API, simulate the GET and POST operations of https, and send enterprise WeChat messages to specified users.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import requests
import json


class WeChat:
    def __init__(self):
        self.CORPID = 'ww2e1234567895498f5498f'  #企业ID,在管理后台获取
        self.CORPSECRET = 'xy11234567898hk_ecJ123456789DhKy4_1y12345OI'#自建应用的Secret,每个自建应用里都有单独的secret
        self.AGENTID = '1000002'  #应用ID,在后台应用中获取
        self.TOUSER = "maomao|dingding"  # 接收者用户名,多个用户用|分割

    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('./tmp/access_token.conf', 'r') as f:
                t, access_token = f.read().split()
        except:
            with open('./tmp/access_token.conf', 'w') as f:
                access_token = self._get_access_token()
                cur_time = time.time()
                f.write('	'.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('./tmp/access_token.conf', 'w') as f:
                    access_token = self._get_access_token()
                    f.write('	'.join([str(cur_time), access_token]))
                    return access_token

    def send_data(self, message):
        send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.get_access_token()
        send_values = {
            "touser": self.TOUSER,
            "msgtype": "text",
            "agentid": self.AGENTID,
            "text": {
                "content": message
                },
            "safe": "0"
            }
        send_msges=(bytes(json.dumps(send_values), 'utf-8'))
        respone = requests.post(send_url, send_msges)
        respone = respone.json()   #当返回的数据是json串的时候直接用.json即可将respone转换成字典
        return respone["errmsg"]


if __name__ == '__main__':
    wx = WeChat()
    wx.send_data("这是程序发送的第1条消息!
 Python程序调用企业微信API,从自建应用“告警测试应用”发送给管理员的消息!")
    wx.send_data("这是程序发送的第2条消息!")

Run the screenshot:

      

Python realizes sending messages through enterprise WeChat

Realized sending messages through corporate WeChat, and the alarms usually used for operation and maintenance are still good. Compared with emails, the real-time performance is higher , but corporate WeChat is more troublesome, so I won’t explain too much here.

For details of the enterprise WeChat api, please see: http://work.weixin.qq.com/api/doc#10167

Not much to say, direct code

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# @Time    : 2018/4/25 17:06
# @Author  : zms
# @Site    :
# @File    : WeChat.py
# @Software: PyCharm Community Edition

# !/usr/bin/env python
# coding:utf-8
# file wechat.py

import time
import requests
import json

import sys

reload(sys)
sys.setdefaultencoding('utf8')


class WeChat:
    def __init__(self):
        self.CORPID = '***********'
        self.CORPSECRET = '*********************************'
        self.AGENTID = '**************'
        self.TOUSER = "**********"  # 接收者用户名

    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)
        # print data
        return data["access_token"]

    def get_access_token(self):
        try:
            with open('./tmp/access_token.conf', 'r') as f:
                t, access_token = f.read().split()
        except:
            with open('./tmp/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, message):
        msg = message.encode('utf-8')
        send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.get_access_token()
        send_values = {
            "touser": self.TOUSER,
            "msgtype": "text",
            "agentid": self.AGENTID,
            "text": {
                "content": msg
                },
            "safe": "0"
            }
        send_data = '{"msgtype": "text", "safe": "0", "agentid": %s, "touser": "%s", "text": {"content": "%s"}}' % (
            self.AGENTID, self.TOUSER, msg)
        r = requests.post(send_url, send_data)
        # print r.content
        return r.content


if __name__ == '__main__':
    wx = WeChat()
    wx.send_data("test")

#!/usr/bin/python
# -*- coding: utf-8 -*-

import time
import requests
import json,os


class WeChat_SMS:
    def __init__(self):
        self.CORPID = 'XXXX'#企业ID, 登陆企业微信,在我的企业-->企业信息里查看
        self.CORPSECRET = 'XXXXX'#自建应用,每个自建应用里都有单独的secret
        self.AGENTID = 'XXXX' #应用代码
        self.TOUSER = "XXX"# 接收者用户名,@all 全体成员
        self.TOPARY = "2"    #部门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)
        #print (data)
        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) < 7200:#token的有效时间7200s
                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, msg):
        send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.get_access_token()
        send_values = {
            "touser": self.TOUSER,
            #"toparty": self.TOPARY, 	#设置给部门发送
            "msgtype": "text",
            "agentid": self.AGENTID,
            "text": {
            "content": msg
            },
            "safe": "0"
        }
        send_msges=(bytes(json.dumps(send_values), 'utf-8'))
        respone = requests.post(send_url, send_msges)
        respone = respone.json()#当返回的数据是json串的时候直接用.json即可将respone转换成字典
        #print (respone["errmsg"])
        return respone["errmsg"]


if __name__ == '__main__':
    wx = WeChat_SMS()
    wx.send_data(msg="服务崩了,你还在这里吟诗作对?")
    #以下是添加对日志的监控
    # srcfile = u"G:/123.txt"
    # file = open(srcfile)
    # file.seek(0, os.SEEK_END)
    # while 1:
    #     where = file.tell()
    #     line = file.readline()
    #     if not line:
    #         time.sleep(1)
    #         file.seek(where)
    #     else:
    #         print(line)
    #         wx.send_data(msg=line)

Simple Tutorial- Interface Documentation- Wechat Enterprise Developer Center

Use Python to send corporate WeChat messages - take a look

Python uses WeChat for message push

https://blog.csdn.net/qq_37939940/article/details/125630492 

Guess you like

Origin blog.csdn.net/qq_22473611/article/details/126652105