首页 > 编程语言 > 详细

Python通过飞书机器人发送消息到群

时间:2021-01-07 18:58:59      阅读:137      评论:0      收藏:0      [点我收藏+]

 

一、创建飞书机器人 

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

 

二、调用飞书发送消息

  自定义机器人添加完成后,就能向其 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/bd86c59"#注意保存webhook不要泄露
    feishu = FeiShutalkChatbot(webhook)
    feishu.send_text("鹏哥!"
                     "我们是大蓝游戏的搬运工")

 

Python通过飞书机器人发送消息到群

原文:https://www.cnblogs.com/chen-xia/p/14247417.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!