Python通過飛書機器人發送消息到群


 

一、創建飛書機器人 

自定義飛書機器人操作步驟,具體詳見飛書官方文檔:《機器人 | 如何在群聊中使用機器人?》

 

二、調用飛書發送消息

  自定義機器人添加完成后,就能向其 webhook 地址發送 POST 請求,從而在群聊中推送消息了。支持推送的消息格式有文本、富文本、圖片消息,也可以分享群名片等。

  參數msg_type代表消息類型,可傳入:text(文本)/ post(富文本)/ image(圖片)/ share_chat(分享群名片)/ interactive(消息卡片),可參照飛書接口文檔:https://open.feishu.cn/document/ukTMukTMukTM/uUjNz4SN2MjL1YzM
發送文本消息

 

三、使用Python封裝飛書請求

接下來我們以發送文本格式消息類型,進行以下封裝,上代碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*
import requests
import json
import logging
import time
import urllib
import urllib3

urllib3.disable_warnings()

try:
    JSONDecodeError = json.decoder.JSONDecodeError
except AttributeError:
    JSONDecodeError = ValueError


def is_not_null_and_blank_str(content):
    """
    非空字符串
    :param content: 字符串
    :return: 非空 - True,空 - False
    """
    if content and content.strip():
        return True
    else:
        return False


class FeiShutalkChatbot(object):
    def __init__(self, webhook, secret=None, pc_slide=False, fail_notice=False):
        '''
        機器人初始化
        :param webhook: 飛書群自定義機器人webhook地址
        :param secret: 機器人安全設置頁面勾選“加簽”時需要傳入的密鑰
        :param pc_slide: 消息鏈接打開方式,默認False為瀏覽器打開,設置為True時為PC端側邊欄打開
        :param fail_notice: 消息發送失敗提醒,默認為False不提醒,開發者可以根據返回的消息發送結果自行判斷和處理
        '''
        super(FeiShutalkChatbot, self).__init__()
        self.headers = {'Content-Type': 'application/json; charset=utf-8'}
        self.webhook = webhook
        self.secret = secret
        self.pc_slide = pc_slide
        self.fail_notice = fail_notice

    def send_text(self, msg, open_id=[]):
        """
        消息類型為text類型
        :param msg: 消息內容
        :return: 返回消息發送結果
        """
        data = {"msg_type": "text", "at": {}}
        if is_not_null_and_blank_str(msg):  # 傳入msg非空
            data["content"] = {"text": msg}
        else:
            logging.error("text類型,消息內容不能為空!")
            raise ValueError("text類型,消息內容不能為空!")

        logging.debug('text類型:%s' % data)
        return self.post(data)

    def post(self, data):
        """
        發送消息(內容UTF-8編碼)
        :param data: 消息數據(字典)
        :return: 返回消息發送結果
        """
        try:
            post_data = json.dumps(data)
            response = requests.post(self.webhook, headers=self.headers, data=post_data, verify=False)
        except requests.exceptions.HTTPError as exc:
            logging.error("消息發送失敗, HTTP error: %d, reason: %s" % (exc.response.status_code, exc.response.reason))
            raise
        except requests.exceptions.ConnectionError:
            logging.error("消息發送失敗,HTTP connection error!")
            raise
        except requests.exceptions.Timeout:
            logging.error("消息發送失敗,Timeout error!")
            raise
        except requests.exceptions.RequestException:
            logging.error("消息發送失敗, Request Exception!")
            raise
        else:
            try:
                result = response.json()
            except JSONDecodeError:
                logging.error("服務器響應異常,狀態碼:%s,響應內容:%s" % (response.status_code, response.text))
                return {'errcode': 500, 'errmsg': '服務器響應異常'}
            else:
                logging.debug('發送結果:%s' % result)
                # 消息發送失敗提醒(errcode 不為 0,表示消息發送異常),默認不提醒,開發者可以根據返回的消息發送結果自行判斷和處理
                if self.fail_notice and result.get('errcode', True):
                    time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
                    error_data = {
                        "msgtype": "text",
                        "text": {
                            "content": "[注意-自動通知]飛書機器人消息發送失敗,時間:%s,原因:%s,請及時跟進,謝謝!" % (
                                time_now, result['errmsg'] if result.get('errmsg', False) else '未知異常')
                        },
                        "at": {
                            "isAtAll": False
                        }
                    }
                    logging.error("消息發送失敗,自動通知:%s" % error_data)
                    requests.post(self.webhook, headers=self.headers, data=json.dumps(error_data))
                return result


if __name__ == '__main__':
    webhook = "https://open.feishu.cn/open-apis/bot/v2/hook/bd86c593-9d08-40f9-9f5f-9**********"#注意保存webhook不要泄露
    feishu = FeiShutalkChatbot(webhook)
    ###_________________________________發送富文本消息____________________________________________
    rich_text= {
    "msg_type": "post",
    "content": {
        "post": {
            "zh_cn": {
                "title": "項目更新通知",
                "content": [
                    [
                        {
                            "tag": "text",
                            "text": "項目有更新: "
                        },
                        {
                            "tag": "a",
                            "text": "點擊查看",
                            "href": "https://oa.superdalan.com/open/jobFlow/preview?job_flow_id=29621"
                        }
                    ]
                ]
            }
        }
    }
    }
    feishu.post(rich_text)

    ###____________________________________________發送文本消息(兩種方式)____________________________________________________________________________
    ###方式一:直接發字符串腳本自動封住處理
    # feishu.send_text("開服測試成功-服名稱:憨憨44區,包鏈接:https://www.baidu.com/.0_20200903_182807.apk,詳情查看:https://oa.superdalan.com/job_flow_id=29621")
    # text={
    # "msg_type": "text",
    # "content": {
    #     "text": "新更新提醒1213122222222222222222222222222222222222222222222222222222222"
    # }}
    #
    # #方式二:調接口發送,需自己提前整理好數據格式
    # feishu.post(text)

 

四、使用API直接發送

import json
import requests

# 你復制的webhook地址
url = "https://open.feishu.cn/open-apis/bot/v2/hook/0946aba4"

###____________________________________________發送普通text___________________________________________________
# payload_message = {
#     "msg_type": "text",
#     "content": {
#         "text": "測試一下"
#     }
# }
# headers = {
#     'Content-Type': 'application/json'
# }
#
# response = requests.request("POST", url, headers=headers, data=json.dumps(payload_message))
# print(response.text)


###_________________________________發送富文本消息_____________________________________________________
rich_text= {
"msg_type": "post",
"content": {
    "post": {
        "zh_cn": {
            "title": "大藍接口測試平台",
            "content": [
                [
                    {
                        "tag": "text",
                        "text": "idiewjdwojedjwiejdijweidjiwejdijwiejdiwje"
                    },
                    {
                        "tag": "a",
                        "text": "點擊查看",
                        "href": "dwjdk[pwe565656565"
                    }
                ]
            ]
        }
    }
}
}
headers = {
    'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=json.dumps(rich_text))
print(response.text)

 

 

 

相關連接:

https://blog.csdn.net/qq_41730930/article/details/109812597 ...............其他更多方式


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM