Skip to content

Commit

Permalink
Merge pull request #5 from BestLemoon/master
Browse files Browse the repository at this point in the history
feat: support push by feishu_bot
  • Loading branch information
nfe-w authored Jan 13, 2024
2 parents f5a00f3 + 58e8d55 commit d682464
Show file tree
Hide file tree
Showing 3 changed files with 125 additions and 5 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,15 @@ docker run -d -v ~/config_bili.ini:/mnt/config_bili.ini --name bili_dynamic_push
- `enable`是否启用钉钉bot推送
- `access_token`机器人access_token,如果启用该推送,则必填

(7)`push_feishu`下的参数
- `enable`是否启用飞书推送
- `app_id`飞书应用id,如果启用该推送,则必填,参考 https://open.feishu.cn/document/server-docs/api-call-guide/calling-process/get-access-token#95c7f5f5
- `app_secret`飞书应用secret,如果启用该推送,则必填
- `receive_id_type`飞书接收id类型,如果启用该推送,则必填,参考 https://open.feishu.cn/document/server-docs/im-v1/message/create
- `receive_id`飞书接收id,如果启用该推送,则必填
- `template_id`飞书消息模板id,如果启用该推送,则必填,参考 https://open.feishu.cn/document/server-docs/im-v1/message-content-description/create_json#11e75d0


#### 2.安装第三方库

`pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/`
Expand Down
15 changes: 15 additions & 0 deletions config_bili.ini
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,18 @@ corp_secret =
enable = false
# 机器人秘钥
access_token =


[push_feishu]
# 是否启用 true/false
enable = false
# 应用appid
appid =
# 应用appsecret
appsecret =
# 接收者类型
receive_id_type =
# 接收者id
receive_id =
# 消息模板id
template_id =
106 changes: 101 additions & 5 deletions push.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,17 @@
# @Time: 2021/3/21 12:33

import json
import mimetypes
import time
import uuid

from requests_toolbelt import MultipartEncoder
import util
from config import global_config
from logger import logger
import hashlib
import base64
import hmac


class Push(object):
Expand All @@ -23,6 +30,7 @@ class Push(object):
dingtalk_access_token = None

def __init__(self):

self.serverChan_enable = global_config.get_raw('push_serverChan', 'enable')
self.serverChan_sckey = global_config.get_raw('push_serverChan', 'serverChan_SCKEY')
self.serverChan_turbo_enable = global_config.get_raw('push_serverChan_turbo', 'enable')
Expand All @@ -33,8 +41,14 @@ def __init__(self):
self.wechat_corp_secret = global_config.get_raw('push_wechat', 'corp_secret')
self.dingtalk_enable = global_config.get_raw('push_dingtalk', 'enable')
self.dingtalk_access_token = global_config.get_raw('push_dingtalk', 'access_token')

def push_for_bili_dynamic(self, uname=None, dynamic_id=None, content=None, pic_url=None, dynamic_type=None, dynamic_time=None):
self.feishu_enable = global_config.get_raw('push_feishu', 'enable')
self.feishu_appid = global_config.get_raw('push_feishu', 'appid')
self.feishu_appsecret = global_config.get_raw('push_feishu', 'appsecret')
self.feishu_receive_id_type = global_config.get_raw('push_feishu', 'receive_id_type')
self.feishu_receive_id = global_config.get_raw('push_feishu', 'receive_id')
self.feishu_template_id = global_config.get_raw('push_feishu', 'template_id')
def push_for_bili_dynamic(self, uname=None, dynamic_id=None, content=None, pic_url=None, dynamic_type=None,
dynamic_time=None):
"""
B站动态提醒推送
:param uname: up主名字
Expand All @@ -45,7 +59,8 @@ def push_for_bili_dynamic(self, uname=None, dynamic_id=None, content=None, pic_u
:param dynamic_time: 动态发送时间
"""
if uname is None or dynamic_id is None or content is None:
logger.error('【推送】缺少参数,uname:[{}],dynamic_id:[{}],content:[{}]'.format(uname, dynamic_id, content[:30]))
logger.error(
'【推送】缺少参数,uname:[{}],dynamic_id:[{}],content:[{}]'.format(uname, dynamic_id, content[:30]))
return

title_msg = '发动态了'
Expand All @@ -54,7 +69,8 @@ def push_for_bili_dynamic(self, uname=None, dynamic_id=None, content=None, pic_u
elif dynamic_type == 8:
title_msg = '投稿了'
title = '【{uname}】{dynamic_type}'.format(uname=uname, dynamic_type=title_msg)
content = '{content}[{dynamic_time}]'.format(content=content[:100] + (content[100:] and '...'), dynamic_time=dynamic_time)
content = '{content}[{dynamic_time}]'.format(content=content[:100] + (content[100:] and '...'),
dynamic_time=dynamic_time)
dynamic_url = 'https://www.bilibili.com/opus/{}'.format(dynamic_id)
self._common_push(title, content, dynamic_url, pic_url)

Expand Down Expand Up @@ -86,6 +102,8 @@ def _common_push(self, title, content, jump_url=None, pic_url=None):
self._wechat_push(access_token, title, content, jump_url, pic_url)
if self.dingtalk_enable == 'true':
self._dingtalk_push(title, content, jump_url, pic_url)
if self.feishu_enable == 'true':
self._feishu_push(title, content, jump_url, pic_url)

def _server_chan_push(self, title, content, url=None):
"""
Expand All @@ -109,7 +127,8 @@ def _server_chan_turbo_push(self, title, content, url=None):
content = '`' + content + '`[点我直达]({url})'.format(url=url)
push_url = 'https://sctapi.ftqq.com/{key}.send'.format(key=self.serverChan_turbo_SendKey)
response = util.requests_post(push_url, '推送_serverChan_Turbo', params={"title": title, "desp": content})
logger.info('【推送_serverChan_Turbo】{msg}'.format(msg='成功' if util.check_response_is_ok(response) else '失败'))
logger.info(
'【推送_serverChan_Turbo】{msg}'.format(msg='成功' if util.check_response_is_ok(response) else '失败'))

def _get_wechat_access_token(self):
access_token = None
Expand Down Expand Up @@ -198,5 +217,82 @@ def _dingtalk_push(self, title, content, url=None, pic_url=None):
logger.debug(response.json())
logger.info('【推送_dingtalk】{msg}'.format(msg='成功' if util.check_response_is_ok(response) else '失败'))

def _get_feishu_access_token(self):
access_url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
headers = {
"Content-Type": "application/json; charset=utf-8"
}
body = {
"app_id": self.feishu_appid,
"app_secret": self.feishu_appsecret
}
res = util.requests_post(access_url, headers=headers, data=json.dumps(body))
return res.json()["tenant_access_token"]

def _upload_feishu_image(self, pic_url):
response = util.requests_get(pic_url)

# 确保请求成功
if response.status_code == 200:
# 获取内容类型
content_type = response.headers['Content-Type']
# 根据内容类型推断扩展名
extension = mimetypes.guess_extension(content_type)

# 如果无法从内容类型推断扩展名,则默认使用.jpg
if not extension:
extension = '.jpg'

# 构建保存文件的完整路径
save_path_with_extension = str(uuid.uuid4()) + extension

# 写入文件
with open(save_path_with_extension, 'wb') as file:
file.write(response.content)

logger.info(f"Image saved as {save_path_with_extension}")

url = "https://open.feishu.cn/open-apis/im/v1/images"
form = {'image_type': 'message',
'image': (open(save_path_with_extension, 'rb'))} # 需要替换具体的path
multi_form = MultipartEncoder(form)
headers = {'Authorization': "Bearer " + self._get_feishu_access_token(),
'Content-Type': multi_form.content_type}
response = util.requests_post(url, headers=headers, data=multi_form)
return response.json()["data"]["image_key"]
else:
logger.error(f"Failed to download image. Status code: {response.status_code}")

def _feishu_push(self, title, content, url=None, pic_url=None):
push_url = "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=" + self.feishu_receive_id_type
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer " + self._get_feishu_access_token()
}
body = {
"type": "template",
"data": {
"template_id": self.feishu_template_id,
"template_variable":
{
"pic": "img_v2_041b28e3-5680-48c2-9af2-497ace79333g",
"title": title,
"content": content,
"url": url
}
}
}
if pic_url is not None:
body["data"]["template_variable"]["pic"] = self._upload_feishu_image(pic_url)
payload = json.dumps({
"content": json.dumps(body),
"msg_type": "interactive",
"receive_id": self.feishu_receive_id
})
response = util.requests_post(push_url, '推送_feishu', headers=headers, data=payload)
logger.debug(response)
logger.info('【推送_feishu】{msg}'.format(msg='成功' if util.check_response_is_ok(response) else '失败'))


push = Push()
# push._feishu_push('test', 'test', 'https://baidu.com', 'test')

0 comments on commit d682464

Please sign in to comment.