Python如何调用飞书实现发送消息
创始人
2024-11-19 00:01:34
0次

一、创建飞书机器人  

  自定义飞书机器人操作步骤,具体详见飞书官方文档:《机器人 | 如何在群聊中使用机器人?》

二、调用飞书发送消息

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

  参数msg_type代表消息类型,可传入:text(文本)/ post(富文本)/ image(图片)/ share_chat(分享群名片)/ interactive(消息卡片),可参照飞书接口文档:https://open.feishu.cn/document/ukTMukTMukTM/uUjNz4SN2MjL1YzM
发送文本消息
  请求的消息体示例:

{
"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 contenttest"
}
}

Curl 请求 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 contenttest"
  }
}'

使用Python封装飞书请求

接下来我们以发送文本格式消息类型,进行以下封装,上代码:

# -*- 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):
    '''
    机器人初始化
    :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

  封装后我们就可以直接调用封装的类,进行消息代码发送;执行以下代码后,就可以使用飞书发送消息咯,是不是很简单。

  webhook = "https://open.feishu.cn/open-apis/bot/v2/hook/1d7b5d0c-03a5-44a9-8d7a-4d09b24bfea1"
  feishu = FeiShutalkChatbot(webhook)
  feishu.send_text("重庆百货-新世纪鱼胡路店内商品'1000800370-牛心白 约1kg'在商详[8]和榜单[7]中排名不一致")

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...