当前位置:网站首页>Python calls flybook to send message

Python calls flybook to send message

2020-11-09 22:18:59 Jiang Feng sleeps in sorrow

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]所创,转载请带上原文链接,感谢