Gradio 月活用户突破 100 万!

阅读更多
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 机器人开始,以确保一切正常运行。在名为 bot.py 的文件中编写以下 Python 代码,粘贴上一步中的 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 帐户,我们很乐意帮助你推广!