Search code examples
pythonautomationdiscord

Error 401 while sending message via requests in discord


Here's my code to begin:

import requests

header = {"authorization": '[Redacted]'
         }
payload = {'content': "Test"}

r = requests.post(
  'https://discord.com/api/v9/channels/[Redacted]/messages',
                data=payload,
                headers=header
            )
print(r.status_code)

I want to send a message to a specific channel via my account (not through a bot). The code provided above used to work just fine for me a while back, but now it returns error code 401 [Unauthorized request]


Solution

  • Verify whether the authorization token or channel ID is correct.

    Your code is correct:

    header = {"authorization": token}
    payload = {"content": "Test"}
    
    r = requests.post(
        f"https://discord.com/api/v9/channels/{channel_id}/messages",
        data=payload,
        headers=header,
    )
    print(r.status_code)
    

    Output: 200