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

#!/usr/bin/env python#-*- coding: utf-8 -*

importrequestsimportjsonimportloggingimporttimeimporturllibimporturllib3

urllib3.disable_warnings()try:

JSONDecodeError=json.decoder.JSONDecodeErrorexceptAttributeError:

JSONDecodeError=ValueErrordefis_not_null_and_blank_str(content):"""非空字符串

:param content: 字符串

:return: 非空 - True,空 - False"""

if content andcontent.strip():returnTrueelse:returnFalseclassFeiShutalkChatbot(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_noticedef 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)returnself.post(data)defpost(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)exceptrequests.exceptions.HTTPError as exc:

logging.error("消息发送失败, HTTP error: %d, reason: %s" %(exc.response.status_code, exc.response.reason))raise

exceptrequests.exceptions.ConnectionError:

logging.error("消息发送失败,HTTP connection error!")raise

exceptrequests.exceptions.Timeout:

logging.error("消息发送失败,Timeout error!")raise

exceptrequests.exceptions.RequestException:

logging.error("消息发送失败, Request Exception!")raise

else:try:

result=response.json()exceptJSONDecodeError:

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))returnresultif __name__ == '__main__':

webhook= "https://open.feishu.cn/open-apis/bot/v2/hook/bd86c593-9d08-40f9-9f5f-9**********"#注意保存webhook不要泄露

feishu =FeiShutalkChatbot(webhook)###_________________________________发送富文本消息____________________________________________

rich_text={"msg_type": "post","content": {"post": {"zh_cn": {"title": "项目更新通知","content": [

[

{"tag": "text","text": "项目有更新:"},

{"tag": "a","text": "点击查看","href": "https://oa.superdalan.com/open/jobFlow/preview?job_flow_id=29621"}

]

]

}

}

}

}

feishu.post(rich_text)###____________________________________________发送文本消息(两种方式)____________________________________________________________________________

###方式一:直接发字符串脚本自动封住处理

#feishu.send_text("开服测试成功-服名称:憨憨44区,包链接:https://www.baidu.com/.0_20200903_182807.apk,详情查看:https://oa.superdalan.com/job_flow_id=29621")

#text={

#"msg_type": "text",

#"content": {

#"text": "新更新提醒1213122222222222222222222222222222222222222222222222222222222"

#}}

# ##方式二:调接口发送,需自己提前整理好数据格式

#feishu.post(text)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值