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 帐户,我们很乐意帮助您推广!

gradio