Sending a timed messege on discord with python

52 Views Asked by At

How do I send a message on discord channel from python? I tried YouTube videos they aren't working also I want the messages to be timed like after every 1 minute the message should go

import requests

token = '(my_token)'

channel_id = '(my_channel_id)'

message = 'thanks'


def sendmessage(token, channel_id, message):
    url = 'https://discord.com/api/v9/channels/{}/messages'.format(channel_id)

    data = {
        'content': message
    }
    header = {'authorisation': token}

    r = requests.post(url, data=data, headers=header)

sendmessage(token, channel_id, message)
1

There are 1 best solutions below

0
furas On

You have typo - it should be z in authorization.


Your code works for me if I run discord in browser and copy my private token from browser
but it doesn't work with my bot token.

For bot it needs:

headers = {'Authorization': f'Bot {token}'}

Eventually it may need also User-Agent with bot's name (but I'm not sure if it is really required) .

headers = {
    'Authorization': f'Bot {token}'}
    'User-Agent': 'FurasBot (https://blog.furas.pl, v0.1)',
}

Found in: sends messages to a discord channel using a bot via http POST


import requests

def send_message(token, channel_id, message, bot=False):

    if bot:
        headers = {'Authorization': f'Bot {token}'}
    else:
        headers = {'Authorization': token}

    url = f'https://discord.com/api/v9/channels/{channel_id}/messages'

    payload = {'content': message}
    
    response = requests.post(url, json=payload, headers=headers)

    data = response.json()
    
    print(data)

# --- main ---

user_token = 'xxxxxxxxxxxxxxxxxxxxxxxx.xxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'  # 70 chars
bot_token  = 'xxxxxxxxxxxxxxxxxxxxxxxx.xxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxx'             # 59 chars

channel_id = 7xxxxxxxxxxxxxxxxx  # 18 digits

message = 'Hello World!'

print('\n--- send as user ---\n')
send_message(user_token, channel_id, message)

print('\n--- send as bot ---\n')
send_message(bot_token, channel_id, message, bot=True)