教你利用python实现企业微信发送消息

一、需要的参数

1、通讯用户:touser 或 通讯组:toparty
 
    2、企业ID:corpid
 
    3、应用ID/密钥:agentId,secret

二、获取通讯用户/组

通讯录 用户的账号或创建组的部门ID

教你利用python实现企业微信发送消息

教你利用python实现企业微信发送消息

三、获取企业ID

我的企业最下方

教你利用python实现企业微信发送消息

四、获取应用ID/密钥

企业微信管理员登录企业微信,

应用管理创建应用

教你利用python实现企业微信发送消息

可见范围:发给谁

教你利用python实现企业微信发送消息

教你利用python实现企业微信发送消息

五、脚本代码

#! /usr/bin/env python
# -*- coding: UTF-8 -*-
 
import requests, sys
 
 
class SendWeiXinWork():
    def __init__(self):
        self.CORP_ID = \"xxx\"  # 企业号的标识
        self.SECRET = \"xxx\"  # 管理组凭证密钥
        self.AGENT_ID = xxx  # 应用ID
        self.token = self.get_token()
 
    def get_token(self):
        url = \"https://qyapi.weixin.qq.com/cgi-bin/gettoken\"
        data = {
            \"corpid\": self.CORP_ID,
            \"corpsecret\": self.SECRET
        }
        req = requests.get(url=url, params=data)
        res = req.json()
        if res[\'errmsg\'] == \'ok\':
            return res[\"access_token\"]
        else:
            return res
 
    def send_message(self, to_user, content):
        url = \"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s\" % self.token
        data = {
            # \"touser\": to_user,  # 发送个人就填用户账号
            \"toparty\": to_user,  # 发送组内成员就填部门ID
            \"msgtype\": \"text\",
            \"agentid\": self.AGENT_ID,
            \"text\": {\"content\": content},
            \"safe\": \"0\"
        }
 
        req = requests.post(url=url, json=data)
        res = req.json()
        if res[\'errmsg\'] == \'ok\':
            print(\"send message sucessed\")
            return \"send message sucessed\"
        else:
            return res
 
 
if __name__ == \'__main__\':
    SendWeiXinWork = SendWeiXinWork()
    SendWeiXinWork.send_message(\"2\", \"测试a\")

六、效果

教你利用python实现企业微信发送消息

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容