How to use the Discord API in Python
Tags: api, python, tutorial
Published: 2023-11-30 15:15:51

---
title: How to use the Discord API in Python
published: true
date: 2023-08-30 22:00:00 UTC
tags: API, Python, Tutorial
canonical_url: https://blog.apify.com/python-discord-api/
---

Discover how to interact with Discord using Python for tasks like sending, reading, updating, and deleting messages. We also guide you through enabling developer mode, getting your Discord token, and finding channel IDs.

Ever thought of automating tasks on Discord or integrating it with your own application? In this tutorial, we'll show you how to interact with Discord using Python. You'll learn how to send messages, read them back, update them, and even delete them.

>💡 [**Click for a more detailed post on how to use Python to connect and interact with APIs**](https://blog.apify.com/python-and-apis/)

## **Using Python with the Discord API**

To work with the Discord API, first, [create a server](https://support.discord.com/hc/en-us/articles/204849977-How-do-I-create-a-server-) on your Discord account. Then, enable developer mode by clicking on the settings button in the bottom left corner -> Advanced -> Enable Developer Mode.

Now, to work with the Discord API, you also need a token and the channel ID (where you want to send the message or retrieve the message from). To get the channel ID, right-click on any channel (such as _#general_) and copy the channel ID.

For the token, follow these steps:

1. Open Discord in a browser and open developer mode by pressing Ctrl+Shift+I.

2. Go to Application -> Local Storage -> Click on [https://discord.com/](https://blog.apify.com/python-and-apis/) -> Click on Filter.

![How to use the Discord API in Python: Inspecting Discord in developer mode](https://lh5.googleusercontent.com/JB2DArDX3Lk6ii1gHJ6hjTPu3Gu0Bo3paRrE_Par3bduGEtPLjA5Cva8J_XHiRro6bhyXQdeDJtaE4oOfYYQqAciB_SK2BzSjrkNDu71j4mtrQz_H1L-6njw1EaQI01d1pYFojkjFu84O7JUQDx8-g)

3. Search for "_token_" in the filter and copy the token.

![How to use the Discord API in Python: Finding the right Discord token](https://lh4.googleusercontent.com/-Vx9EeIrr4c8hoK2pvH--glwpDjG6T3O1oH8QhbLFtRsq4V7GyJNHpGlYXrBGOY-0sdvVuhrXNfbri_UdP5NK8sz0RRMCDP99VNcObRFm_IVTTum44ykBDdSubdYvAgjjkNrqhIFjATh-Irm1HMK9w)

Now you have the token and channel ID. Let's send some messages using a Python POST request.

```
import requests

def message_post(token, channel_id, message):
    url = f"https://discord.com/api/v9/channels/{channel_id}/messages"

    headers = {
        "Authorization": f"{token}",
    }

    data = {
        "content": message
    }

    response = requests.post(url, headers=headers, json=data)

    if response.status_code == 200:
        print("Message sent successfully.")
    else:
        print("Failed to send the message.")
        print(response.text)

token = "YOUR DISCORD TOKEN"
channel_id = "CHANNEL ID"
message = "Hey, How are you?"

message_post(token, channel_id, message)

```

The code output is this:

![How to use the Discord API in Python: Output message from sending POST request to Discord API](https://lh5.googleusercontent.com/0puFjzMnsqnVlvjPcJL2zXJdJLMDWt4FnWSelHZ7FajMwhoi_MlSB10iwhBoZLEkOewrXLox6ti96XIjYIuWAWeerqDTkxLdeHuWcDOOqmlCfY0t216eZHEYoh_vcVGskM-knT6oILD7CDQVdUZvlA)

The message has been sent successfully, as you can see above. Now, read/retrieve the messages from the channel using a Python GET request.

```
import requests

def read_message(channel_id, token):
    url = f"https://discord.com/api/v9/channels/{channel_id}/messages"

    header = {
        "Authorization": f"{token}"
    }

    response = requests.get(url, headers=header)

    if response.status_code == 200:
        messages = response.json()
        return messages
    else:
        print("Failed to fetch messages.")
        print(response.text)
        return None

token = "YOUR DISCORD TOKEN"
channel_id = "CHANNEL ID"

messages = read_message(channel_id, token)

if messages:
    for message in messages:
        print(f"{message['content']}")
else:
    print("Failed to read messages.")

```

The above code will read all the messages that are in the channel.

Next, update the message using a Python PATCH request. To do this, you also need a message ID of the message that is to be updated. Go to the channel and right-click on the message to copy the message ID.

```
msg_id = response.json()    
msg_id = f"{url}/{msg_id['id']}"

```

Use the _requests.patch()_ function to make a PATCH request and pass the _token_, _channel\_id_, _message\_id_, and _new message_ to be updated.

```
import requests

def update_message(token, channel_id, message_id, new_message):
    url = f"https://discord.com/api/v9/channels/{channel_id}/messages/{message_id}"

    headers = {
        "Authorization": f"{token}",
    }

    data = {
        "content": new_message
    }

    response = requests.patch(url, headers=headers, json=data)

    if response.status_code == 200:
        print(f"Message has been updated successfully.")
    else:
        print("Failed to edit the message.")

token = "YOUR DISCORD TOKEN"
channel_id = "CHANNEL ID"
message_id = "YOUR MESSAGE ID"
new_message = "Hey, this message has been updated using the PATCH request."

update_message(token, channel_id, message_id, new_message)

```

Heres the code output:

![How to use the Discord API in Python: Output message from sending PATCH request via Discord API](https://lh4.googleusercontent.com/OhGMvyu_vphsYEeUcy-o8HPMjpgw9yetyjRpe7QAfw0eOpy4vtqmOr97C-txeF--fQXwwJzKXFhzF1SrQ0h5ZSAwdiN7VgLu4_3wQk-W2TrIt2SEJnKVoV4xDkLkXnJsuv1Pec1YWJQQU17J7Cybgg)

Next, delete the message using the _requests.delete()_ function.

```
import requests

def delete_message(token, channel_id, message_id):
    url = f"https://discord.com/api/v9/channels/{channel_id}/messages/{message_id}"
    headers = {
        "Authorization": f"{token}",
    }

    response = requests.delete(url, headers=headers)

    if response.status_code == 204:
        print(f"Message has been deleted successfully.")
    else:
        print("Failed to delete the message.")
        print(response.text)

token = "YOUR DISCORD TOKEN"
channel_id = "CHANNEL ID"
message_id = "YOUR MESSAGE ID"

delete_message(token, channel_id, message_id)

```

That's it. You've just learned how to interact with Discord using Python. From setting up your server and enabling developer mode to managing tokens and channel IDs, you're now equipped to send, read, update, and even delete messages. We hope that this gives you lots of ideas for automating tasks or enhancing your Discord communities.

If you're into using Python, you might like to explore [web scraping with Python](https://blog.apify.com/web-scraping-python/) or learn about [Python and machine learning](https://blog.apify.com/python-machine-learning/).