> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chainlit.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Discord

To make your Chainlit app available on Discord, you will need to create a Discord app and set up the necessary environment variables.

## How it Works

The Discord bot will listen to messages mentioning it in channels and direct messages.
It will send replies to a dedicated thread or DM depending on the context.

<Frame caption="Preview">
  <img src="https://mintcdn.com/chainlit-43/b2WeFP1vh0enOZXn/images/discord/demo.gif?s=7f67eab9467b595b4d84b4bb08a49fc6" width="1692" height="1080" data-path="images/discord/demo.gif" />
</Frame>

## Supported Features

| Message | Streaming | Elements | Audio | Ask User | Chat History | Chat Profiles | Feedback |
| ------- | --------- | -------- | ----- | -------- | ------------ | ------------- | -------- |
| ✅       | ❌         | ✅        | ❌     | ❌        | ✅            | ❌             | ✅        |

## Install the Discord Library

The Discord library is not included in the Chainlit dependencies. You will have to install it manually.

```bash theme={null}
pip install discord
```

## Create a Discord App

To start, navigate to the [Discord apps dashboard](https://discord.com/developers/applications). Here, you should find a button that says New Application. When you click this button, select the option to create your app from scratch.

<Frame caption="Create a Discord App">
  <img src="https://mintcdn.com/chainlit-43/b2WeFP1vh0enOZXn/images/discord/create-app.png?fit=max&auto=format&n=b2WeFP1vh0enOZXn&q=85&s=4abf7fbc98cf38609868d8727526f327" width="2586" height="402" data-path="images/discord/create-app.png" />
</Frame>

## Set the Environment Variables

Navigate to the Bot tab and click on `Reset Token`. This will make the token visible. Copy it and set it as an environment variable in your Chainlit app.

<Frame caption="Copy the Bot Token">
  <img src="https://mintcdn.com/chainlit-43/b2WeFP1vh0enOZXn/images/discord/bot-token.png?fit=max&auto=format&n=b2WeFP1vh0enOZXn&q=85&s=c940da5c8e25a45120cb3fd8b547c1b7" width="3432" height="1458" data-path="images/discord/bot-token.png" />
</Frame>

```bash theme={null}
DISCORD_BOT_TOKEN=your_bot_token
```

## Set Intents

Navigate to the Bot tab and enable the `MESSAGE CONTENT INTENT`, then click on Save Changes.

<Frame caption="Set Intents">
  <img src="https://mintcdn.com/chainlit-43/b2WeFP1vh0enOZXn/images/discord/intent.png?fit=max&auto=format&n=b2WeFP1vh0enOZXn&q=85&s=b189cf3bc7838ae0163e7ac6c5234e81" width="3426" height="1742" data-path="images/discord/intent.png" />
</Frame>

## Working Locally

If you are working locally, you will have to expose your local Chainlit app to the internet to receive incoming messages to Discord. You can use [ngrok](https://ngrok.com/) for this.

```bash theme={null}
ngrok http 8000
```

## Start the Chainlit App

Since the Chainlit app is not running, the Discord bot will not be able to communicate with it.

For the example, we will use this simple app:

```python my_app.py theme={null}
import chainlit as cl

@cl.on_message
async def on_message(msg: cl.Message):
    # Access the original discord message
    print(cl.user_session.get("discord_message"))
    # Access the discord user
    print(cl.user_session.get("user"))

    # Access potential attached files
    attached_files = msg.elements

    await cl.Message(content="Hello World").send()
```

Start the Chainlit app.

<Note>
  Using -h to not open the default Chainlit UI since we are using Discord.
</Note>

```bash theme={null}
chainlit run my_app.py -h
```

## Install the Discord Bot to Your Workspace

Navigate to the OAuth2 tab. In the OAuth2 URL Generator, select the `bot` scope.

<Frame caption="Configure Installation">
  <img src="https://mintcdn.com/chainlit-43/b2WeFP1vh0enOZXn/images/discord/install-bot.png?fit=max&auto=format&n=b2WeFP1vh0enOZXn&q=85&s=a6f0cce686603895ea266404129bc04a" width="2568" height="1288" data-path="images/discord/install-bot.png" />
</Frame>

Then, in the Bot Permissions section, select the following permissions.

<Note>
  You can check that you have selected the right permissions by looking at the
  number of permissions parameter of the URL. It should be `377957238848`.
</Note>

<Frame caption="Bot Permissions">
  <img src="https://mintcdn.com/chainlit-43/b2WeFP1vh0enOZXn/images/discord/bot-permissions.png?fit=max&auto=format&n=b2WeFP1vh0enOZXn&q=85&s=ba9de1da2714e069968805bb7540e7b6" width="2526" height="1726" data-path="images/discord/bot-permissions.png" />
</Frame>

Copy the generated URL and paste it in your browser. You will be prompted to add the bot to a server. Select the server you want to add the bot to.

That's it! You should now be able to interact with your Chainlit app through Discord.

## Chat History

Chat history is directly available through discord.

```python theme={null}
from chainlit.discord.app import client as discord_client

import chainlit as cl
import discord

@cl.on_message
async def on_message(msg: cl.Message):
    # The user session resets on every Discord message.
    # So we add previous chat messages manually.
    messages = cl.user_session.get("messages", [])
    channel: discord.abc.MessageableChannel = cl.user_session.get("discord_channel")

    if channel:
        cl.user_session.get("messages")
        discord_messages = [message async for message in channel.history(limit=10)]

        # Go through last 10 messages and remove the current message.
        for x in discord_messages[::-1][:-1]:
            messages.append({
                "role": "assistant" if x.author.name == discord_client.user.name else "user",
                "content": x.clean_content if x.clean_content else x.channel.name # first message is empty
            })

    # Your code here
```
