1. 聊天机器人
  2. 从 Gradio 应用创建 Slack 机器人

🚀 从 Gradio App 创建 Slack Bot 🚀

您可以将 Gradio 应用程序创建为 Slack bot,让 Slack 工作空间中的用户直接与其互动。

工作原理

Slack bot 将监听提到它的频道消息。当它收到消息(可以包含文本和文件)时,它将通过 Gradio 的内置 API 将其发送到您的 Gradio 应用程序。您的 bot 将回复从 API 接收到的响应。

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

先决条件

  • 安装最新版本的 gradioslack-bolt 库。
pip install --upgrade gradio slack-bolt~=1.0
  • 运行 Gradio 应用程序。该应用程序可以在本地运行,也可以在 Hugging Face Spaces 上运行。在本例中,我们将使用 Gradio Playground Space,它接收图像和/或文本,并生成相应的 Gradio 应用程序代码。

现在,我们准备开始!

1. 创建 Slack App

  1. 转到 api.slack.com/apps 并点击 "Create New App"
  2. 选择 "From scratch" 并为您的应用程序命名
  3. 选择要开发应用程序的工作空间
  4. 在 "OAuth & Permissions" 下,滚动到 "Scopes" 并添加这些 Bot Token Scopes
    • app_mentions:read
    • chat:write
    • files:read
    • files:write
  5. 在同一 "OAuth & Permissions" 页面上,向上滚动并点击按钮将应用程序安装到您的工作空间。
  6. 记下出现的 "Bot User OAuth Token"(以 xoxb- 开头),稍后我们需要它。
  7. 点击菜单栏中的 "Socket Mode"。页面加载后,点击切换按钮 "Enable Socket Mode"
  8. 为您的令牌命名,例如 socket-token,并复制生成的令牌(以 xapp- 开头),稍后我们需要它。
  9. 最后,转到菜单栏中的 "Event Subscription" 选项。点击切换按钮 "Enable Events" 并订阅 app_mention bot 事件。

2. 编写 Slack bot

让我们先编写一个非常简单的 Slack bot,以确保一切正常。在名为 bot.py 的文件中编写以下 Python 代码,粘贴上一节步骤 6 和步骤 8 中的两个令牌。

from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler

SLACK_BOT_TOKEN = # PASTE YOUR SLACK BOT TOKEN HERE
SLACK_APP_TOKEN = # PASTE YOUR SLACK APP TOKEN HERE

app = App(token=SLACK_BOT_TOKEN)

@app.event("app_mention")
def handle_app_mention_events(body, say):
    user_id = body["event"]["user"]
    say(f"Hi <@{user_id}>! You mentioned me and said: {body['event']['text']}")

if __name__ == "__main__":
    handler = SocketModeHandler(app, SLACK_APP_TOKEN)
    handler.start()

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

from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler

SLACK_BOT_TOKEN = # PASTE YOUR SLACK BOT TOKEN HERE
SLACK_APP_TOKEN = # PASTE YOUR SLACK APP TOKEN HERE

app = App(token=SLACK_BOT_TOKEN)
gradio_client = Client("abidlabs/gradio-playground-bot")

def download_image(url, filename):
    headers = {"Authorization": f"Bearer {SLACK_BOT_TOKEN}"}
    response = httpx.get(url, headers=headers)
    image_path = f"./images/{filename}"
    os.makedirs("./images", exist_ok=True)
    with open(image_path, "wb") as f:
        f.write(response.content)
    return image_path

def slackify_message(message):   
    # Replace markdown links with slack format and remove code language specifier after triple backticks
    pattern = r'\[(.*?)\]\((.*?)\)'
    cleaned = re.sub(pattern, r'<\2|\1>', message)
    cleaned = re.sub(r'```\w+\n', '```', cleaned)
    return cleaned.strip()

@app.event("app_mention")
def handle_app_mention_events(body, say):
    # Extract the message content without the bot mention
    text = body["event"]["text"]
    bot_user_id = body["authorizations"][0]["user_id"]
    clean_message = text.replace(f"<@{bot_user_id}>", "").strip()
    
    # Handle images if present
    files = []
    if "files" in body["event"]:
        for file in body["event"]["files"]:
            if file["filetype"] in ["png", "jpg", "jpeg", "gif", "webp"]:
                image_path = download_image(file["url_private_download"], file["name"])
                files.append(handle_file(image_path))
                break
    
    # Submit to Gradio and send responses back to Slack
    for response in gradio_client.submit(
        message={"text": clean_message, "files": files},
    ):
        cleaned_response = slackify_message(response[-1])
        say(cleaned_response)

if __name__ == "__main__":
    handler = SocketModeHandler(app, SLACK_APP_TOKEN)
    handler.start()

3. 将 bot 添加到您的 Slack 工作空间

现在,在您的 Slack 工作空间中创建一个新频道或导航到现有频道,您想在其中使用 bot。点击 Slack 侧边栏中 "Channels" 旁边的 "+" 按钮,按照提示创建一个新频道。

最后,邀请您的 bot 加入频道

  1. 在您的新频道中,输入 /invite @YourBotName
  2. 从下拉菜单中选择您的 bot
  3. 点击 "Invite to Channel"

4. 就是这样!

现在您可以在 bot 所在的任何频道中提及它,选择性地附加图像,它将回复生成的 Gradio 应用程序代码!

bot 将会

  1. 监听提及
  2. 处理任何附加图像
  3. 将文本和图像发送到您的 Gradio 应用程序
  4. 将响应流式传输回 Slack 频道

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

如果您使用 Gradio 应用程序构建了一个 Slack bot,请随时在 X 上分享并标记 Gradio 帐户,我们很高兴帮助您宣传!

gradio