0
Create Discord thread and send messages
One script reply has been approved by the moderators Verified

This script is designed to automate the process of creating a thread in a Discord channel and populating it with a series of messages using a Discord bot. It starts by validating the lengths of the thread name and all messages to ensure they comply with Discord's character limits. If validations pass, it proceeds to create the thread and then sequentially sends the first message, an array of messages, and a final message to the thread. The script handles errors and rate limiting by Discord's API, ensuring that messages are only sent if the thread creation is successful and retrying message sends if rate-limited. Needed bot permissions are: 'Create Private Threads' and 'Send Messages'

Created by henri186 40 days ago Viewed 3340 times
0
Submitted by henri186 Bun
Verified 40 days ago
1
type DiscordBotConfiguration = {
2
  public_key: string,
3
  application_id: string
4
};
5

6
/**
7
 * Creates a thread in Discord and sends a series of messages to it using the Discord bot configuration.
8
 * The series starts with a firstMessage, followed by the messages array, and ends with a lastMessage.
9
 * Before attempting to create the thread, it validates that all messages (including first and last) are within the character limit.
10
 * If any message exceeds the limit, it throws an error without creating the thread.
11
 * @param discordBotConfigResource Contains the Discord bot configuration necessary for API requests.
12
 * @param channelId The ID of the Discord channel where the thread will be created.
13
 * @param threadName The name of the thread to be created. Must be 100 characters or less.
14
 * @param firstMessage The first message to be sent to the thread. Must be 2000 characters or less.
15
 * @param messages An array of messages to be sent to the thread after the firstMessage and before the lastMessage. Each message must be 2000 characters or less.
16
 * @param lastMessage The last message to be sent to the thread. Must be 2000 characters or less.
17
 * @returns An object indicating the success status of thread creation and each message sent.
18
 * @throws Error if the thread creation or any message sending fails, or if input validations fail.
19
 */
20
export async function main(
21
  discordBotConfigResource: DiscordBotConfiguration,
22
  channelId: string,
23
  threadName: string,
24
  firstMessage: string,
25
  messages: string[],
26
  lastMessage: string
27
): Promise<{ thread: boolean; messages: boolean[] }> {
28
  // First, validate threadName length
29
  if (threadName.length > 100) {
30
    throw new Error("Thread name must be 100 characters or less.");
31
  }
32

33
  // Validate firstMessage and lastMessage length
34
  if (firstMessage.length > 2000) {
35
    throw new Error("First message must be 2000 characters or less.");
36
  }
37
  if (lastMessage.length > 2000) {
38
    throw new Error("Last message must be 2000 characters or less.");
39
  }
40

41
  // Next, validate each message length in the array. This ensures all messages are checked before any API request is made.
42
  for (const message of messages) {
43
    if (message.length > 2000) {
44
      throw new Error("Each message must be 2000 characters or less.");
45
    }
46
  }
47

48
  // Initialize the result object
49
  const result = {
50
    thread: false,
51
    messages: []
52
  };
53

54
  // Construct the URL for creating a thread
55
  const createThreadUrl = `https://discord.com/api/v9/channels/${channelId}/threads`;
56

57
  // Prepare the request body for creating a thread
58
  const createThreadBody = JSON.stringify({
59
    name: threadName,
60
    auto_archive_duration: 60, // Automatically archive the thread after 60 minutes of inactivity
61
    type: 11 // Type 11 represents a private thread
62
  });
63

64
  // Prepare the request headers
65
  const headers = {
66
    'Content-Type': 'application/json',
67
    'Authorization': `Bot ${discordBotConfigResource.public_key}`
68
  };
69

70
  // Attempt to create the thread by sending a POST request
71
  const createThreadResponse = await fetch(createThreadUrl, {
72
    method: 'POST',
73
    headers: headers,
74
    body: createThreadBody
75
  });
76

77
  if (!createThreadResponse.ok) {
78
    throw new Error("Failed to create thread");
79
  }
80

81
  // Parse the response to get the thread ID
82
  const threadInfo = await createThreadResponse.json();
83
  const threadId = threadInfo.id;
84
  result.thread = true; // Mark thread creation as successful
85

86
  // Function to send a message to the created thread
87
const sendMessage = async (message: string) => {
88
  // Construct the URL for sending a message to the thread
89
  const sendMessageUrl = `https://discord.com/api/v9/channels/${threadId}/messages`;
90

91
  // Prepare the request body for sending a message
92
  const messageBody = JSON.stringify({
93
    content: message
94
  });
95

96
  // Attempt to send the message by sending a POST request
97
  const sendMessageResponse = await fetch(sendMessageUrl, {
98
    method: 'POST',
99
    headers: headers,
100
    body: messageBody
101
  });
102

103
  // Check for rate limit response before checking if response is OK
104
  if (sendMessageResponse.status === 429) { // 429 is the HTTP status code for Too Many Requests
105
      const retryAfter = parseInt(sendMessageResponse.headers.get('Retry-After'), 10);
106
      console.log(`Rate limit hit, retrying after ${retryAfter} seconds.`);
107
      await new Promise(resolve => setTimeout(resolve, retryAfter * 1000)); // Wait for the duration specified by Retry-After
108
      return sendMessage(message); // Attempt to resend the message
109
  }
110

111
  if (!sendMessageResponse.ok) {
112
    throw new Error(`Failed to send message: ${message}`);
113
  }
114

115
  // Record the success status of sending each message
116
  result.messages.push(true);
117
};
118

119
  // Send the first message
120
  await sendMessage(firstMessage);
121

122
  // Send messages in the array
123
  for (const message of messages) {
124
    await sendMessage(message);
125
  }
126

127
  // Send the last message
128
  await sendMessage(lastMessage);
129

130
  return result;
131
}