Python教程

Python 发送企业微信单发和群发机器人

本文主要是介绍Python 发送企业微信单发和群发机器人,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import time
import requests
import json
 
 
class WeChat:
    def __init__(self):
        self.CORPID = 'ww2e1234567895498f5498f'  #企业ID,在管理后台获取
        self.CORPSECRET = 'xy11234567898hk_ecJ123456789DhKy4_1y12345OI'#自建应用的Secret,每个自建应用里都有单独的secret
        self.AGENTID = '1000002'  #应用ID,在后台应用中获取
        self.TOUSER = "maomao|dingding"  # 接收者用户名,多个用户用|分割
 
    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)
        return data["access_token"]
 
    def get_access_token(self):
        try:
            with open('./tmp/access_token.conf', 'r') as f:
                t, access_token = f.read().split()
        except:
            with open('./tmp/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) < 7260:
                return access_token
            else:
                with open('./tmp/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, message):
        send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.get_access_token()
        send_values = {
            "touser": self.TOUSER,
            "msgtype": "text",
            "agentid": self.AGENTID,
            "text": {
                "content": message
                },
            "safe": "0"
            }
        send_msges=(bytes(json.dumps(send_values), 'utf-8'))
        respone = requests.post(send_url, send_msges)
        respone = respone.json()   #当返回的数据是json串的时候直接用.json即可将respone转换成字典
        return respone["errmsg"]
 
 
if __name__ == '__main__':
    wx = WeChat()
    wx.send_data("这是程序发送的第1条消息!\n Python程序调用企业微信API,从自建应用“告警测试应用”发送给管理员的消息!")
    wx.send_data("这是程序发送的第2条消息!")

群发机器人:

import requests
import json

dsj_url = ''


def send_msg(send_message):
    data1 = json.dumps({'msgtype': "markdown",
                        "markdown": {
                            "content": send_message,
                            "mentioned_list": ["@all"]
                        }})
    # 指定机器人发送消息
    resp = requests.post(dsj_url, data1, auth=('Content-Type', 'application/json'))
    return '出现故障:%s,此次报警成功' % send_message


if __name__ == '__main__':
    # 报警机器人url
    send_message = '''【可疑】<font color=\"warning\">hids 检测到 异常登录!</font>\n
                      >源ip:<font color=\"comment\">10.70.234.21</font>
                      >目标IP:<font color=\"comment\">10.70.218.13</font>
                      >涉及资产:<font color=\"comment\">jssz-ai-newton-cpu-06</font>
                      >详情:
                      >登录主机所属业务组:<font color=\"comment\">未分组主机</font>
                      >登录使用账户:<font color=\"comment\">root</font>
                      >发现时间:<font color=\"comment\">2021-06-10 16:24:12</font>
                      '''
    res = send_msg(send_message)
    print(res)

 

这篇关于Python 发送企业微信单发和群发机器人的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!