What is the best way to reorganize Discord channels based on numerical order when interacting with the application?

Whenever someone submits an application for the server, a designated channel is created at the top of the server (view example here). However, responding to these applications in a consistent order has proven challenging due to various factors. Once I respond to an application, the channel is closed and moved to a category called "Past Channels" (see example here). The issue arises when trying to order the channels within the category based on the application number rather than placing them at the top.

I have attempted the following method, but it has not yielded the desired outcome. It is important to note that I am coding in TypeScript.

function setPosition(client: myClient, channel: TextChannel) {
    const regex = /\d{4}$/;
    const appnum = Number(regex.exec(channel.name)![0]);
    console.log(`[SLASH COMMANDS] Application #${appnum} has been processed.`);
    const category = client.channels.cache.get(client.categoryPastApplications);
    if (!category || category.type !== ChannelType.GuildCategory) {
        console.log(
            `[SLASH COMMANDS] An error occurred while executing the "application" command! Error #6`
        );
        return;
    }
    const channelsCategory = category.children.cache.sort((a, b) => a.position - b.position);
    channelsCategory.forEach((categoryChannel) => {
        if (Number(regex.exec(categoryChannel.name)![0]) > appnum) {
            channel.setPosition(categoryChannel.position + 1);
        }
    });
}

Update: I attempted a different approach with the function as shown below, but the issue persists.

async function setPosition(client: myClient, channel: TextChannel) {
    const regex = /\d{4}$/;
    const appnum = Number(regex.exec(channel.name)![0]);
    console.log(`[SLASH COMMANDS] Application #${appnum} has been processed.`);
    const category = client.channels.cache.get(client.categoryPastApplications);
    if (!category || category.type !== ChannelType.GuildCategory) {
        console.log(
            `[SLASH COMMANDS] An error occurred while executing the "application" command! Error #6`
        );
        return;
    }
    const channelsCategory = category.children.cache.sort((a, b) => a.position - b.position);
    Object.values(channelsCategory).forEach(async (categoryChannel, index) => {
        if (Number(regex.exec(categoryChannel.name)![0]) < appnum) {
            await channel.setPosition(index + 1);
        }
    });
}

Answer №1

It seems like you're looking to organize the channels based on their numbers. If all the channels have the same naming format, you can give this solution a try.

//Make sure to wrap the code in an async function for await to function properly.

const category = client.channels.cache.get(client.categoryPastApplications);
let toSortArr = [];
let elements = category.children.cache.forEach((channel) => {
    let channelName = channel.name.substring(channel.name.indexOf("app"));
                
    toSortArr.push(channelName);
});
let sort = toSortArr.sort();

for (let [channelId, channel] of category.children.cache) {
    let channelName = channel.name.substring(channel.name.indexOf("app"));
    let index = sort.indexOf(channelName);

    await channel.setPosition(index);
}

It's recommended to use a regular for loop instead of forEach for asynchronous methods like async/await. As shown in the example above, using for of loop is a better option.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating multiple copies of a form div in Angular using Typescript

I'm attempting to replicate a form using Angular, but I keep getting the error message "Object is possibly 'null'". HTML: <div class="form-container"> <form class="example"> <mat-form-field> ...

Guide to Reverting the Two-Way ngModel Binding Data in Angular 2

I am utilizing a form in angular 2 that includes two-way binding data value ([(ngModel)]) to enable both edit and add functionality. When a user selects the edit option on the listing page and modifies the input, the new values automatically appear on the ...

Is there a way to establish a data type using a specific key within the Record<K, T> structure in Typescript?

Imagine the scenario where an object type needs to be created and linked to a specific key specified in Record<Keys, Type>. Let's say there is a type called User, which can have one of three values - user, admin, or moderator. A new type called ...

Is there a way to implement personalized error management in TypeScript with Express?

For a while now, I have been using JavaScript to create my APIs but recently made the switch to TypeScript. However, I keep encountering errors along the way. One particular error handler I have set up is for when a route cannot be found, as shown below: i ...

What could be the reason for the file element being undefined in the context menu?

I am currently working on rebuilding my context menu for the second time today. I am encountering an issue with an undefined value of my file element, which is preventing me from deleting, renaming, or performing any other actions. HTML <mat-list-item ...

Retrieve data from a URL using Angular 6's HTTP POST method

UPDATE: Replaced res.json(data) with res.send(data) I am currently working on a web application using Angular 6 and NodeJS. My goal is to download a file through an HTTP POST request. The process involves sending a request to the server by calling a func ...

Unable to globally override the default font in MUI theme

Objective: My goal is to customize the default font in MUI themes. Issue: Despite reviewing MUI documentation and conducting research on Stack Overflow, I am facing difficulty overriding a custom font globally across my theme. Theme setup: import { creat ...

Displaying hidden Divs in React Typescript that are currently not visible

I have an array with various titles ranging from Title1 to Title8. When these titles are not empty, I am able to display their corresponding information successfully. Now, my goal is to include a button that will allow me to show all fields. For example, ...

Is there a way to extract a specific item from a ListView by tapping on it in Nativescript?

Attempting to retrieve data from a tap event using angular2 + typescript: This is the html code for the component: <RadListView row="1" [items]="groceryList" [class.visible]="listLoaded" (tap)="seeItem($event)" swipeActions="true" (itemSwipeProgr ...

Exporting the interface for the state of the redux store

After setting up a redux module, I have organized the following files: //state.tsx export default interface State { readonly user: any; readonly isLoggedIn: boolean; } //types.tsx export default { REQUEST: 'authentication/REQUEST', SUC ...

Error: React is throwing a SyntaxError because a ")" is missing in the argument list

While working on a React-typescript project using Vite, I encountered an issue where my page was displaying blank and showing the error : Uncaught SyntaxError: missing ) after argument list (at main.tsx:6:51) This error was found in the main.tsx file : im ...

What is the best way to retrieve class members using component properties?

I am looking to implement a mixin for setting the header and meta data in my project. I recently discovered vue-meta, which seems to work really well for this purpose. However, I am still getting acquainted with TypeScript and class-based components. How ...

Setting up WebPack for TypeScript with import functionality

A tutorial on webpack configuration for typescript typically demonstrates the following: const path = require('path'); module.exports = { ... } Is it more advantageous to utilize ES modules and configure it with import statements instead? Or is ...

Ways to declare the function prototype using object and key as parameters

I am currently working on defining a utility function that will handle axios errors and store the resulting error message into a specific field of a specified object. The desired syntax for using this function is: axios.get(...).then(...).catch(ParseIntoE ...

Error encountered in Angular with Karma and Jasmine: The function this.Service.<foo> is not defined in the Lifecycle Hook

When running Karma and Jasmine tests using the npm run test -- --no-watch --no-progress command with Karma/Jasmine, an error is thrown: Chrome 92.0.4515.159 (Mac OS 10.15.7) LoginComponent should create FAILED TypeError: this.loggerService.onDebug is n ...

Manipulate classes by adding or removing them on click events in Angular

I am struggling to implement the angular ngClass for adding a class with a click event. Despite calling a function that should change the value of the "isExpandedConectivity" variable when clicking on the "li" element, it doesn't seem to work as expec ...

Exploring the Power of Vercel Deployment: Crafting a Custom CORS Middleware for Your API

Recently, I have been testing different methods to avoid a CORS error in my upcoming app deployed on Vercel. The only solution that worked for me was manually setting the headers for each API request, as shown below: export default async function handler( ...

Creating a default option in a Select tag with React when iterating over elements using the map method

After learning that each element in the dropdown must be given by the Option tag when using Select, I created an array of values for the dropdown: a = ['hai','hello','what'] To optimize my code, I wrote it in the following ...

Make sure to call the loader function in React Router only when there are path params present

I'm currently implementing the new React Router, utilizing loader functions to fetch data based on the loaded element. My goal is to have certain APIs called regardless of the route, with additional APIs triggered for specific routes. However, I&apos ...

Merging Promises in Typescript

In summary, my question is whether using a union type inside and outside of generics creates a different type. As I develop an API server with Express and TypeScript, I have created a wrapper function to handle the return type formation. This wrapper fun ...