如何将 Gradio 应用接入 Discord 服务器作为可交互 Bot
【免费下载链接】gradio Build and share delightful machine learning apps, all in Python. 🌟 Star to support our work! 项目地址: https://gitcode.com/GitHub_Trending/gr/gradio
如果你已经有一个能正常运行的 Gradio 应用,并想让自己的 Discord 服务器成员直接在频道里和它交互,可以把这个应用包一层 Discord Bot:Bot 监听提及它的消息(可包含文本和文件),通过 Gradio 内置 API 把请求转发给你的应用,并把返回结果回复到频道。因为走的是 Gradio API,所以文本、图片、音频、流式返回、聊天历史等能力都可以沿用。
工作原理与适用前提
接入方式基于 discord.py 客户端 + gradio_client 两个库:
- Bot 监听服务器频道中提及它(mention)的消息;
- 收到消息后,把文本和附件通过 Gradio 应用的 API 提交;
- 把 API 返回的结果(支持流式)逐条发回频道。
前提条件:
- 一个正在运行的 Gradio 应用,本地运行或部署在 Hugging Face Spaces 均可。下文示例使用的是 Gradio Playground Space,它接收图片和/或文本,生成对应的 Gradio 应用代码;
- 一个已创建、已获取 Token 的 Discord 应用(见下一步)。
安装依赖
按照文档要求,安装最新版 gradio 和 discord.py(限定 2.0 系列):
pip install –upgrade gradio discord.py~=2.0
这里需要说明一个版本事实:早期版本中 gradio_client 的 Client 类提供过 deploy_discord() 方法用于一键部署 Discord Bot,该方法已被弃用并在 Gradio 6.0 中移除(见 Gradio 6 迁移指南)。所以当前版本应采用本文的手动接入方式,迁移指南也指向本指南作为替代方案。
在 Discord 开发者后台创建应用并获取 Token
编写并首次运行最小 Bot
先用一个最小 Bot 验证 Token 和权限配置是否正确。创建 bot.py,把上一步复制的 Token 粘贴到 TOKEN 处:
# bot.py
import discord
TOKEN = #PASTE YOUR DISCORD BOT TOKEN HERE
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
client.run(TOKEN)
运行:
python bot.py
成功时终端会打印类似下面的登录信息(文档示例,具体账号名和编号因你的 Bot 而异):
We have logged in as GradioPlaygroundBot#1451
看到这个输出,说明 Token、Intent 配置都没问题,可以开始加 Gradio 相关代码。
完整 Bot 代码:转发消息到 Gradio 应用并流式回复
下面的 bot.py 是文档给出的完整示例,使用 Gradio Python Client 查询 Gradio Playground Space。其中 TOKEN 替换为你的 Discord Bot Token;Client("abidlabs/gradio-playground-bot") 指向示例所用的 Gradio 应用地址,接入你自己的应用时替换为对应地址即可:
import discord
from gradio_client import Client, handle_file
import httpx
import os
TOKEN = #PASTE YOUR DISCORD BOT TOKEN HERE
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
gradio_client = Client("abidlabs/gradio-playground-bot")
def download_image(attachment):
response = httpx.get(attachment.url)
image_path = f"./images/{attachment.filename}"
os.makedirs("./images", exist_ok=True)
with open(image_path, "wb") as f:
f.write(response.content)
return image_path
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
# Ignore messages from the bot itself
if message.author == client.user:
return
# Check if the bot is mentioned in the message and reply
if client.user in message.mentions:
# Extract the message content without the bot mention
clean_message = message.content.replace(f"<@{client.user.id}>", "").strip()
# Handle images (only the first image is used)
files = []
if message.attachments:
for attachment in message.attachments:
if any(attachment.filename.lower().endswith(ext) for ext in ['png', 'jpg', 'jpeg', 'gif', 'webp']):
image_path = download_image(attachment)
files.append(handle_file(image_path))
break
# Stream the responses to the channel
for response in gradio_client.submit(
message={"text": clean_message, "files": files},
):
await message.channel.send(response[-1])
client.run(TOKEN)
代码里几个关键点:
- 必须显式开启 intents.message_content = True,否则读取不到消息内容,与后台启用 "Message Content Intent" 是对应的;
- Bot 只处理提及它本人的消息,忽略自己发的消息,避免自我循环;
- 图片附件会被下载到本地 ./images/ 目录,再用 handle_file 包装后随文本一起提交给 Gradio API;代码中明确注释了只处理第一张图片,且仅限 png/jpg/jpeg/gif/webp 后缀;
- gradio_client.submit(…) 按流式迭代,每一帧都会 message.channel.send(response[-1]) 发回频道,这就是"流式回复"的实现方式。
再次运行 python bot.py,确认终端出现登录信息后,Bot 即可在服务器中响应。
把 Bot 邀请到你的 Discord 服务器
https://discord.com/oauth2/authorize?client_id=1319011745452265575&permissions=377957238784&integration_type=0&scope=bot
注意这是文档示例 URL,client_id 对应示例作者的应用,你必须使用自己后台生成的 URL。
验证接入是否成功
在服务器任意频道中:
如果 Bot 完全没反应,对照前面的最小 Bot 验证步骤检查:终端是否出现登录信息、"Message Content Intent" 是否已在后台和代码中同时开启、Bot 是否已成功邀请进目标服务器。
限制与可拓展方向
- 示例只处理第一张图片,且只支持 png、jpg、jpeg、gif、webp 后缀的附件;
- 回复以 response[-1] 逐帧发送,如果你的 Gradio 应用返回结构不同,需要按自身输出格式调整取值方式;
- 文档也指出这只是基础示例,可以在此基础上拓展更多文件类型、增加错误处理、或替换为其他 Gradio 应用。
完整指南原文见 Discord Bot 教程。
【免费下载链接】gradio Build and share delightful machine learning apps, all in Python. 🌟 Star to support our work! 项目地址: https://gitcode.com/GitHub_Trending/gr/gradio
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

