discord | discord messages | discord commands | Search

This module provides a set of functions for interacting with Discord channels, including retrieving user and guild channels, fetching messages from a channel with pagination, deleting a channel, and exporting these functions for use in other modules. The functions utilize a request authentication function requestAuthQ and configuration variables imported from separate modules to perform their respective operations.

Run example

npm run import -- "discord channels"

discord channels

var {
  DEFAULT_GUILD, DEFAULT_CHANNEL, MESSAGE_TIME,
  MESSAGES_START, 
} = importer.import("discord configuration")
const {requestAuthQ} = importer.import("discord request")

async function userChannels(userId = '@me') {
  return await requestAuthQ({
    method: 'GET',
    url: `channels/${userId}`
  })
}

async function guildChannels(guildId = DEFAULT_GUILD) {
  return await requestAuthQ({
    method: 'GET',
    url: `guilds/${guildId}/channels`
  })
}

async function channelMessagesB(channelId = DEFAULT_CHANNEL, messageTime = MESSAGE_TIME) {
  var params = {
    limit: 100,
    after: messageTime.toString()
  };
  var messages = await requestAuthQ({
    method: 'GET',
    url: `channels/${channelId}/messages`,
    params
  })
  if(messages.length == 100) {
    messages = messages.concat(await channelMessagesB(channelId, BigInt(messages[0].id) + BigInt(1)))
  }
  return messages
}

async function channelMessages(channelId = DEFAULT_CHANNEL, messageTime = MESSAGE_TIME) {
  var params = {
    limit: 100,
    after: (BigInt(Date.now() - MESSAGES_START - messageTime) << BigInt(22)).toString()
  };
  var messages = await requestAuthQ({
    method: 'GET',
    url: `channels/${channelId}/messages`,
    params
  })
  if(messages.length == 100) {
    messages = messages.concat(await channelMessagesB(channelId, BigInt(messages[0].id) + BigInt(1)))
  }
  return messages
}

async function deleteChannel(channelId) {
  return await requestAuthQ({
    method: 'DELETE',
    url: `channels/${channelId}`
  })
}

module.exports = {
  userChannels,
  guildChannels,
  channelMessages,
  deleteChannel
}

What the code could have been:

import { 
  DEFAULT_GUILD, 
  DEFAULT_CHANNEL, 
  MESSAGE_TIME,
  MESSAGES_START, 
} from 'discord configuration';
import { requestAuthQ } from 'discord request';

/**
 * Retrieves a list of channels for a given user.
 * 
 * @param {string} [userId=@me] The user ID to fetch channels for, defaults to '@me' if not provided.
 * @returns {Promise} A promise resolving to a list of channels.
 */
async function userChannels(userId = '@me') {
  return await requestAuthQ({
    method: 'GET',
    url: `channels/${userId}`
  });
}

/**
 * Retrieves a list of channels for a given guild.
 * 
 * @param {string} [guildId=DEFAULT_GUILD] The guild ID to fetch channels for, defaults to DEFAULT_GUILD if not provided.
 * @returns {Promise} A promise resolving to a list of channels.
 */
async function guildChannels(guildId = DEFAULT_GUILD) {
  return await requestAuthQ({
    method: 'GET',
    url: `guilds/${guildId}/channels`
  });
}

/**
 * Retrieves a list of messages for a given channel, up to 100 messages at a time.
 * 
 * @param {string} [channelId=DEFAULT_CHANNEL] The channel ID to fetch messages for, defaults to DEFAULT_CHANNEL if not provided.
 * @param {number} [messageTime=MESSAGE_TIME] The time to start fetching messages from, defaults to MESSAGE_TIME if not provided.
 * @returns {Promise} A promise resolving to a list of messages.
 */
async function channelMessagesB(channelId = DEFAULT_CHANNEL, messageTime = MESSAGE_TIME) {
  const params = {
    limit: 100,
    after: messageTime.toString()
  };
  const messages = await requestAuthQ({
    method: 'GET',
    url: `channels/${channelId}/messages`,
    params
  });
  if (messages.length === 100) {
    // TODO: Implement pagination for messages over 100.
    // Currently only fetches the next 100 messages.
    // Consider fetching in batches to handle very large channels.
    const nextMessageId = BigInt(messages[0].id) + BigInt(1);
    return messages.concat(await channelMessagesB(channelId, nextMessageId));
  }
  return messages;
}

/**
 * Retrieves a list of messages for a given channel, up to 100 messages at a time.
 * 
 * @param {string} [channelId=DEFAULT_CHANNEL] The channel ID to fetch messages for, defaults to DEFAULT_CHANNEL if not provided.
 * @param {number} [messageTime=MESSAGE_TIME] The time to start fetching messages from, defaults to MESSAGE_TIME if not provided.
 * @returns {Promise} A promise resolving to a list of messages.
 */
async function channelMessages(channelId = DEFAULT_CHANNEL, messageTime = MESSAGE_TIME) {
  const params = {
    limit: 100,
    after: (BigInt(Date.now() - MESSAGES_START - messageTime) << BigInt(22)).toString()
  };
  const messages = await requestAuthQ({
    method: 'GET',
    url: `channels/${channelId}/messages`,
    params
  });
  if (messages.length === 100) {
    // To be consistent with channelMessagesB, this implementation will also only fetch the next 100 messages.
    // Consider refactoring to allow for pagination in chunks.
    const nextMessageId = BigInt(messages[0].id) + BigInt(1);
    return messages.concat(await channelMessagesB(channelId, nextMessageId));
  }
  return messages;
}

/**
 * Deletes a channel by ID.
 * 
 * @param {string} channelId The ID of the channel to delete.
 * @returns {Promise} A promise resolving to a boolean indicating whether the deletion was successful.
 */
async function deleteChannel(channelId) {
  try {
    await requestAuthQ({
      method: 'DELETE',
      url: `channels/${channelId}`
    });
    return true;
  } catch (error) {
    console.error(`Error deleting channel ${channelId}:`, error);
    return false;
  }
}

export {
  userChannels,
  guildChannels,
  channelMessages,
  deleteChannel
};

Code Breakdown

Importing Configuration and Requests

var {
  DEFAULT_GUILD, DEFAULT_CHANNEL, MESSAGE_TIME,
  MESSAGES_START, 
} = importer.import('discord configuration')
const {requestAuthQ} = importer.import('discord request')

Imports configuration variables and a request function from separate modules.

User Channels Function

async function userChannels(userId = '@me') {
  return await requestAuthQ({
    method: 'GET',
    url: `channels/${userId}`
  })
}

Retrieves user channels for the specified userId or '@me' by default.

Guild Channels Function

async function guildChannels(guildId = DEFAULT_GUILD) {
  return await requestAuthQ({
    method: 'GET',
    url: `guilds/${guildId}/channels`
  })
}

Retrieves guild channels for the specified guildId or the default guild by default.

Channel Messages with Retrieval (Recursive)

async function channelMessagesB(channelId = DEFAULT_CHANNEL, messageTime = MESSAGE_TIME) {
  var params = {
    limit: 100,
    after: messageTime.toString()
  };
  var messages = await requestAuthQ({
    method: 'GET',
    url: `channels/${channelId}/messages`,
    params
  })
  if(messages.length == 100) {
    messages = messages.concat(await channelMessagesB(channelId, BigInt(messages[0].id) + BigInt(1)))
  }
  return messages
}

Retrieves 100 messages from the specified channelId at the specified messageTime, recursively fetching more messages until the end is reached.

Channel Messages Function

async function channelMessages(channelId = DEFAULT_CHANNEL, messageTime = MESSAGE_TIME) {
  var params = {
    limit: 100,
    after: (BigInt(Date.now() - MESSAGES_START - messageTime) << BigInt(22)).toString()
  };
  var messages = await requestAuthQ({
    method: 'GET',
    url: `channels/${channelId}/messages`,
    params
  })
  if(messages.length == 100) {
    messages = messages.concat(await channelMessagesB(channelId, BigInt(messages[0].id) + BigInt(1)))
  }
  return messages
}

Retrieves 100 messages from the specified channelId with a timestamp in the past by the specified messageTime, using a similar approach to channelMessagesB but with a different timestamp calculation.

Delete Channel Function

async function deleteChannel(channelId) {
  return await requestAuthQ({
    method: 'DELETE',
    url: `channels/${channelId}`
  })
}

Deletes the specified channelId using a DELETE request.

Module Exports

module.exports = {
  userChannels,
  guildChannels,
  channelMessages,
  deleteChannel
}

Exports the functions for use in other modules.