Gradio 代理与 MCP 黑客马拉松

获奖者
Gradio logo
  1. 聊天机器人
  2. 从 Gradio 应用创建 Discord 机器人

🚀 使用 Gradio 创建 Discord 机器人 🚀

你可以将你的 Gradio 应用作为 Discord 机器人使用,让你的 Discord 服务器用户直接与其交互。

工作原理?

Discord 机器人将监听频道中提及它的消息。当它收到消息(可以包含文本和文件)时,它会通过 Gradio 的内置 API 将其发送到你的 Gradio 应用。你的机器人将回复从 API 接收到的响应。

由于 Gradio 的 API 非常灵活,你可以非常轻松地创建支持文本、图像、音频、流媒体、聊天记录和各种其他功能的 Discord 机器人。

先决条件

  • 安装最新版本的 gradiodiscord.py
pip install --upgrade gradio discord.py~=2.0
  • 有一个正在运行的 Gradio 应用。此应用可以在本地运行,也可以在 Hugging Face Spaces 上运行。在此示例中,我们将使用 Gradio Playground Space,它接收图像和/或文本,并生成相应的 Gradio 应用代码。

现在,我们准备开始!

1. 创建 Discord 应用

首先,前往 Discord 应用控制面板。找到“New Application”(新应用)按钮并点击它。为你的应用命名,然后点击“Create”(创建)。

在结果屏幕上,你将看到有关你应用的基本信息。在“Settings”(设置)部分下,点击“Bot”(机器人)选项。如果需要,你可以更新机器人的用户名。

然后点击“Reset Token”(重置令牌)按钮。将生成一个新令牌。复制它,因为下一步我们需要它。

向下滚动到“Privileged Gateway Intents”(特权网关意图)部分。你的机器人需要某些权限才能正常工作。在本教程中,我们将只使用“Message Content Intent”(消息内容意图),因此点击切换按钮以启用此意图。保存更改。

2. 编写 Discord 机器人

让我们从编写一个非常简单的 Discord 机器人开始,只是为了确保一切正常。将以下 Python 代码写入名为 bot.py 的文件中,并粘贴上一步中获取的 Discord 机器人令牌

# 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,它应该运行并打印类似以下消息

We have logged in as GradioPlaygroundBot#1451

如果一切正常,我们就可以添加 Gradio 特定代码了。我们将使用 Gradio Python 客户端 来查询上面提到的 Gradio Playground Space。这是更新后的 bot.py 文件

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)

3. 将机器人添加到你的 Discord 服务器

现在我们准备好将机器人安装到我们的服务器上。返回 Discord 应用控制面板。在“Settings”(设置)部分下,点击“OAuth2”选项。向下滚动到“OAuth2 URL Generator”(OAuth2 URL 生成器)框并选择“bot”(机器人)复选框

然后在弹出的“Bot Permissions”(机器人权限)框中,启用以下权限

复制下方生成的 URL,它应该看起来像这样

https://discord.com/oauth2/authorize?client_id=1319011745452265575&permissions=377957238784&integration_type=0&scope=bot

将其粘贴到你的浏览器中,这将允许你将 Discord 机器人添加到你管理的任何 Discord 服务器。

4. 大功告成!

现在你可以在 Discord 服务器的任何频道中提及你的机器人,选择性地附加一张图片,它将用生成的 Gradio 应用代码进行回复!

该机器人将

  1. 监听提及

  2. 处理所有附加图像

  3. 将文本和图像发送到你的 Gradio 应用

  4. 将响应流式传输回 Discord 频道

    这只是一个基本示例——你可以扩展它以处理更多类型的文件、添加错误处理,或与不同的 Gradio 应用集成。

如果你使用 Gradio 应用构建了 Discord 机器人,请随时在 X 上分享并标记 Gradio 账号,我们很乐意帮助你进行推广!