2
votes

I'm creating a bot for an educational server on Discord, and many times I need to quickly clone voice channels to perform tasks in small groups. These channels must belong to the same category from where the command is executed, and maintain the same permissions as the original channel. Also I need to handle via message which channel is duplicated, and how many times.

I managed to retrieve the category and the voice channels contained within it, according to where the command is executed. The bot returns a message with a list of voice channels, and adds an index to identify them like this:

1 - Channel Name
2 - Channel Name
etc...

What I am not achieving is that just by indicating the "index" of the channel, and then the number of times you want to clone it, it executes the clone function.

What I have so far is the following (sorry, this is in Spanish, the server is from Argentina):

        else if (command === 'canales') {
            if (!message.member.hasPermission('MANAGE_CHANNELS')) {
                message.channel.send('No podés crear canales en este espacio, solo podés hacerlo en las secciones que administrás.');
                return;
            }
            const filter = message.author;
            const seccion = message.channel.parentID;
            const voiceEnParent = await message.guild.channels.cache.filter(c => c.type === 'voice' && c.parentID === seccion);
            const canalesArray = voiceEnParent.map(u => u.name);
            const canalesIdArray = voiceEnParent.map(u => u.id);
            let startString = '';
            let pregunta = '';

            for (let i = 0; i < canalesArray.length; i++) {
                pregunta = startString += '**' + (i + 1) + '** - ' + canalesArray[i] + '\n';
            }
            message.channel.send(`**¿Que canal deseas duplicar?** Respondé a este mensaje únicamente con el número de indice del canal, según se indica:\n\n${pregunta}`).then(() => {

                message.channel.awaitMessages(filter, {
                  max: 1,
                  time: 15000,
                  errors: ['time'],
                }).then(msg => {
                   const index = msg.first();
                  if (!isNaN(index.content)) {
                        message.channel.send('**¿Cuantas copias del canal querés hacer?**\n(Ingresá un valor numérico del 1 al 10)').then(() => {

                            message.channel.awaitMessages(filter, {
                                max: 1,
                                time: 15000,
                                errors: ['time'],
                            }).then(async emj => {
                                const cantidad = emj.first();
                                if (isNaN(cantidad.content)) {
                                    message.channel.send('La cantidad ingresada es incorrecta, o no es un valor numérico.');
                                    return;
                                }
                                else {
                                    message.channel.send(`Genial. Creé un total de ${cantidad} copias del canal ${canalesArray[(index.content - 1)]}`);
                                    let numInicio = 0;
                                    let intentos = 0;
                                    do {
                                        message.guild.channel(canalesIdArray[index.content]).clone();
                                        intentos = numInicio += 1;
                                    }
                                    while (intentos < cantidad);
                                
                                    return console.log(`${cantidad} copias creadas.`);
                                }
                            })
                                .catch(() => {
                                    message.channel.send('Se acabó el tiempo.');
                                });
                        })
                            .catch(error => {
                                message.channel.send(`Se acabó el tiempo. **Error:** ${error}`);
                            });
                    }
                    else {
                        message.channel.send('El indice ingresado no existe, o no es un valor numérico.');
                        return;
                    }
                })
                    .catch(error => {
                        message.channel.send(error);
                    });
            });

            message.delete({ timeout: 6000 });
        }

Everything works just fine until I respond to this message the bot sends:

message.channel.send(`**¿Que canal deseas duplicar?** Respondé a este mensaje únicamente con el número de indice del canal, según se indica:\n\n${pregunta}`).then(() => {

When on Discord I reply to that message I get this error in my console, and the bot crashes.

    if (collect && (await this.filter(...args, this.collected))) {
                                                    ^

TypeError: Function.prototype.apply was called on [object Object], which is a object and not a function

Any ideas where to continue?

1
Sorry to see you haven't received any help on Stack Overflow yet. Try asking in the official Discord.JS Discord ServerElitezen
Finally find the solution by myself!!. Thank you, anyway.Julián Gak

1 Answers

0
votes

[SOLVED]
Finally find the solution by myself. Here I share my approach if anyone need it:

else if (command === 'canales') {
            if (!message.member.hasPermission('MANAGE_CHANNELS')) {
                message.channel.send('No podés crear canales en este espacio, solo podés hacerlo en las secciones que administrás.');
                return;
            }
            const filter = m => m.author.id === message.author.id;
            const seccion = message.channel.parentID;
            const voiceEnParent = await message.guild.channels.cache.filter(c => c.type === 'voice' && c.parentID === seccion);
            const canalesArray = voiceEnParent.map(u => u.name);
            const canalesIdArray = voiceEnParent.map(u => u.id);
            let startString = '';
            let pregunta = '';
            for (let i = 0; i < canalesArray.length; i++) {
                pregunta = startString += '**' + (i + 1) + '** - ' + canalesArray[i] + '\n';
            }
            message.channel.send(`**¿Que canal deseas duplicar?** Respondé a este mensaje únicamente con el número de indice del canal, según se indica:\n\n${pregunta}`).then(sent => {

                message.channel.awaitMessages(filter, {
                  max: 1,
                  time: 15000,
                  errors: ['time'],
                }).then(async msg => {
                    await msg.first().delete({ timeout: 100 });
                   const index = parseInt(msg.first());
                  if (!isNaN(index) && !(index > canalesArray.length)) {
                        await sent.edit(`Vas a duplicar el canal: ${canalesArray[(index - 1)]}. **¿Cuantas copias del canal querés hacer?**\n(Ingresá un valor numérico del 1 al 10)`).then(() => {

                            message.channel.awaitMessages(filter, {
                                max: 1,
                                time: 15000,
                                errors: ['time'],
                            }).then(async emj => {
                                const cantidad = parseInt(emj.first());
                                await emj.first().delete({ timeout: 100 });
                                if (isNaN(cantidad)) {
                                    setTimeout(() => {
                                        sent.edit('La cantidad ingresada es incorrecta, o no es un valor numérico.');
                                    }, 1000);
                                    return;
                                }
                                else {
                                    for (let i = 0; i < cantidad; i++) {
                                        await sent.edit(`Creando canal ${i + 1}/${cantidad}`), 500;

                                        await message.guild.channels.cache.get(canalesIdArray[(index - 1)]).clone().then(async clon => {
                                            await clon.setName(`${canalesArray[(index - 1)]} - ${i + 1}`), 2000;
                                        })
                                            .catch(err => {
                                                message.channel.send(err);
                                            });
                                    }
                                    await sent.edit(`Genial. Creé un total de **${cantidad}** copias del canal **${canalesArray[(index - 1)]}**`).then(() => {
                                        sent.delete({ timeout: 5000 });
                                    });
                                    console.log(`${cantidad} copias creadas. Canal ${canalesArray[(index - 1)]}`);
                                }
                            });
                        })
                            .catch(error => {
                                sent.edit(`Se acabó el tiempo. **Error:** ${error}`);
                            });
                    }
                    else {
                        message.channel.send('El indice ingresado no existe, o no es un valor numérico.');
                        return;
                    }
                })
                    .catch(error => {
                        message.channel.send(error);
                    });
            });

            message.delete({ timeout: 6000 });
        }