欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python調(diào)用飛書發(fā)送消息的示例

 更新時(shí)間:2020年11月10日 08:36:32   作者:江楓對(duì)愁眠  
這篇文章主要介紹了Python調(diào)用飛書發(fā)送消息的示例,幫助大家更好的理解和學(xué)習(xí)python編程語言的用法,感興趣的朋友可以了解下

一、創(chuàng)建飛書機(jī)器人  

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

二、調(diào)用飛書發(fā)送消息

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

  參數(shù)msg_type代表消息類型,可傳入:text(文本)/ post(富文本)/ image(圖片)/ share_chat(分享群名片)/ interactive(消息卡片),可參照飛書接口文檔:https://open.feishu.cn/document/ukTMukTMukTM/uUjNz4SN2MjL1YzM
發(fā)送文本消息
  請(qǐng)求的消息體示例:

{
"open_id":"ou_5ad573a6411d72b8305fda3a9c15c70e",
"root_id":"om_40eb06e7b84dc71c03e009ad3c754195",
"chat_id":"oc_5ad11d72b830411d72b836c20",
"user_id": "92e39a99",
"email":"fanlv@gmail.com",
"msg_type":"text",
"content":{
"text":"text content<at user_id=\"ou_88a56e7e8e9f680b682f6905cc09098e\">test</at>"
}
}

Curl 請(qǐng)求 Demo

curl -X POST \
 https://open.feishu.cn/open-apis/message/v4/send/ \
 -H 'Authorization: Bearer t-fee42159a366c575f2cd2b2acde2ed1e94c89d5f' \
 -H 'Content-Type: application/json' \
 -d '{
  "chat_id": "oc_f5b1a7eb27ae2c7b6adc2a74faf339ff",
  "msg_type": "text",
  "content": {
    "text": "text content<at user_id=\"ou_88a56e7e8e9f680b682f6905cc09098e\">test</at>"
  }
}'

使用Python封裝飛書請(qǐng)求

接下來我們以發(fā)送文本格式消息類型,進(jìn)行以下封裝,上代碼:

# -*- coding:utf-8 -*-
'''
@File   :  feiShuTalk.py 
@Time   :  2020/11/9 11:45  
@Author  :  DY
@Version  :  V1.0.0
@Desciption: 
'''

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):
    '''
    機(jī)器人初始化
    :param webhook: 飛書群自定義機(jī)器人webhook地址
    :param secret: 機(jī)器人安全設(shè)置頁面勾選“加簽”時(shí)需要傳入的密鑰
    :param pc_slide: 消息鏈接打開方式,默認(rèn)False為瀏覽器打開,設(shè)置為True時(shí)為PC端側(cè)邊欄打開
    :param fail_notice: 消息發(fā)送失敗提醒,默認(rèn)為False不提醒,開發(fā)者可以根據(jù)返回的消息發(fā)送結(jié)果自行判斷和處理
    '''
    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: 消息內(nèi)容
    :return: 返回消息發(fā)送結(jié)果
    """
    data = {"msg_type": "text", "at": {}}
    if is_not_null_and_blank_str(msg):  # 傳入msg非空
      data["content"] = {"text": msg}
    else:
      logging.error("text類型,消息內(nèi)容不能為空!")
      raise ValueError("text類型,消息內(nèi)容不能為空!")

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

  def post(self, data):
    """
    發(fā)送消息(內(nèi)容UTF-8編碼)
    :param data: 消息數(shù)據(jù)(字典)
    :return: 返回消息發(fā)送結(jié)果
    """
    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("消息發(fā)送失敗, HTTP error: %d, reason: %s" % (exc.response.status_code, exc.response.reason))
      raise
    except requests.exceptions.ConnectionError:
      logging.error("消息發(fā)送失敗,HTTP connection error!")
      raise
    except requests.exceptions.Timeout:
      logging.error("消息發(fā)送失敗,Timeout error!")
      raise
    except requests.exceptions.RequestException:
      logging.error("消息發(fā)送失敗, Request Exception!")
      raise
    else:
      try:
        result = response.json()
      except JSONDecodeError:
        logging.error("服務(wù)器響應(yīng)異常,狀態(tài)碼:%s,響應(yīng)內(nèi)容:%s" % (response.status_code, response.text))
        return {'errcode': 500, 'errmsg': '服務(wù)器響應(yīng)異常'}
      else:
        logging.debug('發(fā)送結(jié)果:%s' % result)
        # 消息發(fā)送失敗提醒(errcode 不為 0,表示消息發(fā)送異常),默認(rèn)不提醒,開發(fā)者可以根據(jù)返回的消息發(fā)送結(jié)果自行判斷和處理
        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": "[注意-自動(dòng)通知]飛書機(jī)器人消息發(fā)送失敗,時(shí)間:%s,原因:%s,請(qǐng)及時(shí)跟進(jìn),謝謝!" % (
                time_now, result['errmsg'] if result.get('errmsg', False) else '未知異常')
            },
            "at": {
              "isAtAll": False
            }
          }
          logging.error("消息發(fā)送失敗,自動(dòng)通知:%s" % error_data)
          requests.post(self.webhook, headers=self.headers, data=json.dumps(error_data))
        return result

  封裝后我們就可以直接調(diào)用封裝的類,進(jìn)行消息代碼發(fā)送;執(zhí)行以下代碼后,就可以使用飛書發(fā)送消息咯,是不是很簡(jiǎn)單。

  webhook = "https://open.feishu.cn/open-apis/bot/v2/hook/1d7b5d0c-03a5-44a9-8d7a-4d09b24bfea1"
  feishu = FeiShutalkChatbot(webhook)
  feishu.send_text("重慶百貨-新世紀(jì)魚胡路店內(nèi)商品'1000800370-牛心白 約1kg'在商詳[8]和榜單[7]中排名不一致")

以上就是Python調(diào)用飛書發(fā)送消息的示例的詳細(xì)內(nèi)容,更多關(guān)于python 飛書發(fā)送信息的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論