'Interacting with Discord buttons using requests (Python)

I'm trying to automate clicking on discord buttons using requests (python), but I get error "400" every time I test it out. I found code here and add a couple modifications, but it is not working. Any ideas how to fix it? My code:

import requests
import time
import json
header = {'authorization': "authtoken"}

def buttonclicker():
    ButtonCLicker = {'content': "test"}
    ReqClicker = requests.post('https://discordapp.com/api/v9/channels/968490796116492310/messages',data=ButtonClicker,headers=header)
    time.sleep(2)
    r = requests.get("https://discord.com/api/v9/channels/968490796116492310/messages", headers = header)
    JData = json.loads(r.text)[0]
    print(JData,"\n-------------")
    data = {
        "type": 3,
        "guild_id": 'XXX',
        "channel_id": 'XXX',
        "message_id": JData['id'], 
        "application_id": 'XXX', 
        "data": {
                "component_type": 2,
                "custom_id": JData['components'][0]['components'][1]['custom_id'] 
                }
            }
    print(data, "\n--------")
    r = requests.post('https://discord.com/api/v9/interactions', json = data, headers = header)
    print(r.json)
buttonclicker()

Error from print(r.json):

<bound method Response.json of <Response [400]>>


Solution 1:[1]

You need session_id in data

Try this

import random, string
import requests
import time
import json
header = {'authorization': "authtoken"}

def buttonclicker():
    ButtonCLicker = {'content': "test"}
    ReqClicker = requests.post('https://discordapp.com/api/v9/channels/968490796116492310/messages',data=ButtonClicker,headers=header)
    time.sleep(2)
    r = requests.get("https://discord.com/api/v9/channels/968490796116492310/messages", headers = header)
    JData = json.loads(r.text)[0]
    sessionID = "".join(random.choice(string.ascii_letters + string.digits) for _ in range(32))
    print(JData,"\n-------------")
    data = {
        "type": 3,
        "guild_id": 'XXX',
        "channel_id": 'XXX',
        "message_id": JData['id'], 
        "application_id": 'XXX',
        "session_id": sessionID, 
        "data": {
                "component_type": 2,
                "custom_id": JData['components'][0]['components'][1]['custom_id'] 
                }
            }
    print(data, "\n--------")
    r = requests.post('https://discord.com/api/v9/interactions', json = data, headers = header)
    print(r.json)
buttonclicker()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mmaicus