danni-cool / wechatbot-webhook

轻量、可部署的微信机器人webhook服务,使用http接口收发微信消息, 用它作为个人通知、AIGC 应用或者 coze、n8n等自动化工作流的消息节点
MIT License
1.6k stars 276 forks source link

FastAPI怎样接收bot发送的图片 #241

Closed swyxjk closed 2 months ago

swyxjk commented 2 months ago

接收图片的格式怎么设置?

app = FastAPI()

@app.post("/receive_msg") async def receive_msg(type: str = Form(), content: str = Form(),source:str = Form()):

https://github.com/danni-cool/wechatbot-webhook?tab=readme-ov-file#2-%E6%94%B6%E6%B6%88%E6%81%AF-api 看不明白

danni-cool commented 2 months ago

receive_msg回调 的 payload 整体是一个form

swyxjk commented 2 months ago
from fastapi import FastAPI, Form,File,UploadFile
from pydantic import BaseModel # 引入BaseModel
from typing import Union, List, Optional

# 创建payload 模型
class payload (BaseModel):
    type: str
    content: Union[str,UploadFile] = None
    #content: Optional[UploadFile] = None
    source: Optional[str] = None
    isMentioned: Optional[str] = None
    isMsgFromSelf: Optional[str] = None

@app.post("/receive_msg")
async def receive_message(payload:payload=Form()):
    print(payload)
    type_str = payload.type

    if type_str == 'file':
    # 文件名
        filename_1 = payload.content.filename
    # 发送者昵称
        name = json.loads(payload.source)['from']['payload']['name']

        # 读取文件内容
        file_content = await payload.content.read()

        # 保存文件到磁盘
        with open(filename_1, 'wb') as f:
            f.write(file_content)

        return
danni-cool commented 2 months ago

解决了话可以关掉issue