Python calls flybook to send message

Jiang Feng sleeps in sorrow 2020-11-09 22:18:59
python calls flybook send message


One 、 Creating a flying Book Robot

since Define the operation steps of flying Book Robot , For details, please refer to the official documents of Feishu :《 robot | How to use robots in group chat ?

Two 、 Call flybook to send message

After adding a custom robot , You can tell them webhook The address to send POST request , So we can push messages in group chat . Message formats that support push include text 、 Rich text 、 Picture message , You can also share group business cards and so on .

Parameters msg_type Represents the message type , Can be introduced into :text( Text )/ post( Rich text )/ image( picture )/ share_chat( Share group business cards )/ interactive( Message card ), Please refer to the interface document of Feishu :https://open.feishu.cn/document/ukTMukTMukTM/uUjNz4SN2MjL1YzM
Send a text message
An example of the requested message body :
{
"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 request 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>"
}
}'

Use Python Package flybook request

Next we send text message types , Package as follows , Code up :

# -*- 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):
"""
Non empty string
:param content: character string
:return: Non empty - True, empty - 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):
'''
Robot initialization
:param webhook: Flying book group custom robot webhook Address
:param secret: Check the robot security settings page “ The signature of the ” The key passed in is required when
:param pc_slide: How to open the message link , Default False Open for browser , Set to True When is PC The end sidebar opens
:param fail_notice: Message sending failure alert , The default is False Don't remind , Developers can judge and process the returned message by themselves
'''
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=[]):
"""
The message type is text type
:param msg: The message content
:return: Return message sending result
"""
data = {"msg_type": "text", "at": {}}
if is_not_null_and_blank_str(msg): # Pass in msg Non empty 
data["content"] = {"text": msg}
else:
logging.error("text type , Message content cannot be empty !")
raise ValueError("text type , Message content cannot be empty !")
logging.debug('text type :%s' % data)
return self.post(data)
def post(self, data):
"""
Send a message ( Content UTF-8 code )
:param data: The message data ( Dictionaries )
:return: Return message sending result
"""
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(" Message delivery failed , HTTP error: %d, reason: %s" % (exc.response.status_code, exc.response.reason))
raise
except requests.exceptions.ConnectionError:
logging.error(" Message delivery failed ,HTTP connection error!")
raise
except requests.exceptions.Timeout:
logging.error(" Message delivery failed ,Timeout error!")
raise
except requests.exceptions.RequestException:
logging.error(" Message delivery failed , Request Exception!")
raise
else:
try:
result = response.json()
except JSONDecodeError:
logging.error(" Server response exception , Status code :%s, Response content :%s" % (response.status_code, response.text))
return {'errcode': 500, 'errmsg': ' Server response exception '}
else:
logging.debug(' Send results :%s' % result)
# Message sending failure alert (errcode Not for 0, Indicates that the message is sent abnormally ), Default not to remind , Developers can judge and process the returned message by themselves 
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": "[ Be careful - Automatic notification ] Message sending failure of flying Book Robot , Time :%s, reason :%s, Please follow up in time , thank you !" % (
time_now, result['errmsg'] if result.get('errmsg', False) else ' Unknown exception ')
},
"at": {
"isAtAll": False
}
}
logging.error(" Message delivery failed , Automatic notification :%s" % error_data)
requests.post(self.webhook, headers=self.headers, data=json.dumps(error_data))
return result

After encapsulation, we can directly call the encapsulated class , Send message code ; After executing the following code , You can use flybook to send messages , Is it simple .

 webhook = "https://open.feishu.cn/open-apis/bot/v2/hook/1d7b5d0c-03a5-44a9-8d7a-4d09b24bfea1"
feishu = FeiShutalkChatbot(webhook)
feishu.send_text(" Chongqing department store - Yuhu road in the new century '1000800370- Niuxinbai about 1kg' In business details [8] And the list [7] The rankings are not consistent ")

 

 

版权声明
本文为[Jiang Feng sleeps in sorrow]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database