Edits history of script submission #6021 for ' Create Discord thread and send messages (discord)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    type DiscordBotConfiguration = {
      public_key: string,
      application_id: string
    };
    
    /**
     * Creates a thread in Discord and sends a series of messages to it using the Discord bot configuration.
     * The series starts with a firstMessage, followed by the messages array, and ends with a lastMessage.
     * Before attempting to create the thread, it validates that all messages (including first and last) are within the character limit.
     * If any message exceeds the limit, it throws an error without creating the thread.
     * @param discordBotConfigResource Contains the Discord bot configuration necessary for API requests.
     * @param channelId The ID of the Discord channel where the thread will be created.
     * @param threadName The name of the thread to be created. Must be 100 characters or less.
     * @param firstMessage The first message to be sent to the thread. Must be 2000 characters or less.
     * @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.
     * @param lastMessage The last message to be sent to the thread. Must be 2000 characters or less.
     * @returns An object indicating the success status of thread creation and each message sent.
     * @throws Error if the thread creation or any message sending fails, or if input validations fail.
     */
    export async function main(
      discordBotConfigResource: DiscordBotConfiguration,
      channelId: string,
      threadName: string,
      firstMessage: string,
      messages: string[],
      lastMessage: string
    ): Promise<{ thread: boolean; messages: boolean[] }> {
      // First, validate threadName length
      if (threadName.length > 100) {
        throw new Error("Thread name must be 100 characters or less.");
      }
    
      // Validate firstMessage and lastMessage length
      if (firstMessage.length > 2000) {
        throw new Error("First message must be 2000 characters or less.");
      }
      if (lastMessage.length > 2000) {
        throw new Error("Last message must be 2000 characters or less.");
      }
    
      // Next, validate each message length in the array. This ensures all messages are checked before any API request is made.
      for (const message of messages) {
        if (message.length > 2000) {
          throw new Error("Each message must be 2000 characters or less.");
        }
      }
    
      // Initialize the result object
      const result = {
        thread: false,
        messages: []
      };
    
      // Construct the URL for creating a thread
      const createThreadUrl = `https://discord.com/api/v9/channels/${channelId}/threads`;
    
      // Prepare the request body for creating a thread
      const createThreadBody = JSON.stringify({
        name: threadName,
        auto_archive_duration: 60, // Automatically archive the thread after 60 minutes of inactivity
        type: 11 // Type 11 represents a private thread
      });
    
      // Prepare the request headers
      const headers = {
        'Content-Type': 'application/json',
        'Authorization': `Bot ${discordBotConfigResource.public_key}`
      };
    
      // Attempt to create the thread by sending a POST request
      const createThreadResponse = await fetch(createThreadUrl, {
        method: 'POST',
        headers: headers,
        body: createThreadBody
      });
    
      if (!createThreadResponse.ok) {
        throw new Error("Failed to create thread");
      }
    
      // Parse the response to get the thread ID
      const threadInfo = await createThreadResponse.json();
      const threadId = threadInfo.id;
      result.thread = true; // Mark thread creation as successful
    
      // Function to send a message to the created thread
    const sendMessage = async (message: string) => {
      // Construct the URL for sending a message to the thread
      const sendMessageUrl = `https://discord.com/api/v9/channels/${threadId}/messages`;
    
      // Prepare the request body for sending a message
      const messageBody = JSON.stringify({
        content: message
      });
    
      // Attempt to send the message by sending a POST request
      const sendMessageResponse = await fetch(sendMessageUrl, {
        method: 'POST',
        headers: headers,
        body: messageBody
      });
    
      // Check for rate limit response before checking if response is OK
      if (sendMessageResponse.status === 429) { // 429 is the HTTP status code for Too Many Requests
          const retryAfter = parseInt(sendMessageResponse.headers.get('Retry-After'), 10);
          console.log(`Rate limit hit, retrying after ${retryAfter} seconds.`);
          await new Promise(resolve => setTimeout(resolve, retryAfter * 1000)); // Wait for the duration specified by Retry-After
          return sendMessage(message); // Attempt to resend the message
      }
    
      if (!sendMessageResponse.ok) {
        throw new Error(`Failed to send message: ${message}`);
      }
    
      // Record the success status of sending each message
      result.messages.push(true);
    };
    
      // Send the first message
      await sendMessage(firstMessage);
    
      // Send messages in the array
      for (const message of messages) {
        await sendMessage(message);
      }
    
      // Send the last message
      await sendMessage(lastMessage);
    
      return result;
    }

    Submitted by hugo697 378 days ago

  • bun
    type DiscordBotConfiguration = {
      public_key: string,
      application_id: string
    };
    
    /**
     * Creates a thread in Discord and sends a series of messages to it using the Discord bot configuration.
     * The series starts with a firstMessage, followed by the messages array, and ends with a lastMessage.
     * Before attempting to create the thread, it validates that all messages (including first and last) are within the character limit.
     * If any message exceeds the limit, it throws an error without creating the thread.
     * @param discordBotConfigResource Contains the Discord bot configuration necessary for API requests.
     * @param channelId The ID of the Discord channel where the thread will be created.
     * @param threadName The name of the thread to be created. Must be 100 characters or less.
     * @param firstMessage The first message to be sent to the thread. Must be 2000 characters or less.
     * @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.
     * @param lastMessage The last message to be sent to the thread. Must be 2000 characters or less.
     * @returns An object indicating the success status of thread creation and each message sent.
     * @throws Error if the thread creation or any message sending fails, or if input validations fail.
     */
    export async function main(
      discordBotConfigResource: DiscordBotConfiguration,
      channelId: string,
      threadName: string,
      firstMessage: string,
      messages: string[],
      lastMessage: string
    ): Promise<{ thread: boolean; messages: boolean[] }> {
      // First, validate threadName length
      if (threadName.length > 100) {
        throw new Error("Thread name must be 100 characters or less.");
      }
    
      // Validate firstMessage and lastMessage length
      if (firstMessage.length > 2000) {
        throw new Error("First message must be 2000 characters or less.");
      }
      if (lastMessage.length > 2000) {
        throw new Error("Last message must be 2000 characters or less.");
      }
    
      // Next, validate each message length in the array. This ensures all messages are checked before any API request is made.
      for (const message of messages) {
        if (message.length > 2000) {
          throw new Error("Each message must be 2000 characters or less.");
        }
      }
    
      // Initialize the result object
      const result = {
        thread: false,
        messages: []
      };
    
      // Construct the URL for creating a thread
      const createThreadUrl = `https://discord.com/api/v9/channels/${channelId}/threads`;
    
      // Prepare the request body for creating a thread
      const createThreadBody = JSON.stringify({
        name: threadName,
        auto_archive_duration: 60, // Automatically archive the thread after 60 minutes of inactivity
        type: 11 // Type 11 represents a private thread
      });
    
      // Prepare the request headers
      const headers = {
        'Content-Type': 'application/json',
        'Authorization': `Bot ${discordBotConfigResource.public_key}`
      };
    
      // Attempt to create the thread by sending a POST request
      const createThreadResponse = await fetch(createThreadUrl, {
        method: 'POST',
        headers: headers,
        body: createThreadBody
      });
    
      if (!createThreadResponse.ok) {
        throw new Error("Failed to create thread");
      }
    
      // Parse the response to get the thread ID
      const threadInfo = await createThreadResponse.json();
      const threadId = threadInfo.id;
      result.thread = true; // Mark thread creation as successful
    
      // Function to send a message to the created thread
    const sendMessage = async (message: string) => {
      // Construct the URL for sending a message to the thread
      const sendMessageUrl = `https://discord.com/api/v9/channels/${threadId}/messages`;
    
      // Prepare the request body for sending a message
      const messageBody = JSON.stringify({
        content: message
      });
    
      // Attempt to send the message by sending a POST request
      const sendMessageResponse = await fetch(sendMessageUrl, {
        method: 'POST',
        headers: headers,
        body: messageBody
      });
    
      // Check for rate limit response before checking if response is OK
      if (sendMessageResponse.status === 429) { // 429 is the HTTP status code for Too Many Requests
          const retryAfter = parseInt(sendMessageResponse.headers.get('Retry-After'), 10);
          console.log(`Rate limit hit, retrying after ${retryAfter} seconds.`);
          await new Promise(resolve => setTimeout(resolve, retryAfter * 1000)); // Wait for the duration specified by Retry-After
          return sendMessage(message); // Attempt to resend the message
      }
    
      if (!sendMessageResponse.ok) {
        throw new Error(`Failed to send message: ${message}`);
      }
    
      // Record the success status of sending each message
      result.messages.push(true);
    };
    
      // Send the first message
      await sendMessage(firstMessage);
    
      // Send messages in the array
      for (const message of messages) {
        await sendMessage(message);
      }
    
      // Send the last message
      await sendMessage(lastMessage);
    
      return result;
    }

    Submitted by henri186 793 days ago