当前位置:首页 » python教程 » 正文

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

看: 799次  时间:2021-06-09  分类 : python教程

一、需要的参数

1、通讯用户:touser 或 通讯组:toparty

    2、企业ID:corpid

    3、应用ID/密钥:agentId,secret

二、获取通讯用户/组

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

三、获取企业ID

我的企业最下方

四、获取应用ID/密钥

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

应用管理创建应用

可见范围:发给谁

五、脚本代码

#! /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实现企业微信发送消息的文章就介绍到这了,更多相关python企业微信发送消息内容请搜索python博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持python博客!

标签:requests  

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!