如何用Python脚本通过Midjourney机器人在Discord发送Prompt并获取图片URL
解决Discord Midjourney命令发送与图片URL获取问题
一、修复Slash命令发送问题
直接发送content: "/imagine..."会被Discord识别为纯文本,因为Slash命令需要通过交互API的特定结构发送,而非普通消息格式。以下是修正后的代码:
import requests import time # 替换为你的实际参数 AUTH_TOKEN = "你的Discord授权令牌" CHANNEL_ID = "目标频道ID" GUILD_ID = "服务器ID" MIDJOURNEY_APP_ID = "936929561302675456" # Midjourney机器人固定ID url = "https://discord.com/api/v9/interactions" headers = { 'Authorization': AUTH_TOKEN, 'Content-Type': 'application/json' } # 构造Slash命令请求体(部分参数需从Discord抓包获取最新值) payload = { "type": 2, "application_id": MIDJOURNEY_APP_ID, "guild_id": GUILD_ID, "channel_id": CHANNEL_ID, "session_id": str(int(time.time())), # 用时间戳生成临时会话ID "data": { "version": "1118961510123847772", # 从抓包获取imagine命令的最新版本号 "id": "938956540159881230", # 从抓包获取imagine命令的ID "name": "imagine", "type": 1, "options": [ { "type": 3, "name": "prompt", "value": "dog with sun" } ], "attachments": [] } } # 发送命令 response = requests.post(url, headers=headers, json=payload) response.raise_for_status() # 检查请求是否成功
注意事项:
version和id参数可能随Midjourney更新变化,建议自己通过Discord开发者工具(F12)抓包一次正常的/imagine请求,替换为最新值。session_id可任意填写字符串,用时间戳是简单的生成方式。
二、获取生成的图片URL
Midjourney生成图片后会向频道发送消息,我们可以通过轮询频道消息,过滤出机器人发送的带图片内容,提取URL:
def get_midjourney_image(channel_id, auth_token, max_wait=120): start_time = time.time() midjourney_bot_id = "936929561302675456" msg_url = f"https://discord.com/api/v9/channels/{channel_id}/messages?limit=50" headers = {'Authorization': auth_token} while time.time() - start_time < max_wait: response = requests.get(msg_url, headers=headers) response.raise_for_status() messages = response.json() # 遍历消息,筛选Midjourney机器人发送的带图片内容 for msg in messages: if (msg['author']['id'] == midjourney_bot_id and 'attachments' in msg and len(msg['attachments']) > 0): return msg['attachments'][0]['url'] time.sleep(5) # 每5秒轮询一次 return None # 调用函数获取图片URL image_url = get_midjourney_image(CHANNEL_ID, AUTH_TOKEN) if image_url: print(f"生成图片URL:{image_url}") else: print("超时未获取到图片")
说明:
max_wait设置最大等待时长(秒),根据Midjourney生成速度调整,一般1-2分钟足够。- 每次轮询取最近50条消息,避免遗漏刚生成的图片。
内容的提问来源于stack exchange,提问作者szczery
相关产品推荐
相关产品推荐

