Discord.js - How to send YouTube url after searching for a video - discord.js

So basically, my idea for a new command for my discord bot is a "link searcher", which will be a searching command that sends the url of the video that is chosen by the user. Something like in the image attached.
What I already have made is a searching command with embed, but im not quite sure how to send the video url that gets chosen via reaction. Any ideas/solutions?

I have found a solution after some tries, so here's the final code.
//////CONFIG LOAD///////////
////////////////////////////
const ytsr = require("youtube-sr")
const { Client, Collection, MessageEmbed } = require("discord.js");
const { attentionembed } = require("../util/attentionembed"); //attentionembed is an embed i pre-made for errors/attention cases for when the user gets one
const { approveemoji, denyemoji, PREFIX, } = require(`../config.json`); //my config contains the definitions for "yes" and "no" emojis, together with the bot token
////////////////////////////
//////COMMAND BEGIN/////////
////////////////////////////
module.exports = {
name: "linkfor",
aliases: ["searchlink","findlink","link","lf"], //optional
cooldown: 3, //optional
async execute(message, args, client) {
//if its not in a guild return
if (!message.guild) return;
//react with approve emoji
message.react(approveemoji).catch(console.error);
//if the argslength is null return error
if (!args.length)
return attentionembed(message, `Usage: ${message.client.prefix}${module.exports.name} <Video Name>`)
//if there is already a search return error
if (message.channel.activeCollector)
return attentionembed(message, "There is a search active!");
//define search
const search = args.join(" ");
//define a temporary Loading Embed
let temEmbed = new MessageEmbed()
.setAuthor("Searching...", "put a gif link here if you want")
.setColor("#F0EAD6")
//define the Result Embed
let resultsEmbed = new MessageEmbed()
.setTitle("Results for ")
.setDescription(`\`${search}\``)
.setColor("#F0EAD6")
.setAuthor("Search results:", "put a gif link here if you want")
.setFooter("Respond with the right number", "put a gif link here if you want")
//try to find top 9 results
try {
//find them
const results = await ytsr.search(search, { limit: 9 });
//map them and sort them and add a Field to the ResultEmbed
results.map((video, index) => resultsEmbed.addField(video.url, `${index + 1}. ${video.title}`));
//send the temporary embed aka Loading... embed
const resultsMessage = await message.channel.send(temEmbed)
//react with 9 Numbers
await resultsMessage.react("1️⃣");
await resultsMessage.react("2️⃣");
await resultsMessage.react("3️⃣");
await resultsMessage.react("4️⃣");
await resultsMessage.react("5️⃣");
await resultsMessage.react("6️⃣");
await resultsMessage.react("7️⃣");
await resultsMessage.react("8️⃣");
await resultsMessage.react("9️⃣");
//edit the resultmessage to the resultembed (you can also try deleting and sending the new one, if you need to)
await resultsMessage.edit(resultsEmbed)
//set the collector to true
message.channel.activeCollector = true;
//wait for a response
let response;
await resultsMessage.awaitReactions((reaction, user) => user.id == message.author.id,
{ max: 1, time: 60000, errors: ['time'], }).then(collected => {
//if its one of the emoji set them to 1 / 2 / 3 / 4 / ...
if (collected.first().emoji.name == "1️⃣") { return response = 1; }
if (collected.first().emoji.name == "2️⃣") { return response = 2; }
if (collected.first().emoji.name == "3️⃣") { return response = 3; }
if (collected.first().emoji.name == "4️⃣") { return response = 4; }
if (collected.first().emoji.name == "5️⃣") { return response = 5; }
if (collected.first().emoji.name == "6️⃣") { return response = 6; }
if (collected.first().emoji.name == "7️⃣") { return response = 7; }
if (collected.first().emoji.name == "8️⃣") { return response = 8; }
if (collected.first().emoji.name == "9️⃣") { return response = 9; }
//otherwise set it to error
else {
response = "error";
}
});
//if response is error return error
if (response === "error") {
//send error message
attentionembed(message, "Please use the right emoji symbol.");
//try to delete the message
return resultsMessage.delete().catch(console.error);
}
//get the response link
const URL = resultsEmbed.fields[parseInt(response) - 1].name;
//set collector to false aka off
message.channel.activeCollector = false;
//send the collected url
message.channel.send(URL);
//delete the search embed (optional, for better displaying)
resultsMessage.delete().catch(console.error);
//catch any errors while searching
} catch (error) {
//log them
console.error(error);
//set collector false, just incase its still true
message.channel.activeCollector = false;
}
}
};

Related

discordjs Embed won't show up

Ok, so i'm trying to make a push notification for my discord.
i found this script online.
but it will not post the embed....
This is my monitor code:
TwitchMonitor.onChannelLiveUpdate((streamData) => {
const isLive = streamData.type === "live";
// Refresh channel list
try {
syncServerList(false);
} catch (e) { }
// Update activity
StreamActivity.setChannelOnline(streamData);
// Generate message
const msgFormatted = `${streamData.user_name} is nu live op twitch <:bday:967848861613826108> kom je ook?`;
const msgEmbed = LiveEmbed.createForStream(streamData);
// Broadcast to all target channels
let anySent = false;
for (let i = 0; i < targetChannels.length; i++) {
const discordChannel = targetChannels[i];
const liveMsgDiscrim = `${discordChannel.guild.id}_${discordChannel.name}_${streamData.id}`;
if (discordChannel) {
try {
// Either send a new message, or update an old one
let existingMsgId = messageHistory[liveMsgDiscrim] || null;
if (existingMsgId) {
// Fetch existing message
discordChannel.messages.fetch(existingMsgId)
.then((existingMsg) => {
existingMsg.edit(msgFormatted, {
embed: msgEmbed
}).then((message) => {
// Clean up entry if no longer live
if (!isLive) {
delete messageHistory[liveMsgDiscrim];
liveMessageDb.put('history', messageHistory);
}
});
})
.catch((e) => {
// Unable to retrieve message object for editing
if (e.message === "Unknown Message") {
// Specific error: the message does not exist, most likely deleted.
delete messageHistory[liveMsgDiscrim];
liveMessageDb.put('history', messageHistory);
// This will cause the message to be posted as new in the next update if needed.
}
});
} else {
// Sending a new message
if (!isLive) {
// We do not post "new" notifications for channels going/being offline
continue;
}
// Expand the message with a #mention for "here" or "everyone"
// We don't do this in updates because it causes some people to get spammed
let mentionMode = (config.discord_mentions && config.discord_mentions[streamData.user_name.toLowerCase()]) || null;
if (mentionMode) {
mentionMode = mentionMode.toLowerCase();
if (mentionMode === "Nu-Live") {
// Reserved # keywords for discord that can be mentioned directly as text
mentionMode = `#${mentionMode}`;
} else {
// Most likely a role that needs to be translated to <#&id> format
let roleData = discordChannel.guild.roles.cache.find((role) => {
return (role.name.toLowerCase() === mentionMode);
});
if (roleData) {
mentionMode = `<#&${roleData.id}>`;
} else {
console.log('[Discord]', `Cannot mention role: ${mentionMode}`,
`(does not exist on server ${discordChannel.guild.name})`);
mentionMode = null;
}
}
}
let msgToSend = msgFormatted;
if (mentionMode) {
msgToSend = msgFormatted + ` ${mentionMode}`
}
let msgOptions = {
embed: msgEmbed
};
discordChannel.send(msgToSend, msgOptions)
.then((message) => {
console.log('[Discord]', `Sent announce msg to #${discordChannel.name} on ${discordChannel.guild.name}`)
messageHistory[liveMsgDiscrim] = message.id;
liveMessageDb.put('history', messageHistory);
})
.catch((err) => {
console.log('[Discord]', `Could not send announce msg to #${discordChannel.name} on ${discordChannel.guild.name}:`, err.message);
});
}
anySent = true;
} catch (e) {
console.warn('[Discord]', 'Message send problem:', e);
}
}
}
liveMessageDb.put('history', messageHistory);
return anySent;
});
This is the embed code:
const Discord = require('discord.js');
const moment = require('moment');
const humanizeDuration = require("humanize-duration");
const config = require('../data/config.json');
class LiveEmbed {
static createForStream(streamData) {
const isLive = streamData.type === "live";
const allowBoxArt = config.twitch_use_boxart;
let msgEmbed = new Discord.MessageEmbed();
msgEmbed.setColor(isLive ? "RED" : "BLACK");
msgEmbed.setURL(`https://twitch.tv/${(streamData.login || streamData.user_name).toLowerCase()}`);
// Thumbnail
let thumbUrl = streamData.profile_image_url;
if (allowBoxArt && streamData.game && streamData.game.box_art_url) {
thumbUrl = streamData.game.box_art_url;
thumbUrl = thumbUrl.replace("{width}", "288");
thumbUrl = thumbUrl.replace("{height}", "384");
}
msgEmbed.setThumbnail(thumbUrl);
if (isLive) {
// Title
msgEmbed.setTitle(`:red_circle: **${streamData.user_name} is live op Twitch!**`);
msgEmbed.addField("Title", streamData.title, false);
} else {
msgEmbed.setTitle(`:white_circle: ${streamData.user_name} was live op Twitch.`);
msgEmbed.setDescription('The stream has now ended.');
msgEmbed.addField("Title", streamData.title, true);
}
// Add game
if (streamData.game) {
msgEmbed.addField("Game", streamData.game.name, false);
}
if (isLive) {
// Add status
msgEmbed.addField("Status", isLive ? `Live with ${streamData.viewer_count} viewers` : 'Stream has ended', true);
// Set main image (stream preview)
let imageUrl = streamData.thumbnail_url;
imageUrl = imageUrl.replace("{width}", "1280");
imageUrl = imageUrl.replace("{height}", "720");
let thumbnailBuster = (Date.now() / 1000).toFixed(0);
imageUrl += `?t=${thumbnailBuster}`;
msgEmbed.setImage(imageUrl);
// Add uptime
let now = moment();
let startedAt = moment(streamData.started_at);
msgEmbed.addField("Uptime", humanizeDuration(now - startedAt, {
delimiter: ", ",
largest: 2,
round: true,
units: ["y", "mo", "w", "d", "h", "m"]
}), true);
}
return msgEmbed;
}
}
module.exports = LiveEmbed;
But it won't post the embed, only the msg. as you can see it updates teh msg aswell.
enter image description here
i'm stuck on this for four days now, can someone help?

Discord.js music bot playlist dont loop

I made a bot for Discord and came out with a pre-built playlist in the code itself, I tried to loop it so that whoever executes the command can get for example 20 songs and not just 1.
This is what I tried:
for (let i = 0; i < 10; i++) {
const msg = message
let channel = msg.member.voice.channel;
if (!channel) return msg.reply("\`I'm sorry but you need to be in a voice channel to play music\`");
const presong = ["Etham - 12:45 (acoustic ver.)(cover by Monkljae)","another love cover","James Arthur – Train Wreck (Acoustic) #AtHome #WithMe","Gracie Abrams - I miss you, I’m sorry","Olivia Rodrigo - drivers license","slow shy","Miguel - Sure Thing (Lyrics)","Nightcore - I Lied, I'm Dying Inside (Lyrics)","Nightcore - Sorry","Nightcore → Don't Watch Me Cry (Lyrics)","Khalid - Talk (Official Video)","Khalid - Better","Demons by Imagine Dragons | cover by Jada Facer","The One That Got Away by Katy Perry | cover by Jada Facer","Let Her Go - Passenger (Official Video Cover by Jasmine Thompson)","IT'S YOU - ALI GATIE[slowed + reverb]starmilk","All Kids Are Depressed (Slowed to Perfection)","billie eilish khalid - lovely","Duncan Laurence - Arcade","yellow","Heartbreak Anniversary","dancing with your ghout","heater tate macrae","hold on","watch billie eilish","martin and gina slowed reverb","Kali Uchis - telepatía (Cover by Lesha)","leaving on a jet plane macarone project","fly me to the moon yungrythm","close to you renee dominnique","blue moon jaritenph remix","run away","let me down slowely","little do you know","gnash feat. Olivia o'brien - I hate u, I love u (Consoul Trainin Remix)","ocaen eyes","hostage","listen before i go billie","Billie Eilish - Six Feet Under ","Chelsea Cutler - Crazier Things","All Kids Are Depressed (Slowed to Perfection)","Close To You- The Carpenters (ukulele cover) | Reneé Dominique","the hills || slowed","Powfu - Death Bed (Slowed To Perfection)","maroon 5 - memories (slowed + reverb)","Ashe - Moral Of The Story (Slowed + Lyrics)","Olivia Rodrigo - traitor (Lyrics)","kina - can we kiss forever [slowed + reverb]","Claire Rosinkranz - Backyard Boy (Lyrics)","comethru - jeremy zucker cover by kimswizzled","Be Alright by Dean Lewis | acoustic cover by Jada Facer","remendy of broken heart","jocelyn floers","CKay - Love Nwantiti (Acoustic Version)","Tate McRae - friends don’t look at friends that way","juice wrld - forever ( lyrics )"]
const preLofi = presong[Math.floor(Math.random() * presong.length)];
var searched = await yts.search(preLofi);
const url = "";
var serverQueue = message.client.queue.get(message.guild.id);
let songInfo = null;
let song = null;
if (url.match(/^(https?:\/\/)?(www\.)?(m\.)?(youtube\.com|youtu\.?be)\/.+$/gi)) {
try {
songInfo = await ytdl.getInfo(url);
if (!songInfo) return msg.reply("\`Looks like i was unable to find the song on YouTube\`");
song = {
id: songInfo.videoDetails.videoId,
title: songInfo.videoDetails.title,
url: songInfo.videoDetails.video_url,
img: songInfo.player_response.videoDetails.thumbnail.thumbnails[0].url,
duration: songInfo.videoDetails.lengthSeconds,
ago: songInfo.videoDetails.publishDate,
views: String(songInfo.videoDetails.viewCount).padStart(10, " "),
req: msg.author,
};
} catch(error) {
}
} else {
try {
songInfo = searched.videos[0];
song = {
id: songInfo.videoId,
title: Util.escapeMarkdown(songInfo.title),
views: String(songInfo.views).padStart(10, " "),
url: songInfo.url,
ago: songInfo.ago,
img: songInfo.image,
req: msg.author,
};
} catch (error) {
return msg.reply("\`Something Wrong, Text Or\`")
}
}
if (serverQueue) {
serverQueue.songs.push(song);
let thing = new MessageEmbed()
.setAuthor("Song has been added to queue")
.setThumbnail(song.img)
.setColor("#fffdd0")
.addField("Name", song.title, true)
.addField("Playlist", "Lofi")
.setFooter(`Views: ${song.views} | ${song.ago}`);
return msg.channel.send(thing);
}
const queueConstruct = {
textChannel: msg.channel,
voiceChannel: channel,
connection: null,
songs: [],
volume: 80,
playing: true,
loop: false,
};
msg.client.queue.set(msg.guild.id, queueConstruct);
queueConstruct.songs.push(song);
const play = async (song) => {
const queue = msg.client.queue.get(msg.guild.id);
if (!song) {
message.client.queue.delete(message.guild.id);
return;
}
let stream = null;
if (song.url.includes("youtube.com")) {
stream = await ytdl(song.url);
stream.on("error", function (er) {
if (er) {
if (queue) {
queue.songs.shift();
play(queue.songs[0]);
}
}
});
}
queue.connection.on("disconnect", () => msg.client.queue.delete(msg.guild.id));
const dispatcher =
queue.connection.play(ytdl(song.url, { quality: "highestaudio", highWaterMark: 1 << 25, type: "opus" })).on("finish", () => {
const shiffed = queue.songs.shift();
if (queue.loop === true) {
queue.songs.push(shiffed);
}
play(queue.songs[0]);
});
dispatcher.setVolumeLogarithmic(queue.volume / 100);
let thing = new MessageEmbed()
.setAuthor("PussyMusic Has Started Playing Music")
.setImage(song.img)
.setColor("#fffdd0")
.addField("Name", song.title, true)
.addField("Views", song.views, true)
.addField("Requested by", song.req.tag, true)
.setFooter(`PussyMusic`);
queue.textChannel.send(thing).then((question) => {
question.react('⏸');
question.react('▶️');
question.react('⬅️');
question.react('⏹️');
const filter = (reaction, user) => {
return ['⏹️', '⬅️','⏸','▶️'].includes(reaction.emoji.name) && !user.bot;
};
const collector = question.createReactionCollector(filter, { time: 400000 });
collector.on('collect', (reaction, reactionCollector) => {
const emoji = reaction.emoji.name;
if (emoji === '⬅️') {
const channel = msg.member.voice.channel
if (!channel)return msg.channel.send("\`I'm sorry but you need to be in a voice channel to skip music\`");
const serverQueue = msg.client.queue.get(msg.guild.id);
if (!msg.member.voice.channel)
return msg.channel.send(
"You have to be in a voice channel to skip the music!"
);
if (!serverQueue)
return msg.reply("\`There is no song that I could skip\`");
if (serverQueue.connection.dispatcher.paused)try{
serverQueue.connection.dispatcher.resume();
}
catch (error) {
}
serverQueue.connection.dispatcher.end();
} else if (emoji === '⏹️') {
const channel = msg.member.voice.channel
if (!channel)return msg.channel.send("\`I'm sorry but you need to be in a voice channel to stop music\`");
const serverQueue = msg.client.queue.get(msg.guild.id);
if (!serverQueue)return msg.channel.send("\`There is nothing playing that I could stop for you\`");
if(!serverQueue.connection)return
if(!serverQueue.connection.dispatcher)return
try{
serverQueue.connection.dispatcher.end()
msg.channel.send(":ballot_box_with_check: \`The Music Has Stopped\`:ballot_box_with_check:")
} catch (error) {
}
msg.client.queue.delete(msg.guild.id);
serverQueue.songs = [];
}
else if (emoji === '⏸') {
const channel = msg.member.voice.channel
if (!channel)return sendError("I'm sorry but you need to be in a voice channel to pause music!", msg.channel);
const serverQueue = msg.client.queue.get(msg.guild.id);
if (!serverQueue)return msg.channel.send("\`There is nothing playing that I could pause for you\`");
if (serverQueue.connection.dispatcher.paused)return msg.reply("\` The Music Already Been Paused \`");
if(!serverQueue.connection)return
if(!serverQueue.connection.dispatcher)return
try{
serverQueue.connection.dispatcher.pause()
msg.channel.send(":ballot_box_with_check:\`Pussy Has Paused The Music\`:ballot_box_with_check:")
}
catch (error) {
}
}
else if (emoji === '▶️') {
const channel = msg.member.voice.channel
if (!channel)return msg.channel.send("\`I'm sorry but you need to be in a voice channel to resume music\`");
const serverQueue = msg.client.queue.get(msg.guild.id);
if (!serverQueue)return msg.channel.send("\`There is nothing playing that I could resume for you\`");
if (!serverQueue.connection.dispatcher.paused)return msg.reply("\` The Music Already Been Resumed \`");
if(!serverQueue.connection)return
if(!serverQueue.connection.dispatcher)return
try{
serverQueue.connection.dispatcher.resume()
msg.channel.send(":ballot_box_with_check:\`Pussy Has resumed The Music\`:ballot_box_with_check:");
}
catch (error) {
msg.reply(`Whoops, Something wrong`);
}
}
});
});
};
try {
const connection = await channel.join()
queueConstruct.connection = connection;
play(queueConstruct.songs[0]);
} catch (error) {
msg.client.queue.delete(msg.guild.id);
await channel.leave();
return msg.reply(`I could not join the voice channel`);
}
}
}
};
In this situation, the bot gives only 2 songs, and not 10 (as i write in for loop)
how can i fix it? thank's for helping.

Command deprecated [duplicate]

This question already has an answer here:
Discord.js v12 code breaks when upgrading to v13
(1 answer)
Closed 1 year ago.
So basically I had this blackjack command that worked fine with v12 discord.js but as soon as I updated to discord v13. Bugs starting to appear like:
node:5932) DeprecationWarning: The message event is deprecated. Use messageCreate instead
(Use node --trace-deprecation ... to show where the warning was created)
(Only error showing up)
So I made some research and figured out that what happens to embed, but this command does not content an embed.. I came here to ask help. I would appreciate it :)
Blackjack.js
const { stripIndents } = require('common-tags');
const { shuffle, verify } = require('../../functions');
const db = require('quick.db');
const suits = ['♣', '♥', '♦', '♠'];
const faces = ['Jack', 'Queen', 'King'];
const hitWords = ['hit', 'hit me'];
const standWords = ['stand'];
module.exports = {
config: {
name: 'blackjack',
aliases: ['bj'],
category: 'games',
usage: '[deck] <bet>',
description: 'Play A Game Of Blackjack!',
accessableby: 'everyone'
},
run: async (bot, message, args, ops) => {
if (!args[0]) return message.channel.send('**Please Enter Your Deck Amount!**')
let deckCount = parseInt(args[0])
if (isNaN(args[0])) return message.channel.send('**Please Enter A Number!**')
if (deckCount <= 0 || deckCount >= 9) return message.channel.send("**Please Enter A Number Between 1 - 8!**")
let user = message.author;
let bal = db.fetch(`money_${user.id}`)
if (!bal === null) bal = 0;
if (!args[1]) return message.channel.send("**Please Enter Your Bet!**")
let amount = parseInt(args[1])
if (isNaN(args[1])) return message.channel.send("**Please Enter A Number**")
if (amount > 10000) return message.channel.send("**Cannot Place Bet More Than \`10000\`**")
if (bal < amount) return message.channel.send("**You Are Betting More Than You Have!**")
const current = ops.games.get(message.channel.id);
if (current) return message.channel.send(`**Please Wait Until The Current Game Of \`${current.name}\` Is Finished!**`);
try {
ops.games.set(message.channel.id, { name: 'blackjack', data: generateDeck(deckCount) });
const dealerHand = [];
draw(message.channel, dealerHand);
draw(message.channel, dealerHand);
const playerHand = [];
draw(message.channel, playerHand);
draw(message.channel, playerHand);
const dealerInitialTotal = calculate(dealerHand);
const playerInitialTotal = calculate(playerHand);
if (dealerInitialTotal === 21 && playerInitialTotal === 21) {
ops.games.delete(message.channel.id);
return message.channel.send('**Both Of You Just Hit Blackjack!**');
} else if (dealerInitialTotal === 21) {
ops.games.delete(message.channel.id);
db.subtract(`money_${user.id}`, amount);
return message.channel.send(`**The Dealer Hit Blackjack Right Away!\nNew Balance - **\` ${bal - amount}\``);
} else if (playerInitialTotal === 21) {
ops.games.delete(message.channel.id);
db.add(`money_${user.id}`, amount)
return message.channel.send(`**You Hit Blackjack Right Away!\nNew Balance -**\`${bal + amount}\``);
}
let playerTurn = true;
let win = false;
let reason;
while (!win) {
if (playerTurn) {
await message.channel.send(stripIndents`
**First Dealer Card -** ${dealerHand[0].display}
**You [${calculate(playerHand)}] -**
**${playerHand.map(card => card.display).join('\n')}**
\`[Hit / Stand]\`
`);
const hit = await verify(message.channel, message.author, { extraYes: hitWords, extraNo: standWords });
if (hit) {
const card = draw(message.channel, playerHand);
const total = calculate(playerHand);
if (total > 21) {
reason = `You Drew ${card.display}, Total Of ${total}! Bust`;
break;
} else if (total === 21) {
reason = `You Drew ${card.display} And Hit 21!`;
win = true;
}
} else {
const dealerTotal = calculate(dealerHand);
await message.channel.send(`**Second Dealer Card Is ${dealerHand[1].display}, Total Of ${dealerTotal}!**`);
playerTurn = false;
}
} else {
const inital = calculate(dealerHand);
let card;
if (inital < 17) card = draw(message.channel, dealerHand);
const total = calculate(dealerHand);
if (total > 21) {
reason = `Dealer Drew ${card.display}, Total Of ${total}! Dealer Bust`;
win = true;
} else if (total >= 17) {
const playerTotal = calculate(playerHand);
if (total === playerTotal) {
reason = `${card ? `Dealer Drew ${card.display}, Making It ` : ''}${playerTotal}-${total}`;
break;
} else if (total > playerTotal) {
reason = `${card ? `Dealer Drew ${card.display}, Making It ` : ''}${playerTotal}-\`${total}\``;
break;
} else {
reason = `${card ? `Dealer Drew ${card.display}, Making It ` : ''}\`${playerTotal}\`-${total}`;
win = true;
}
} else {
await message.channel.send(`**Dealer Drew ${card.display}, Total Of ${total}!**`);
}
}
}
db.add(`games_${user.id}`, 1)
ops.games.delete(message.channel.id);
if (win) {
db.add(`money_${user.id}`, amount);
return message.channel.send(`**${reason}, You Won ${amount}!**`);
} else {
db.subtract(`money_${user.id}`, amount);
return message.channel.send(`**${reason}, You Lost ${amount}!**`);
}
} catch (err) {
ops.games.delete(message.channel.id);
throw err;
}
function generateDeck(deckCount) {
const deck = [];
for (let i = 0; i < deckCount; i++) {
for (const suit of suits) {
deck.push({
value: 11,
display: `${suit} Ace!`
});
for (let j = 2; j <= 10; j++) {
deck.push({
value: j,
display: `${suit} ${j}`
});
}
for (const face of faces) {
deck.push({
value: 10,
display: `${suit} ${face}`
});
}
}
}
return shuffle(deck);
}
function draw(channel, hand) {
const deck = ops.games.get(channel.id).data;
const card = deck[0];
deck.shift();
hand.push(card);
return card;
}
function calculate(hand) {
return hand.sort((a, b) => a.value - b.value).reduce((a, b) => {
let { value } = b;
if (value === 11 && a + value > 21) value = 1;
return a + value;
}, 0);
}
}
};
Event Handler:
const { readdirSync } = require("fs")
module.exports = (bot) => {
const load = dirs => {
const events = readdirSync(`./events/${dirs}/`).filter(d => d.endsWith('.js'));
for (let file of events) {
const evt = require(`../events/${dirs}/${file}`);
let eName = file.split('.')[0];
bot.on(eName, evt.bind(null, bot));
};
};
["client", "guild"].forEach(x => load(x));
};
message is an event. you have an event handler, which fires, when a message event is triggered by a user. (they send a message).
What this error is saying is that the message event is deprecated. messageCreate (or messageUpdate) are the new events, and your event handlers need to use that syntax to address the message events (accordingly to creation or update).

How to get the specific discord bot channel with channelid?

My bot returns undefined when using bot.channels.get(channelid).
Here's a sample of my code:
//this is executed in a guild with id 416809320513011713
const Discordjs = require("discord.js");
const bot = new Discordjs.Client();
const auth = require('./auth.json');
const FileSys = require("fs");
bot.on('messageDelete', async function (message) {
console.log('message deleted')
let currentguildsettings = JSON.parse(FileSys.readFileSync('./DatStore/GuildDat/' + message.guild.id + '.dat', 'UTF8'));
if (currentguildsettings[0] == 1) {
if (currentguildsettings[1] != 0) {
let channelid = currentguildsettings[1].toString()
let channel = bot.channels.get(channelid);
console.log('settings on true, channelid ' + channelid)
if (channel) {
console.log('channel found')
}
}
}
}
bot.login(auth.token)
file ./DatStore/GuildDat/416809320513011713.dat contains:
[1,424085503361417200,0]
Here's the output:
message deleted
settings on true, channelid 424085503361417200
If the channel was found it should've logged 'channel found' in the output.
What should I change to make it return the channel?
The channel id key is a string, you must enclose it as a string in your array.
let c1 = bot.channels.get(424085503361417200); // Will produce undefined
let c2 = bot.channels.get('424085503361417200'); // Will produce a channel object (if available)
The channel wasn't available since I used the wrong id:
I saved the id's at my server settings command in int format instead of string, parseInt() broke the exact number.
if (logchannelaction == 'set') {
if (currentguildsettings[1] == message.channel.id) return message.reply("logchannel was already set to this channel");
currentguildsettings[1] = parseInt(message.channel.id);
message.reply("logchannel has set to #" + message.channel.name);
if (currentguildsettings[0] == 0) {
currentguildsettings[0] = 1
message.reply("logchannel has automatically enabled");
}
FileSys.writeFileSync(guilddatpath, JSON.stringify(currentguildsettings));
return
}
Thank you for trying to help me.

How can I send a random image?

I am trying to post a random dog picture when someone says toggledoggo. Every time I try to run the command, it gives me an error message in the terminal, and does nothing.
Here is my code:
const Discord = require('discord.js');
const client = new Discord.Client();
client.on("message", message => {
var prefix = 'toggle';
var doggos = ['dog1', 'dog2'];
var dog1 = message.channel.send({ files: ['dog1.jpg'] });
var dog2 = message.channel.send({ files: ['dog2.jpg'] });
if (message.content.startsWith(prefix + 'doggo')) {
Math.floor(Math.random() * doggos.length);
};
});
client.login('token');
If you want a truly random picture (pseudo-random but still) use an api. I use dog.ceo. Heres a code that, while big, gives a user plenty of options to choose from.
if(msg.split(' ')[0] === prefix + "doggo"){
let breeds = []; // Initializing an array to use later
let breeds2 = []; // Due to the size, we need to split it.
request('https://dog.ceo/api/breeds/list/all', async function (error, response, body) { // Begin a request to list all breeds.
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
for(var name in importedJSON.message){ // looping through every breed and pushing it into the array made earlier
breeds.push(name)
if(importedJSON.message[name].length != 0){
for(var i = 0; i < importedJSON.message[name].length; i++){
breeds.push("- " + importedJSON.message[name][i]) // Pushing sub-breeds into the array too
}
}
}
for(var j = 0; j < breeds.length/2; j++){ // Halving the previous array because it's too big for one message.
let toArray = breeds.shift()
breeds2.push(toArray)
}
}
})
let args = msg.split(' ').slice(1)
if(!args[0]){ // if no breed, then send a random image
request('https://dog.ceo/api/breeds/image/random', async function (error, response, body) {
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
return await message.channel.send(importedJSON.message)
}
})
}
if(args[0] === "breeds"){ // Command to list the breeds.
setTimeout(async function(){
let m = breeds2.map(name => name.charAt(0).toUpperCase() + name.slice(1)) // Creating a map of the arrays earlier to send as a message
let m2 = breeds.map(name => name.charAt(0).toUpperCase() + name.slice(1))
await message.channel.send(m)
return await message.channel.send(m2)
}, 1000);
}
if(args[0]){
setTimeout(async function(){
for(var i = 0; i < breeds.length; i++){ // Looping through every breed in the array to see if it matches the input
if(args[0] == breeds[i]){
let input = breeds[i]
args.shift() // This is to check for a sub breed input, which is taken into account in the else statement of this if statement
if(!args[0] || args[0] == undefined){
request(`https://dog.ceo/api/breed/${input}/images/random`, async function (error, response, body) {
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
return await message.channel.send(importedJSON.message)
}else{
await message.channel.send(`You must have typed something wrong, do ${prefix}doggo breeds for a list of breeds.`)
return
}
})
return
}else{
request(`https://dog.ceo/api/breed/${input}/${args[0]}/images/random`, async function (error, response, body) { // requesting a dog of a certain breed and sub breed
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
return await message.channel.send(importedJSON.message)
}else{
await message.channel.send(`You must have typed something wrong, do ${prefix}doggo breeds for a list of breeds.`)
return
}
})
return
}
}
}
for(var i = 0; i < breeds2.length; i++){ // This is identical to the above, but with the other array
if(args[0] == breeds2[i]){
let input = breeds2[i]
args.shift()
if(!args[0] || args[0] == undefined){
request(`https://dog.ceo/api/breed/${input}/images/random`, async function (error, response, body) {
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
return await message.channel.send(importedJSON.message)
}else{
await message.channel.send(`You must have typed something wrong, do ${prefix}doggo breeds for a list of breeds.`)
return
}
})
return
}else{
request(`https://dog.ceo/api/breed/${input}/${args[0]}/images/random`, async function (error, response, body) {
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
return await message.channel.send(importedJSON.message)
}else{
await message.channel.send(`You must have typed something wrong, do ${prefix}doggo breeds for a list of breeds.`)
return
}
})
return
}
}
}
}, 1000);
}
};
The acceptable command for this are: (prefix)doggo, (prefix)doggo breeds, (prefix)doggo (breed), (prefix)doggo (breed) (sub breed)
You will need the "request" module you can read up on it here: https://www.npmjs.com/package/request. Hopefully the comments I put in the code are enough to explain whats going on if not, ask for clarification. If you just wanted a small command for 2 pictures then you can also tell me and I'll delete this post entirely.

Resources