Python3调用微信企业号API发送文本消息

本文介绍了一种使用Python实现的企业微信消息推送方法。通过调用企业微信API接口,可以轻松地将定制化的消息发送到指定的企业微信群组或成员。文章提供了一个具体的Python脚本示例,展示了如何设置消息内容、接收者等参数,并通过日志记录了消息发送的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

import urllib.request
import json
import sys
import logging

touser = '@all'
agentid = 0
corpid = 'wx5aef2da956514535'
corpsecret = 'Co17m_OPlvE8Q4P2RKKwtq5oIA3p42xGUZEvCHBI8S0'
url = 'https://qyapi.weixin.qq.com'
subject = sys.argv[2]
message = sys.argv[3]

logging.basicConfig(level=logging.DEBUG, filename='E:\Python_project\Scripts\my.log',
                    format='%(asctime)s - %(levelname)s: %(message)s')


class Weixin:
    def __init__(self, url, corpid, corpsecret):
        token_url = '%s/cgi-bin/gettoken?corpid=%s&corpsecret=%s' % (url, corpid, corpsecret)
        self.token = json.loads(urllib.request.urlopen(token_url).read().decode())['access_token']

    def send_message(self, url, data):
        send_url = '%s/cgi-bin/message/send?access_token=%s' % (url, self.token)
        self.respone = urllib.request.urlopen(urllib.request.Request(url=send_url, data=data)).read()
        x = json.loads(self.respone.decode())['errcode']

        if x == 0:
            logging.debug('Successfully %s    %s' % (subject, message))
            return 'Succesfully'
        else:
            logging.debug('Failed %s    %s' % (subject, message))
            return 'Failed'

    def messages(self, subject, message):
        values = {
            "touser": touser,
            "msgtype": 'text',
            "agentid": agentid,
            "text": {'content': subject + message},
            "safe": 0
        }
        return self.send_message(url, bytes(json.dumps(values), 'utf-8'))


if __name__ == '__main__':
    obj = Weixin(url, corpid, corpsecret)
    ret = obj.messages(subject, message)

转载于:https://www.cnblogs.com/postgres/p/6942812.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值