Home > OS >  Python Request Send Massage again in same channel
Python Request Send Massage again in same channel

Time:09-25

Is there any way if the status response code of CHANNEL_ID_1comes 200, then it should not send the message again in the same channel.

USERS_TOKEN = "TOKEN"
CHANNEL_ID_1 = "CHANNELID HERE"
CHANNEL_ID_2 = "CHANNELID HERE"
CHANNEL_ID_3 = "CHANNELID HERE"
CHANNEL_ID_4 = "CHANNELID HERE"
MESSAGE_1 = "msg 1 channel 1"
MESSAGE_2 = "msg 2 channel 2"
MESSAGE_3 = "msg 3 channel 3"
MESSAGE_4 = "msg 4 channel 4"
msgcount = "10"
def sendMessage(token, channel_id, message):
    url = 'https://discord.com/api/v9/channels/{}/messages'.format(channel_id)
    data = {"content": message}
    header = {"authorization": token}

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

for i in range(int(msgcount)):
    time.sleep(0.3)
    sendMessage(USERS_TOKEN, CHANNEL_ID_1, MESSAGE_1)
    sendMessage(USERS_TOKEN, CHANNEL_ID_2, MESSAGE_2)
    sendMessage(USERS_TOKEN, CHANNEL_ID_3, MESSAGE_3)
    sendMessage(USERS_TOKEN, CHANNEL_ID_4, MESSAGE_4)

plz modify that code its really helpful for me

CodePudding user response:

If I understand the question correctly, I would suggest this code structure.

[ Note: This is untested ]

import requests
import time

USERS_TOKEN = "TOKEN"
MDICT = {"CHANNEL_1": "message_1",
         "CHANNEL_2": "message_2",
         "CHANNEL_3": "message_3",
         "CHANNEL_4": "message_4"
         }
msgcount = 10


def sendMessage(token, channel_id, message):
    url = f'https://discord.com/api/v9/channels/{channel_id}/messages'
    data = {"content": message}
    header = {"authorization": token}
    with requests.Session() as session:
        return session.post(url, data=data, headers=header).status_code


while msgcount > 0 and MDICT:
    time.sleep(0.3)
    key = next(iter(MDICT.keys()))
    if sendMessage(USERS_TOKEN, key, MDICT[key]) == 200:
        del MDICT[key]
    msgcount -= 1
  • Related