python脚本(一):飞书机器人实现新闻抓取与推送

发布于:2025-02-22 ⋅ 阅读:(15) ⋅ 点赞:(0)

根据飞书官方文档描述,可以在群组内增加飞书机器人来实现信息推送

自定义机器人使用指南 - 开发指南 - 开发文档 - 飞书开放平台

一、基于官方文档写一个基本文本推送的demo

# feishu_notifier.py
import requests
import json

def send_feishu_message(content, webhook_url, msg_type='text'):
    """
    发送消息到飞书机器人

    :param content: 消息内容(字符串或字典格式)
    :param webhook_url: 飞书机器人Webhook地址
    :param msg_type: 消息类型,默认为'text'
    :return: API响应内容或异常信息
    """
    payload = {
        "msg_type": msg_type,
        "content": {
            "text": content  # 自动处理字符串类型
        } if isinstance(content, str) else content
    }

    try:
        response = requests.post(
            webhook_url,
            headers={"Content-Type": "application/json"},
            data=json.dumps(payload)
        )
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        return {"status": "error", "message": str(e)}

        在其他文件可以通过引用该文件的概述实现信息推送,推送机器人的url可以在函数给默认值,或从外部传入。

二、通过访问开放api来获取新闻信息

我这里使用的链接是 'https://api.vvhan.com/api/hotlist/all',

可以获取到各个平台实时热度最高的新闻

然后对于新闻内容进行解析分类即可推送到飞书群组。

效果图如下

if __name__ == "__main__":
    # 测试配置
   

    # 执行完整流程
    result = send_platform_updates(FEISHU_WEBHOOK, CONFIG["MAX_ITEMS_PER_PLATFORM"])

    # 示例输出预览
    print("\n测试用例输出:")
    test_data = {
        "success": True,
        "data": [{
            "name": "微博",
            "update_time": "2025-02-19 21:00:00",
            "data": [{
                "title": "测试标题",
                "hot": "123.4万",
                "url": "https://example.com"
            }]
        }]
    }
    platforms = group_by_platform(test_data)
    print(format_platform_message("微博", platforms["微博"], 5))

代码稍微有点长,等有空放到git上。