Python脚本实现发送飞书加急消息

#!/usr/bin/python3
import json
import time
import datetime
import requests

class CONFIG():
    Feishu_Host = 'https://open.feishu.cn'
    Feishu_Appid = 'cli_a22161e5e9bbdxxxx'
    Feishu_AppSecret = 'v8AYp8ksE3xgjmg8vFD7Xbhs6lADtxxxx'
    Fast_Operation_Team = 'oc_86b2991bbf9783703ac8e3edb686d3330'
    User_List = ['xxxxxxxx']
    Urgent_Mode = ['inside', 'sms', 'phone'] #'inside’:内部加急, 'sms‘:短信加急, 'phone':电话加急
    
class Feishu(object):
    def __init__(self):
        self.domain = CONFIG.Feishu_Host
        self.app_id = CONFIG.Feishu_Appid
        self.app_secret = CONFIG.Feishu_AppSecret
        self.token = None
        
    def fetch(self, method, url, headers=None, params=None, data=None):
        url = self.domain + url
        if data and type(data) == dict:
            data = json.dumps(data)
        for i in [1,2,3]:
            try:
                response = requests.request(method, url, headers=headers, params=params, data=data, timeout=10)
                if response.status_code in [200]:
                    rep_body = response.json()
                    return True, rep_body
                else:
                    print('http code is not 200, code:%s' % response.status_code)
                    return False, response.text
            except requests.exceptions.ReadTimeout as e:
                print('http request read timeout Exception:%s, will retry:%s' % (e, i))
                time.sleep(1)
                continue
            except Exception as e:
                print('http request Exception:%s' % e)
                return False, {}
        print('http request read timeout 3 times failed will return, param:%s' % params)
        return False, 'retry 3 times failed, will return'

    def get(self, url, headers=None, params={}, data=None, callback=False):
        return self.fetch('get', url, headers=headers, params=params, data=data)
    
    def post(self, url, headers=None, params={}, data=None, callback=False):
        return self.fetch('post', url, headers=headers, params=params, data=data)
        
    def delete(self, url, headers=None, params={}, data=None, callback=False):
        return self.fetch('delete', url, headers=headers, params=params, data=data)
    
    def patch(self, url, headers=None, params={}, data=None, callback=False):
        return self.fetch('patch', url, headers=headers, params=params, data=data)
        
    def get_token(self):
        if not self.token:
            self.token = self.gen_token()
        return self.token
        
    def gen_token(self):
        url = '/open-apis/auth/v3/app_access_token/internal'
        headers = {
            'Content-Type': 'application/json; charset=utf-8',
        }
        data = {
            'app_id': self.app_id,
            'app_secret': self.app_secret
        }
        success, result = self.post(url, headers=headers, data=data)
        if success:
            return result.get('app_access_token','')
        return ''

    def send_msg_card_common(self, chat_id, content):
        '''
        发送消息卡片群消息
        '''
        url = '/open-apis/im/v1/messages'
        headers = {
            'Authorization': 'Bearer ' + self.get_token(),
            'Content-Type': 'application/json; charset=utf-8',
        }
        params = {
            'receive_id_type': 'chat_id'
        }
        data = {
            'receive_id': chat_id,
            'content': json.dumps(content),
            'msg_type': 'interactive'
        }
        success, result = self.post(url, headers=headers, params=params, data=data)
        return success, result

    def send_msg_inside(self, message_id, user_list):
        url = '/open-apis/im/v1/messages/%s/urgent_app' % message_id
        headers = {
            'Authorization': 'Bearer ' + self.get_token(),
            'Content-Type': 'application/json; charset=utf-8',
        }
        params = {
            'user_id_type': 'user_id'
        }
        data = {
            'user_id_list': user_list
        }
        success, result = self.patch(url, headers=headers, params=params, data=data)
        return success, result

    def send_msg_sms(self, message_id, user_list):
        url = '/open-apis/im/v1/messages/%s/urgent_sms' % message_id
        headers = {
            'Authorization': 'Bearer ' + self.get_token(),
            'Content-Type': 'application/json; charset=utf-8',
        }
        params = {
            'user_id_type': 'user_id'
        }
        data = {
            'user_id_list': user_list
        }
        success, result = self.patch(url, headers=headers, params=params, data=data)
        return success, result
    
    def send_msg_phone(self, message_id, user_list):
        url = '/open-apis/im/v1/messages/%s/urgent_phone' % message_id
        headers = {
            'Authorization': 'Bearer ' + self.get_token(),
            'Content-Type': 'application/json; charset=utf-8',
        }
        params = {
            'user_id_type': 'user_id'
        }
        data = {
            'user_id_list': user_list
        }
        success, result = self.patch(url, headers=headers, params=params, data=data)
        return success, result

def send_msg():
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    msg = {
            "config": {},
            "i18n_elements": {
                "zh_cn": [
                    {
                        "tag": "column_set",
                        "flex_mode": "none",
                        "background_style": "default",
                        "horizontal_spacing": "8px",
                        "horizontal_align": "left",
                        "columns": [
                            {
                                "tag": "column",
                                "width": "weighted",
                                "vertical_align": "top",
                                "vertical_spacing": "8px",
                                "background_style": "default",
                                "elements": [
                                    {
                                        "tag": "markdown",
                                        "content": "**💻紧急故障:**\n通过fast的接口探测失败,疑似告警中心宕机,请处理",
                                        "text_align": "left",
                                        "text_size": "normal"
                                    }
                                ],
                                "weight": 1
                            },
                            {
                                "tag": "column",
                                "width": "weighted",
                                "vertical_align": "top",
                                "vertical_spacing": "8px",
                                "background_style": "default",
                                "elements": [
                                    {
                                        "tag": "markdown",
                                        "content": "**🔢事件开始时间:**\n%s" % now,
                                        "text_align": "left",
                                        "text_size": "normal"
                                    }
                                ],
                                "weight": 1
                            }
                        ],
                        "margin": "16px 0px 0px 0px"
                    }
                ]
            },
            "i18n_header": {
                "zh_cn": {
                    "title": {
                        "tag": "plain_text",
                        "content": "【告警中心服务宕机】"
                    },
                    "subtitle": {
                        "tag": "plain_text",
                        "content": "备注:告警中心宕机会发不出告警。"
                    },
                    "template": "red"
                }
            }
        }
    task = Feishu()
    success, result = task.send_msg_card_common(CONFIG.Fast_Operation_Team, msg)
    if success:
        msg_id = result.get('data', {}).get('message_id', '')
        for mode in CONFIG.Urgent_Mode:
            if mode == 'inside':
                task.send_msg_inside(msg_id, CONFIG.User_List)
            if mode == 'sms':
                task.send_msg_sms(msg_id, CONFIG.User_List)
            if mode == 'phone':
                task.send_msg_phone(msg_id, CONFIG.User_List)
    else:
        print("发送消息失败:", result)
        
if __name__ == '__main__':
    send_msg()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

旷野九思

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值