用python借用飞书机器人群发布定期内容
最近在切换使用飞书。
在群管理里有个功能,就是可以添加一个自定义的机器人,为了方便定期的发布和提醒业务。可采用:
1.使用Webhook和定时任务
新建群机器人:
在需要接收通知的群组中新建群机器人,并获取Webhook地址。
配置消息卡片:
在飞书开放平台新建消息卡片并编辑内容,复制代码。
新建飞书捷径:
选择触发器并设定触发时间(例如每周定时),选择Webhook并配置。
完成配置:
测试触发器是否正常工作,确保消息可以按时发送到群组
上代码:
import requests
import time
import hmac
import hashlib
import base64
from datetime import datetimeWEBHOOK_URL = "webhook配置"
SECRET = "webhook配置"def gen_sign(timestamp, secret):string_to_sign = f'{timestamp}\n{secret}'hmac_code = hmac.new(secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256).digest()sign = base64.b64encode(hmac_code).decode('utf-8')return signdef send_message(content):timestamp = int(time.time())sign = gen_sign(timestamp, SECRET)headers = {"Content-Type": "application/json;charset=utf-8"}data = {"msg_type": "text","content": {"text": content},"timestamp": timestamp,"sign": sign}response = requests.post(WEBHOOK_URL, json=data, headers=headers)if response.status_code == 200:print("消息发送成功")print("响应内容:", response.json()) # 打印响应内容,便于调试else:print("消息发送失败")print("状态码:", response.status_code)print("响应内容:", response.text) # 打印错误信息if __name__ == "__main__":send_message("发布的内容")