前言

使用飞书机器人发送消息,本质是使用Python的requests类库发送http请求,请求地址即为创建机器时保存的webhook链接,发送的内容实际为json串,请求header为{'Content-Type': 'application/json; charset=utf-8'}

一、创建飞书机器人  

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

二、调用飞书发送消息

  自定义机器人添加完成后,就能向其 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 content<at user_id=\"ou_88a56e7e8e9f680b682f6905cc09098e\">test</at>"
}
}

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 content<at user_id=\"ou_88a56e7e8e9f680b682f6905cc09098e\">test</at>"
}
}'

使用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即是创建机器人时生成的webhook链接,执行以下代码后,就可以使用飞书发送消息咯~

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

Python调用飞书发送消息的更多相关文章

  1. 关于 使用python向qq好友发送消息(对爬虫的作用----当程序执行完毕或者报错无限给自己qq发送消息,直到关闭)

    以前看到网上一些小程序,在处理完事物后会自动发送qq消息,但是一直搞不懂是说明原理.也在网上找过一些python登陆qq发送消息的文字,但是都太复杂了.今天偶然看到一篇文章,是用python调用win ...

  2. 个人微信公众号搭建Python实现 -接收和发送消息-基本说明与实现(14.2.1)

    @ 目录 1.原理 2.接收普通消息 3.接收代码普通消息代码实现 1.原理 2.接收普通消息 其他消息类似参考官方文档 3.接收代码普通消息代码实现 from flask import Flask, ...

  3. Python 微信公众号发送消息

    1. 公众号测试地址 https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index 2. ...

  4. python 钉钉机器人发送消息

    import json import requests def sendmessage(message): url = 'https://oapi.dingtalk.com/robot/send?ac ...

  5. 使用python对mysql主从进行监控,并调用钉钉发送报警信息

    1.编写python的监控脚本 A.通过获取mysql库中的状态值来判断这个mysql主从状态是否正常 B.进行两个状态值的判断 C.进行调取钉钉机器人,发送消息 2.设置定时任务进行脚本运行 cro ...

  6. Java企业微信开发_05_消息推送之发送消息(主动)

    一.本节要点 1.发送消息与被动回复消息 (1)流程不同:发送消息是第三方服务器主动通知微信服务器向用户发消息.而被动回复消息是 用户发送消息之后,微信服务器将消息传递给 第三方服务器,第三方服务器接 ...

  7. Kafka生产者发送消息的三种方式

    Kafka是一种分布式的基于发布/订阅的消息系统,它的高吞吐量.灵活的offset是其它消息系统所没有的. Kafka发送消息主要有三种方式: 1.发送并忘记 2.同步发送 3.异步发送+回调函数 下 ...

  8. 如何在MFC DLL中向C#类发送消息

    如何在MFC DLL中向C#类发送消息 一. 引言 由于Windows Message才是Windows平台的通用数据流通格式,故在跨语言传输数据时,Message是一个不错的选择,本文档将描述如何在 ...

  9. activeMq发送消息流程

    1,发送消息入口 Message message = messageBean.getMessageCreator().createMessage(session); producer.send(mes ...

随机推荐

  1. BSGS算法解析

    前置芝士: 1.快速幂(用于求一个数的幂次方) 2.STL里的map(快速查找) 详解 BSGS 算法适用于解决高次同余方程 \(a^x\equiv b (mod p)\) 由费马小定理可得 x &l ...

  2. tomcat:tomcat安装(在一台电脑上安装两个tomcat)

    1.安装前的说明 (1)在安装第二个tomcat之前,我们要知道安装一台tomcat的时候需要在电脑上添加两个系统变量 然后在path中配置: (2)这个时候我们就要思考了,当安装第二台服务器的时候首 ...

  3. centos7 下 kafka的安装和基本使用

    首先确保自己的linux环境下正确安装了Java 8+. 1:取得KAFKA https://mirrors.bfsu.edu.cn/apache/kafka/2.6.0/kafka_2.13-2.6 ...

  4. axio跨域请求,vue中的config的配置项。

    这是我用 vue cli 脚手架搭建的跨域.以上是可以请求到的.

  5. MeteoInfo脚本示例:GrADS to netCDF

    这里给出一个将GrADS数据文件转为netCDF数据文件的脚本示例程序,其它格式数据转netCDF可以参考: #-------------------------------------------- ...

  6. gitlab 拉代码提示:Your Account has been blocked. fatal: Could not read from remote repository. 最佳解决方案

    今天在脚本服务器上拉取代码,突然发现拉不了代码了,提示: GitLab: Your account has been blocked. fatal: Could not read from remot ...

  7. C语言/C++编程学习:送给考计算机二级的同学:公共基础知识总结!

    数据结构与算法 1.算法 算法:是指解题方案的准确而完整的描述. 算法不等于程序,也不等计算机方法,程序的编制不可能优于算法的设计. 算法的基本特征:是一组严谨地定义运算顺序的规则,每一个规则都是有效 ...

  8. Linux ALSA音频库(二) 环境测试+音频合成+语音切换 项目代码分享

    1. 环境测试 alsa_test.c #include <alsa/asoundlib.h> #include <stdio.h> // 官方测试代码, 运行后只要有一堆信息 ...

  9. kafka-消费者测试

    1. 在窗口1创建一个producer,topic为test,broker-list为zookeeper集群ip+端口   /usr/local/kafka/bin/kafka-console-pro ...

  10. linux(centos8):prometheus使用alertmanager发送报警邮件(prometheus 2.18.1/alertmanager 0.20.0)

    一,alertmanager的用途 1,Alertmanager的作用: Alertmanager是一个独立的报警模块, 它接收Prometheus等客户端发来的警报,并通过分组.删除重复等处理, 通 ...