通过webhook定时给飞书自定义机器人推送消息实现(python版)
通过webhook定时给飞书自定义机器人推送消息实现
官方接入文档
飞书自定义机器人使用指南
准备工作
安装python,我使用的版本是2.7(3.0+则简单)
安装APScheduler库, 这是一个Python定时任务框架
#python2.7
pip install apscheduler==3.6.3 --index-url https://pypi.tuna.tsinghua.edu.cn/simple
#python3.0+
pip install apscheduler
安装requests库
pip install requests
创建自定义机器人、获取webhook地址
代码实现
定时任务实现
# 本文件处理定时任务,详细api可以查找apscheduler
# coding:utf-8
from apscheduler.schedulers.blocking import BlockingScheduler
import subprocess
import logging
# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger('apscheduler')
logger.setLevel(logging.DEBUG) # 可以根据需要调整日志级别
# 执行send.py (arg是携带的参数,如不需要可删除)
def run_script(arg):
subprocess.call(["python", "send.py", str(arg)])
scheduler = BlockingScheduler()
# 添加定时任务9点(arg参数同理可删除)
scheduler.add_job(run_script, 'cron', hour=9, minute=0, args=(1,))
# 添加定时任务每5秒执行
scheduler.add_job(run_script, 'interval', seconds=5, args=(3,))
scheduler.start()
推送自定义消息
# coding:utf-8
import sys
import requests
WEBHOOK_URL = "" # 这里填写你的自定义机器人webhook地址
def getParams(message_type):
# params JSON
params = {}
if message_type == 1:
params = {
"msg_type": "text",
"content": {
"text": "新更新提醒"
}
return params
def sendMessage(params):
resp = requests.post(WEBHOOK_URL, json=params)
resp.raise_for_status()
result = resp.json()
if result.get("code") != 0:
print u"发送失败", result['msg']
else:
print(u"消息发送成功")
def main(message_type):
sendMessage(getParams(message_type))
if __name__ == '__main__':
if len(sys.argv) > 1:
try:
message_type = int(sys.argv[1])
main(message_type)
except ValueError:
print(u"参数错误")
else:
main(1)
可以用个批处理文件执行main.py即可
python main.py
最终效果
作者:用户0912