Python发送企业微信消息

给某个用户发送文本消息

#! /usr/bin/env python
# -*- coding: UTF-8 -*-
  
import requests, sys
  
class SendWeiXinWork():
    def __init__(self):
        self.CORP_ID = "ww2w"  # 企业微信的标识
        self.SECRET = 'iqqqqqq'  # 企业微信应用密钥
        self.AGENT_ID = '10'  # 应用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()
    # print(SendWeiXinWork.get_token())
    res = SendWeiXinWork.send_message("yc02", "测试a")
    print(res) #提前在企业微信应用中添加可信IP

 

给企业微信群通过机器人发送文本消息

import requests
def SendGroupMsg(textContent, webHookUrl, mentioned_list=[],mentioned_mobile_list=[]):
     """
     发送微信群组机器人消息
     :param textContent: 消息内容
     :param webHookUrl: 群组机器人WebHook
     :param mentioned_list: userid的列表,提醒群中的指定成员(@某个成员),@all表示提醒所有人
     :param mentioned_mobile_list: 手机号列表,提醒手机号对应的群成员(@某个成员),@all表示提醒所有人
     :return:
     """
     # url为群组机器人WebHook,配置项
     url = webHookUrl
     headers = {
         "content-type": "application/json"
     }
     msg = {"msgtype": "text", 
     "text": {
         "content": textContent, 
         "mentioned_list":mentioned_list,
         "mentioned_mobile_list": mentioned_mobile_list
         }}  # 发送文本消息27     # 发送请求
     try:
         result = requests.post(url, headers=headers, json=msg)
         return True
     except Exception as e:
         # print("Requset Failed:", e)
         return False

webHookUrl = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=933333333'
textContent = 'test text'
SendGroupMsg(textContent, webHookUrl, mentioned_list=['@all'],mentioned_mobile_list=[])         

 

posted on 2024-04-13 00:14  momingliu11  阅读(92)  评论(0编辑  收藏  举报