python脚本--用企业微信实现发送信息

运行环境python3

#!/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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值