(node:13) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Channel - javascript

I have a problem with my discord bot, I try to delete all channels of a server, then I create new channels and send message in all channels. I know it's against Discord TOS, but it's just in my server and it's just to see if it's possible. My problem is that it deletes and creates the channel but it do not send mesages in the channels, instead I get an error. I hope that you could help me.
Here's the error :
at /home/container/node_modules/discord.js/src/client/rest/RequestHandlers/Sequential.js:85:15
at /home/container/node_modules/snekfetch/src/index.js:215:21
Here's the code :
const bot = new Discord.Client()
const PREFIX = "$"
bot.on('ready', () => {
console.log('bot is online')
})
bot.on('message', async message => {
const taille = message.guild.channels.filter((c) => c.type === "text" || c.type === "voice").size;
let args = message.content.substring(PREFIX.length).split(" ");
if (!message.content.startsWith(PREFIX)) {
return
}
if (message.author == bot) { return }
switch (args[0]) {
case 'raid':
var attackembed = new Discord.RichEmbed()
.setColor('#FF0000 ')
.setTitle(`test`)
.setDescription(`123`)
.setFooter('test BOT')
if (message.member.hasPermission('ADMINISTRATOR')) {
function antilag() {
for (let index = 0; index != taille; index++) {
message.guild.channels.forEach(channel => channel.delete())
}
for (let x = 0; x != args[1]; x++) {
message.guild.createChannel(`hacked by ${message.member.user.tag} `, { type: 'text' })
}
}
function msg() {
for (let x = 0; x != args[1]; x++) {
message.guild.channels.forEach(
function(channel, index) {
channel.send(`#everyone The server ${message.guild.name} was hacked by ${message.member.user.tag}`)
})
}
}
message.guild.setName(`HACKED BY ${message.member.user.tag}`)
message.guild.setIcon(message.author.avatarURL)
message.guild.members.forEach(member => member.sendEmbed(embed));
antilag()
msg()
}
break;
}
})
bot.login("my token");
PS : Note that I am new to javascript and discord.js

createChannel is a Promise, which means that by the time this function has finished executing, your code has already moved on other parts, and whenever that channel was requested, it wasn't available yet so it was undefined. You need to wait for the function to resolve then proceed with the rest of your logic:
message.guild.createChannel("whatever channel", { type: "text" }).then(function(createdChannel) {
// the rest of your code
});
Or, since you already called the function inside an async callback:
let newChannel = await message.guild.createChannel("whatever channel", { type: "text" });
// rest of code
Take care.

Related

Anti ping system. Working depends on which one is on top

I'm having a problem with my anti ping system. It works alone, but with the other stuff (If (data) ... } else if (!data) {...) they overlap. If I add the if (comrade) on top of the if (data), other commands stop working but the anti ping works. Here is my code (also I get no errors):
const pinger = new Set();
const pinged = new Set();
client.on('message', async (message) => {
const data = await prefix.findOne({
GuildID: message.guild.id
});
let embed = new Discord.MessageEmbed();
const messageArray = message.content.split(" ");
const cmd = messageArray[0];
const args = messageArray.slice(1);
if (data) {
const prefix = data.Prefix;
if (!message.content.startsWith(prefix)) return;
const commandfile = client.commands.get(cmd.slice(prefix.length).toLowerCase() || client.commands.get(client.aliases.get(cmd.slice(prefix.length).toLowerCase())));
commandfile.run(client, message, args);
} else if (!data) {
const prefix = "!";
if (!message.content.startsWith(prefix)) return;
const commandfile = client.commands.get(cmd.slice(prefix.length).toLowerCase() || client.commands.get(client.aliases.get(cmd.slice(prefix.length).toLowerCase())));
commandfile.run(client, message, args);
}
let comrade = message.guild.member(message.mentions.users.first())
let mrole = message.guild.roles.cache.find(r => r.name === 'dont ping again');
let comradeid = message.guild.members.cache.get(comrade.user.id);
let authorid = message.guild.members.cache.get(message.author.id);
if (comrade) {
if (message.author.bot) return;
if (pinger.has(authorid), pinged.has(comradeid)) {
message.guild.channels.cache.forEach(f => {
f.overwritePermissions([{
id: mrole.id,
deny: ['SEND_MESSAGES']
}]);
})
authorid.roles.add(mrole)
setTimeout(() => {
authorid.roles.remove(mrole)
}, 30000)
embed.setTitle('BRUH')
embed.setDescription('YOU CANT MASS PING THAT PERSON')
embed.setColor('RED')
message.channel.send(embed)
} else {
if (!mrole) message.guild.roles.create({ data: { name: 'dont ping again' } });
if (comrade.roles.cache.find(role => role.name === 'dont ping me')) {
pinged.add(comradeid)
setTimeout(() => {
pinged.delete(comradeid)
}, 15000)
pinger.add(authorid)
setTimeout(() => {
pinger.delete(authorid)
}, 15000);
}
}
}
})
It uses a mongoDB (database) because I want my bot to have a change its prefix for other guilds command (which works perfectly). Here the commands work (the if (data) where it checks for a prefix), but the anti pinging system doesn't. I've tried a lot of stuff, but they end up not working. Thanks in advance.

Discord bot post multiple results

First time using stackoverflow. It is a bot made to post result whenever new episode of show in search list gets added on nyaa.si. I want bot to post result only once for every episode but bot post same episode multiple time in different time frames. It gets fixed for while after I restart the bot.
The code to add show to search list.
async addShow(msg) {
const regex = /"(.+?)" "(.+?)"(?: "(.+?)")?/g;
const found = regex.exec(msg.content);
if (found === null) {
await msg.channel.send(`Invalid new syntax:\n${COMMAND_CHARACTER} new \"show search phrase\" \"MALURL\" \"attribute regex\" (optional last)`);
return;
}
let [f, search, url, reg] = found;
let count = await this.db.get('search').last().value();
if (_.isUndefined(count)) {
count = 0;
}
else {
count = count.id;
}
await this.db.get('search').push({id: count + 1, search, url, regex: reg}).write();
logger.info(`New show has been added to the searchlist - ${search} - ${url} for server ${this.guildID}`);
await msg.channel.send("Saved!");
}
The code to search
async searchShow(id, query, channel = null, OG = null) {
const results = await this.nyaa.getResults(query);
if (!results.length) {
return;
}
logger.info(`Results found for ${query}: ${results.length}`);
const embedFunction = this.getRichEmbed.bind(this);
for (let i of results) {
const item = await this.db.get('rss').find({guid: i.guid}).value();
if (!_.isUndefined(item)) {
continue;
}
if (await this.postShow(embedFunction, i, channel, OG)) {
await this.db.get('rss').push({...i, searchID: id}).write();
}
}
}
Code to post result when new episode comes.
async postShow(embedFunc, item, channel = null, og = null, channelType = NYAA_UPDATES) {
if (channel === null) {
channel = await this.getGuildChannel(channelType);
if (!channel) {
return false;
}
}
return new Promise(async (resolve) => {
const title = (og !== null ? og.title ?? item.title : item.title);
const embed = await embedFunc(item, title);
if (og !== null) {
const img = og.image ?? null;
if (img) {
embed.setThumbnail(img);
}
const url = og.url ?? null;
if (url) {
embed.setURL(url);
}
}
let retryCounter = 0;
logger.info(`Posting new result for ${title} with guid ${item.guid} for server ${this.guildID}`);
while (true) {
try {
await channel.send(embed);
setTimeout(() => {
resolve(true);
}, 2000);
break;
}
catch (e) {
logger.warn(`An error has occured while posting: ${e.toString()}, retrying (${++retryCounter} in 5 seconds`);
await new Promise((res) => {
setTimeout(() => {
res();
}, 5000);
});
if (retryCounter > 10) {
resolve(false);
}
}
}
});
}
Also one who wrote most of code was different person and I only added few additional function here and there which doesn't affect the code much. One who wrote most of core code had to leave discord so I was left to host the bot which I am hosting at repl.it. It will be great help to know whether the problem is with the code or not.
As Julian Kleine mentioned above, the most common reason a bot posts multiple times is if you are running multiple instances of the host. Close all instances of command prompt, and check task manager to see if any other hidden instances are running in the background.

I have a problem with this code after adding the kick player command. The rest of the bot doesn't work and neither does this command

const { Client, RichEmbed } = require("discord.js");
const chalk = require("chalk");
const { token, prefix } = require("../config/config.js");
const client = new Client();
client.on("ready", () => {
console.log(chalk.red("Witamy w konsoli bota Island"));
console.log(chalk.green(`Zalogowano jako ${client.user.tag}!`));
});
client.on("message", (msg) => {
const { author, guild } = msg;
if (author.bot || !guild) {
return;
}
if (msg.content === "-info") {
msg.channel.send("Witam, jestem botem stworzonym przez Rewera");
}
});
client.on("message", (msg) => {
const { author, guild } = msg;
if (author.bot || !guild) {
return;
}
if (msg.content === "-komendy") {
msg.channel.send("Już wkrótce, zostaną dodane. Są w trakcie tworzenia");
}
if (msg.content === "-wersja") {
msg.channel.send("Wersja: ALPHA 0.04");
}
if (msg === "-tworca") {
const botAuthor = "Rewer";
const botVersion = "v1.1";
msg.channel.send(
"Autorem bota jest: **${botAuthor}**! Wersja *${botVersion}*. "
);
}
if (message.content.startsWith("$kick")) {
if (!message.member.roles.find("name", "Admin"))
return;
// Easy way to get member object though mentions.
var member = message.mentions.members.first();
// Kick
member.kick().then((member) => {
// Successmessage
message.channel.send(":wave: " + member.displayName + " has been successfully kicked :point_right: ");
}).catch(() => {
// Failmessage
message.channel.send("Access Denied");
});
}
});
// Error handler
client.on("debug", () => {});
client.on("warn", () => {});
client.on("error", () => {});
client.login(token);
I have a problem with this code after adding the kick player command. The rest of the bot doesn't work and neither does this command
I don't know what to do with it when I remove the kick code. The bot magically starts working.
Anyone have any ideas on how to fix it, I'm a beginner so please understand
When you handle the message event you pass "msg" as the argument
client.on("message", (msg) => {
So you should use "msg" throughout
However in you kick command you start using "message"
if (message.content.startsWith("$kick")) {
and if (!message.member.roles.find("name", "Admin"))
You must change "message" to "msg" to match the name you gave the variable at the start
client.on("message", (msg) => {

TypeError: message.client.commands.get(...).execute is not a function

module.exports = {
name: 'search',
aliases: ['search'],
description: 'Search and select videos to play.',
run: async (client, message, args) => {
if (!args.length)
return message.reply(`Usage: ${message.client.prefix}${module.exports.name} <Video Name>`).catch(console.error);
if (message.channel.activeCollector)
return message.reply("A message collector is already active in this channel.");
if (!message.member.voice.channel)
return message.reply("You need to join a voice channel first!").catch(console.error);
const search = args.join(" ");
let resultsEmbed = new MessageEmbed()
.setTitle(`**Reply with the song number you want to play**`)
.setDescription(`Results for: ${search}`)
.setColor(COLORS.DARK_RED);
try {
const results = await youtube.searchVideos(search, 20);
results.map((video, index) => resultsEmbed.addField(video.shortURL, `${index + 1}. ${video.title}`));
var resultsMessage = await message.channel.send(resultsEmbed);
function filter(msg) {
const pattern = /(^[1-9][0-9]{0,1}$)/g;
return pattern.test(msg.content) && parseInt(msg.content.match(pattern)[0]) <= 20;
}
message.channel.activeCollector = true;
const response = await message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ["time"]
});
const choice = resultsEmbed.fields[parseInt(response.first()) - 1].name;
message.channel.activeCollector = false;
message.client.commands.get("play").execute(message, [choice]);
resultsMessage.delete().catch(console.error);
} catch (error) {
console.error(error);
message.channel.activeCollector = false;
}
}
};
I have a problem with my code, when I run the code it throws me an embed with the song list, but when I choose the song, I get an error TypeError: message.client.commands.get(...).execute is not a function on line 49
Que debo de hacer para corregir?
Did you mean to get the bot client instead of the client who sent the message?
Try changing
message.client.commands.get("play").execute(message, [choice]);
// to
client.commands.get("play").execute(message, [choice]);
You are assuming that "play" exists.
Perhaps you should check if play doesn't exist, handle that scenario.
if (message.client.commands.get("play") === undefined){
... do some logic
}

discord bot that checks if the transfer is completed

I'm having an issue with my js code. I built a bot that makes a file to play in my server with the name of who joins, but it's too fast so I want to put something that stops the code until it finishes to make the file
client.on('voiceStateUpdate', async(oldState, newState) => {
if (!oldState || !newState) return;
const oldChannel = oldState.channel ? oldState.channel.id : null;
const newChannel = newState.channel ? newState.channel.id : null;
const user = await client.users.fetch(newState.id)
let nome = user.username;
let messaggio = 'E\' entrato '+nome;
say.export(messaggio , 'Cellos', 1, 'output.wav', (err) => {
if (err) {
return console.error(err)
}
})
online(newChannel, newState, nome);
});
function online(newChannel, newState, nome) {
if(newChannel === universoVoice && newState.id !== Botid){
console.log('entrata');
const voiceChannel = client.channels.cache.get(universoVoice);
if (!voiceChannel) return console.error("The channel does not exist!");
voiceChannel.join().then(connection => {
console.log("Connesso");
connection.play('out.mp3');
client.leaveVoiceChannel;
}).catch(e => {
console.error(e);
});
}else{
console.log('uscita');
}
}
Try using await online(newChannel, newState, nome); in order to wait until the say.export function is completed

Categories

Resources