Skip to main content
Once you’ve deployed your Gradio Chat Interface, it’s easy to use in other applications because of the built-in API. Here are guides for deploying your chatbot to different platforms:

Discord bot

You can make your Gradio app available as a Discord bot to let users in your Discord server interact with it directly.

How does it work?

The Discord bot will listen to messages mentioning it in channels. When it receives a message (which can include text as well as files), it will send it to your Gradio app via Gradio’s built-in API. Your bot will reply with the response it receives from the API. Because Gradio’s API is very flexible, you can create Discord bots that support text, images, audio, streaming, chat history, and a wide variety of other features very easily. Discord bot demo

Prerequisites

Install the latest version of gradio and the discord.py libraries:
pip install --upgrade gradio discord.py~=2.0
Have a running Gradio app. This app can be running locally or on Hugging Face Spaces. In this example, we will be using the Gradio Playground Space, which takes in an image and/or text and generates the code to generate the corresponding Gradio app.

Create a Discord application

1

Create new application

First, go to the Discord apps dashboard. Look for the “New Application” button and click it. Give your application a name, and then click “Create”.Discord create app
2

Configure bot settings

On the resulting screen, you will see basic information about your application. Under the Settings section, click on the “Bot” option. You can update your bot’s username if you would like.Then click on the “Reset Token” button. A new token will be generated. Copy it as we will need it for the next step.Scroll down to the section that says “Privileged Gateway Intents”. Your bot will need certain permissions to work correctly. In this tutorial, we will only be using the “Message Content Intent” so click the toggle to enable this intent. Save the changes.Discord bot settings

Write a Discord bot

Let’s start by writing a very simple Discord bot, just to make sure that everything is working. Write the following Python code in a file called bot.py, pasting the discord bot token from the previous step:
# 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)
Now, run this file: python bot.py, which should run and print a message like:
We have logged in as GradioPlaygroundBot#1451
If that is working, we are ready to add Gradio-specific code. We will be using the Gradio Python Client to query the Gradio Playground Space mentioned above. Here’s the updated bot.py file:
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)

Add the bot to your Discord server

1

Generate OAuth2 URL

Now we are ready to install the bot on our server. Go back to the Discord apps dashboard. Under the Settings section, click on the “OAuth2” option. Scroll down to the “OAuth2 URL Generator” box and select the “bot” checkbox:Discord OAuth2
2

Set permissions

Then in “Bot Permissions” box that pops up underneath, enable the following permissions:Discord permissions
3

Install bot

Copy the generated URL that appears underneath, which should look something like:
https://discord.com/oauth2/authorize?client_id=1319011745452265575&permissions=377957238784&integration_type=0&scope=bot
Paste it into your browser, which should allow you to add the Discord bot to any Discord server that you manage.

That’s it!

Now you can mention your bot from any channel in your Discord server, optionally attach an image, and it will respond with generated Gradio app code! The bot will:
  1. Listen for mentions
  2. Process any attached images
  3. Send the text and images to your Gradio app
  4. Stream the responses back to the Discord channel
This is just a basic example—you can extend it to handle more types of files, add error handling, or integrate with different Gradio apps. If you build a Discord bot from a Gradio app, feel free to share it on X and tag the Gradio account, and we are happy to help you amplify!

Slack bot

You can make your Gradio app available as a Slack bot to let users in your Slack workspace interact with it directly.

How does it work?

The Slack bot will listen to messages mentioning it in channels. When it receives a message (which can include text as well as files), it will send it to your Gradio app via Gradio’s built-in API. Your bot will reply with the response it receives from the API. Because Gradio’s API is very flexible, you can create Slack bots that support text, images, audio, streaming, chat history, and a wide variety of other features very easily. Slack bot demo

Prerequisites

Install the latest version of gradio and the slack-bolt library:
pip install --upgrade gradio slack-bolt~=1.0
Have a running Gradio app. This app can be running locally or on Hugging Face Spaces. In this example, we will be using the Gradio Playground Space, which takes in an image and/or text and generates the code to generate the corresponding Gradio app.

Create a Slack app

1

Create new app

  1. Go to api.slack.com/apps and click “Create New App”
  2. Choose “From scratch” and give your app a name
  3. Select the workspace where you want to develop your app
2

Configure permissions

  1. Under “OAuth & Permissions”, scroll to “Scopes” and add these Bot Token Scopes:
    • app_mentions:read
    • chat:write
    • files:read
    • files:write
3

Install app

  1. In the same “OAuth & Permissions” page, scroll back up and click the button to install the app to your workspace
  2. Note the “Bot User OAuth Token” (starts with xoxb-) that appears as we’ll need it later
4

Enable Socket Mode

  1. Click on “Socket Mode” in the menu bar. When the page loads, click the toggle to “Enable Socket Mode”
  2. Give your token a name, such as socket-token and copy the token that is generated (starts with xapp-) as we’ll need it later
5

Enable events

  1. Finally, go to the “Event Subscription” option in the menu bar. Click the toggle to “Enable Events” and subscribe to the app_mention bot event

Write a Slack bot

Let’s start by writing a very simple Slack bot, just to make sure that everything is working. Write the following Python code in a file called bot.py, pasting the two tokens from the previous section:
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()
If that is working, we are ready to add Gradio-specific code. We will be using the Gradio Python Client to query the Gradio Playground Space mentioned above. Here’s the updated bot.py file:
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from gradio_client import Client, handle_file
import httpx
import os
import re

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
    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()

Add the bot to your Slack workspace

Now, create a new channel or navigate to an existing channel in your Slack workspace where you want to use the bot. Click the ”+” button next to “Channels” in your Slack sidebar and follow the prompts to create a new channel. Finally, invite your bot to the channel:
  1. In your new channel, type /invite @YourBotName
  2. Select your bot from the dropdown
  3. Click “Invite to Channel”

That’s it!

Now you can mention your bot in any channel it’s in, optionally attach an image, and it will respond with generated Gradio app code! The bot will:
  1. Listen for mentions
  2. Process any attached images
  3. Send the text and images to your Gradio app
  4. Stream the responses back to the Slack channel
This is just a basic example—you can extend it to handle more types of files, add error handling, or integrate with different Gradio apps! If you build a Slack bot from a Gradio app, feel free to share it on X and tag the Gradio account, and we are happy to help you amplify!

Website widget

You can make your Gradio Chatbot available as an embedded chat widget on your website, similar to popular customer service widgets like Intercom. This is particularly useful for:
  • Adding AI assistance to your documentation pages
  • Providing interactive help on your portfolio or product website
  • Creating a custom chatbot interface for your Gradio app
Website widget demo

How does it work?

The chat widget appears as a small button in the corner of your website. When clicked, it opens a chat interface that communicates with your Gradio app via the JavaScript Client API. Users can ask questions and receive responses directly within the widget.

Prerequisites

A running Gradio app (local or on Hugging Face Spaces). In this example, we’ll use the Gradio Playground Space, which helps generate code for Gradio apps based on natural language descriptions.

Create and style the chat widget

First, add this HTML and CSS to your website:
<div id="chat-widget" class="chat-widget">
    <button id="chat-toggle" class="chat-toggle">💬</button>
    <div id="chat-container" class="chat-container hidden">
        <div id="chat-header">
            <h3>Gradio Assistant</h3>
            <button id="close-chat">×</button>
        </div>
        <div id="chat-messages"></div>
        <div id="chat-input-area">
            <input type="text" id="chat-input" placeholder="Ask a question...">
            <button id="send-message">Send</button>
        </div>
    </div>
</div>

<style>
.chat-widget {
    position: fixed;
    bottom: 20px;
    right: 20px;
    z-index: 1000;
}

.chat-toggle {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background: #007bff;
    border: none;
    color: white;
    font-size: 24px;
    cursor: pointer;
}

.chat-container {
    position: fixed;
    bottom: 80px;
    right: 20px;
    width: 300px;
    height: 400px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
    display: flex;
    flex-direction: column;
}

.chat-container.hidden {
    display: none;
}

#chat-header {
    padding: 10px;
    background: #007bff;
    color: white;
    border-radius: 10px 10px 0 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

#chat-messages {
    flex-grow: 1;
    overflow-y: auto;
    padding: 10px;
}

#chat-input-area {
    padding: 10px;
    border-top: 1px solid #eee;
    display: flex;
}

#chat-input {
    flex-grow: 1;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-right: 8px;
}

.message {
    margin: 8px 0;
    padding: 8px;
    border-radius: 4px;
}

.user-message {
    background: #e9ecef;
    margin-left: 20px;
}

.bot-message {
    background: #f8f9fa;
    margin-right: 20px;
}
</style>

Add the JavaScript

Then, add the following JavaScript code (which uses the Gradio JavaScript Client to connect to the Space) to your website by including this in the <head> section:
<script type="module">
    import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js";
    
    async function initChatWidget() {
        const client = await Client.connect("https://abidlabs-gradio-playground-bot.hf.space");
        
        const chatToggle = document.getElementById('chat-toggle');
        const chatContainer = document.getElementById('chat-container');
        const closeChat = document.getElementById('close-chat');
        const chatInput = document.getElementById('chat-input');
        const sendButton = document.getElementById('send-message');
        const messagesContainer = document.getElementById('chat-messages');
    
        chatToggle.addEventListener('click', () => {
            chatContainer.classList.remove('hidden');
        });
    
        closeChat.addEventListener('click', () => {
            chatContainer.classList.add('hidden');
        });
    
        async function sendMessage() {
            const userMessage = chatInput.value.trim();
            if (!userMessage) return;

            appendMessage(userMessage, 'user');
            chatInput.value = '';

            try {
                const result = await client.predict("/chat", {
                    message: {"text": userMessage, "files": []}
                });
                const botMessage = result.data[0].join('\n');
                appendMessage(botMessage, 'bot');
            } catch (error) {
                console.error('Error:', error);
                appendMessage('Sorry, there was an error processing your request.', 'bot');
            }
        }
    
        function appendMessage(text, sender) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${sender}-message`;
            messageDiv.textContent = text;
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }
    
        sendButton.addEventListener('click', sendMessage);
        chatInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') sendMessage();
        });
    }
    
    initChatWidget();
</script>

That’s it!

Your website now has a chat widget that connects to your Gradio app! Users can click the chat button to open the widget and start interacting with your app.

Customization

You can customize the appearance of the widget by modifying the CSS. Some ideas:
  • Change the colors to match your website’s theme
  • Adjust the size and position of the widget
  • Add animations for opening/closing
  • Modify the message styling
If you build a website widget from a Gradio app, feel free to share it on X and tag the Gradio account, and we are happy to help you amplify!