【Python接口自动化】调用飞书机器人

发布于:2025-09-05 ⋅ 阅读:(15) ⋅ 点赞:(0)
  1. 创建飞书自定义机器人
    打开飞书,进入你想要接收消息的群聊

点击群聊右上角的设置(三个点)

选择 「群机器人」 → 「添加机器人」 → 「自定义机器人」

设置机器人名称和描述,并复制生成的Webhook URL(务必妥善保管,避免泄露)

2、Python脚本

import requests
import json

def send_feishu_message_webhook(webhook_url, message):
    """
    通过Webhook发送飞书群消息
    :param webhook_url: 机器人的Webhook URL
    :param message: 要发送的文本消息
    """
    headers = {"Content-Type": "application/json; charset=utf-8"}
    # 构建消息体
    payload = {
        "msg_type": "text",
        "content": {
            "text": message
        }
    }
    
    # 发送POST请求
    response = requests.post(webhook_url, headers=headers, data=json.dumps(payload))
    result = response.json()
    
    # 检查是否发送成功
    if result.get("code") == 0:
        print("消息发送成功!")
        return True
    else:
        print(f"消息发送失败: {result.get('msg')}")
        return False

# 使用示例
if __name__ == "__main__":
    webhook_url = "https://open.feishu.cn/open-apis/bot/v2/hook/你的WEBHOOK_TOKEN"  # 替换为你的真实Webhook URL
    message_content = "你好,飞书!这是通过Python脚本发送的消息。"
    send_feishu_message_webhook(webhook_url, message_content)

3、更多消息类型

  1. 富文本消息 (Post)
# 在Webhook的payload中替换为以下内容
payload = {
    "msg_type": "post",
    "content": {
        "post": {
            "zh_cn": {
                "title": "项目更新通知",
                "content": [
                    [{
                        "tag": "text",
                        "text": "项目有新的更新: "
                    }, {
                        "tag": "a",
                        "text": "点击查看详情",
                        "href": "https://www.example.com"
                    }]
                ]
            }
        }
    }
}

2.消息卡片 (Interactive)

# 在Webhook的payload中替换为以下内容
payload = {
    "msg_type": "interactive",
    "card": {
        "elements": [{
            "tag": "div",
            "text": {
                "content": "**西湖**,位于浙江省杭州市西湖区龙井路1号,杭州市区西部,景区总面积49平方千米。",
                "tag": "lark_md"
            }
        }, {
            "actions": [{
                "tag": "button",
                "text": {
                    "content": "更多景点介绍 :rose:",
                    "tag": "lark_md"
                },
                "url": "https://www.example.com",
                "type": "default"
            }],
            "tag": "action"
        }],
        "header": {
            "title": {
                "content": "今日旅游推荐",
                "tag": "plain_text"
            }
        }
    }
}```


网站公告

今日签到

点亮在社区的每一天
去签到