discord.js image search with pages - discord.js

is there a way to add pages for this command.
e.g | https://gyazo.com/e6782fc9386f9d15c7cc52dabeb8844e (it can be with reactions or buttons)
const { MessageEmbed } = require("discord.js");
module.exports = {
name: "img",
description: "Search for an image!",
category: "utility",
cooldown: {type: "map", time: 10},
aliases: ["is", "imgsearch"],
run: async (client, message, args) => {
if (!args) client.err(message);
gis(args.join(" "), logResults);
async function logResults(error, results){
if (error)return client.err(message);
let random = Math.floor(Math.random() * results.length);
let image = results[random].url
const embed = new MessageEmbed()
.setImage(image)
.setColor("#2f3136");
return message.reply(embed);
}
}
}

The easiest solution would be to add two reactions '⬅️, ➡️', and await till user reacts with one of them. (working with reactions is nicely described here)
Your code would look like this:
const { MessageEmbed } = require("discord.js");
module.exports = {
name: "img",
description: "Search for an image!",
category: "utility",
cooldown: {type: "map", time: 10},
aliases: ["is", "imgsearch"],
run: async (client, message, args) => {
if (!args) client.err(message);
gis(args.join(" "), logResults);
async function logResults(error, results){
if (error)return client.err(message);
let random = Math.floor(Math.random() * results.length);
let image = results[random].url
const embed = new MessageEmbed()
.setImage(image)
.setColor("#2f3136");
// Awaiting till the message gets sent so we can add reactions & await users to react
const msg = await message.reply(embed);
// Adding reactions
await msg.react('⬅️');
await msg.react('➡️');
// Create a filter so only when original author reacts with ⬅️ or ➡️ the message is edited.
const filter = (reaction, user) => {
return ['⬅️', '➡️'].includes(reaction.emoji.name) && user.id === message.author.id;
};
// Await until user reacts
message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '⬅️') {
await msg.reactions.removeAll();
let image = results[random-1].url
const embed = new MessageEmbed()
.setImage(image)
.setColor("#2f3136");
msg.edit(embed);
} else {
await msg.reactions.removeAll();
let image = results[random+1].url
const embed = new MessageEmbed()
.setImage(image)
.setColor("#2f3136");
msg.edit(embed);
}
})
.catch(collected => {
message.reply('Your time to open next or previous image expired!');
});
}
}
}

Related

Discord.Js The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined

I was coding a new command on discord which its focusing on OsuApi and now what I did is making a data function that writes the info on the Api.
I tried this code and it seems that I cannot fix it because I'm kinda new to this function and its bugging me
and here's my code
const { member, channel, content, guild } = message
const cache = {}
let data = cache[member.id]
if (!data) {
const e1 = new ME()
.setTitle(`Fetching Data Please Wait`)
.setColor("Random")
.setTimestamp()
.setFooter({ text: client.user.username, iconURL: client.user.displayAvatarURL() })
console.log("Fecting From DataBase")
const msg = await channel.send({ embeds: [e1] })
await shi().then(async mongodb => {
try {
const result = await us.findOne({ _id: member.id })
if (!result) {
const e2 = new ME()
.setTitle("Aweeee~")
.setColor(config.colors.no)
.setDescription("No user found set user using 's!setuser <username or userid>' ")
.setTimestamp()
.setFooter({ text: client.user.username, iconURL: client.user.displayAvatarURL() })
await setTimeout(() => {
msg.edit({ embeds: [e2] })
}, 5000);
return
}
cache[member.id] = data = [result.text]
} catch (err) {
console.log(err)
message.channel.send("Something bad happened sorry")
}
})
api.user
.get(data)
.then(data => {
const dataJSON = JSON.stringify(data)
fs.writeFileSync('user.json', dataJSON)
const dataBuffer = fs.readFileSync('user.json')
const stringJSON = dataBuffer.toString()
const parseDATA = JSON.parse(stringJSON)
console.log(parseDATA.username)
channel.send("testing")
})
}

TypeError: interaction.options.getSubcommand is not a function

I have made a all-in-one moderation bot by compiling certain codes. Recently, I was adding Ticket-System to my bot and it showed me this error. Although, I tried all the fixes I could find on the internet but still couldn't solve it.
Here is my code -->
ticket-config.js
const { Util, MessageEmbed } = require('discord.js');
const configOptions = require('../../configOptions');
module.exports = {
name: "ticketconfig",
description: "Configuration ticket system.",
options: configOptions,
permission: "ADMINISTRATOR",
run: async(interaction, client) => {
const replyMessage = {
content: "Config has been set!"
}
if (interaction.options.getSubcommand() === 'message') {
const message = interaction.options.getString('message');
const content = interaction.options.getString('content') || null;
let data = await client.db.get('config', interaction.guild.id);
if (!data) data = {};
data.message = message;
data.content = content;
await client.db.set('config', interaction.guild.id, data);
return interaction.reply(replyMessage)
}
configOptions.js
module.exports = [
{
name: "message",
description: "Configuration your ticket message",
type: 1,
options: [
{
name: "message",
description: "The message to sent in ticket",
type: 3,
required: true
},
{
name: "content",
description: "content will be appeared above embed message, use /variables command to see all available variables.",
type: 3
}
]
},
./handler/index.js
module.exports = async (client) => {
const eventFiles = await globPromise(`${process.cwd()}/events/*.js`);
eventFiles.map((value) => require(value));
const slashCommands = await globPromise(
`${process.cwd()}/SlashCommands/*/*.js`
);
const arrayOfSlashCommands = [];
slashCommands.map((value) => {
const file = require(value);
if (!file?.name) return;
client.slashCommands.set(file.name, file);
if (["MESSAGE", "USER"].includes(file.type)) delete file.description;
arrayOfSlashCommands.push(file);
});
client.on("ready", async () => {
await client.application.commands.set(arrayOfSlashCommands);
});

Discord.js Ticket system doesn't send an ephemeral message

I'm trying to make a ticket system with discord.js v13, but the ephemeral method doesn't work and, when my bot turn on, i need to click one time in the button to activate the system.
print
My code:
const { MessageActionRow, MessageButton, MessageEmbed, Permissions } = require('discord.js');
const db = require("quick.db");
exports.run = async (client, interaction) => {
if (!interaction.isButton()) return;
interaction.deferUpdate();
let getContador = await db.get('counter')
if(getContador === null) {
let contador = await db.set("counter", 1)
}
await db.add("counter", 1)
let tcID = "895323735702253569"
let tmID = "895358127950659604"
const filter = i => i.customId === 'OPENTICKET'
const collector = interaction.channel.createMessageComponentCollector({ filter, max: 1 });
collector.on("collect", async i => {
let cTicket = await i.guild.channels.create(`🎫┆Ticket ${getContador}`, {
type: 'GUILD_TEXT',
permissionOverwrites: [
{
id: i.guild.id,
deny: [Permissions.FLAGS.VIEW_CHANNEL],
},
{
id: i.user.id,
allow: [Permissions.FLAGS.VIEW_CHANNEL, Permissions.FLAGS.SEND_MESSAGES],
},
]
})
await interaction.channel.messages.cache.get(tmID).reply({ content: `... ${cTicket.toString()}...`, ephemeral: true })
})
}
You are replying to a normal message. If you would like an ephemeral message, you have to directly reply to the interaction.
interaction.reply({
content: `... ${cTicket.toString()}...`,
ephemeral: true
})

Discord.js v13, #discordjs/voice Play Music Command

This is my code,
The command executes perfectly, The bot joins the voice channel and also sends the name of the song its about to play, but it doesnt play the song in the voice channel.
This is my first time ever asking a question on stackoverflow so dont mind the format and stuff. But I really need help here.
Discord v13 and latest node module.
const ytsearch = require('yt-search');
const Discord = require('discord.js')
const {
joinVoiceChannel,
createAudioPlayer,
createAudioResource,
NoSubscriberBehavior
} = require('#discordjs/voice');
module.exports = {
name: "play",
description: "test command",
async run(client, message, args) {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send('Please connect to a voice channel!');
if (!args.length) return message.channel.send('Please Provide Something To Play!')
const connection = await joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
const videoFinder = async (query) => {
const videoResult = await ytsearch(query);
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
const video = await videoFinder(args.join(' '));
if (video) {
const stream = ytdl(video.url, { filter: 'audioonly' });
const player = createAudioPlayer();
const resource = createAudioResource(stream)
await player.play(resource);
connection.subscribe(player);
await message.reply(`:thumbsup: Now Playing ***${video.title}***`)
} else {
message.channel.send('No video results found');
}
}
}```
I would suggest you look at the music bot example at #discordjs/voice.
They do a good job of how to extract the stream from ytdl.
I'm currently still learning how this all works but the part that you will want to look at is in the createAudioResource function.
public createAudioResource(): Promise<AudioResource<Track>> {
return new Promise((resolve, reject) => {
const process = ytdl(
this.url,
{
o: '-',
q: '',
f: 'bestaudio[ext=webm+acodec=opus+asr=48000]/bestaudio',
r: '100K',
},
{ stdio: ['ignore', 'pipe', 'ignore'] },
);
if (!process.stdout) {
reject(new Error('No stdout'));
return;
}
const stream = process.stdout;
const onError = (error: Error) => {
if (!process.killed) process.kill();
stream.resume();
reject(error);
};
process
.once('spawn', () => {
demuxProbe(stream)
.then((probe) => resolve(createAudioResource(probe.stream, { metadata: this, inputType: probe.type })))
.catch(onError);
})
.catch(onError);
});
}

Embed for music bot not working/discord.js

I'm working on my music bot for my discord server. So my code from a technical perspective works, it can play music, and it has queues, but I'm trying to add embeds to the messages, but I keep getting an error message that my message, channel, author is not defined. How do correctly define properties that I need for my embeds to work?
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
const queue = new Map();
module.exports = {
name: 'play',
aliases: ('skip', 'stop'),
cooldown: 0,
description: 'Advanced music bot',
async execute(client, message, args, cmd, Discord){
const voice_channel = message.member.voice.channel;
if (!voice_channel) return message.channel.send('You need to be in a channel to execute this command!');
const permissions = voice_channel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('You dont have the correct permissins');
if (!permissions.has('SPEAK')) return message.channel.send('You dont have the correct permissins');
const server_queue = queue.get(message.guild.id);
if (cmd === 'play'){
if (!args.length) return message.channel.send('You need to send the second argument!');
let song = {};
if (ytdl.validateURL(args[0])) {
const song_info = await ytdl.getInfo(args[0]);
song = { title: song_info.videoDetails.title, url: song_info.videoDetails.video_url }
} else {
const video_finder = async (query) =>{
const video_result = await ytSearch(query);
return (video_result.videos.length > 1) ? video_result.videos[0] : null;
}
const video = await video_finder(args.join(' '));
if (video){
song = { title: video.title, url: video.url }
} else {
message.channel.send('Error finding video.');
}
}
if (!server_queue){
const queue_constructor = {
voice_channel: voice_channel,
text_channel: message.channel,
connection: null,
songs: []
}
queue.set(message.guild.id, queue_constructor);
queue_constructor.songs.push(song);
try {
const connection = await voice_channel.join();
const Discord = require('discord.js');
queue_constructor.connection = connection;
video_player(message.guild, queue_constructor.songs[0]);
} catch (err) {
queue.delete(message.guild.id);
message.channel.send('There was an error connecting!');
throw err;
}
} else{
server_queue.songs.push(song);
newEmbed = new Discord.MessageEmbed()
.setTitle("**Now adding...**")
.setDescription(`${song.title}\n\`Requested by:\` ${message.author}`)
.setColor("#ff0000")
.setThumbnail('https://i.pinimg.com/474x/db/cd/d0/dbcdd0a38ebdb5f7f32cfda2f671dede.jpg')
return message.channel.send
message.channel.send(newEmbed);
}
}
}
}
const video_player = async (guild, song) => {
const song_queue = queue.get(guild.id);
if (!song) {
song_queue.voice_channel.leave();
queue.delete(guild.id);
return;
}
const stream = ytdl(song.url, { filter: 'audioonly' });
const Discord = require('discord.js');
song_queue.connection.play(stream, { seek: 0, volume: 0.5 })
.on('finish', () => {
song_queue.songs.shift();
video_player(guild, song_queue.songs[0]);
});
await song_queue.text_channel.send
newEmbed = new Discord.MessageEmbed()
.setTitle("**Now playing...**")
.setDescription(`${song.title}\n\`Requested by:\` ${message.author}`)
.setColor("#ff0000")
.setThumbnail('https://i.pinimg.com/236x/a1/57/2c/a1572c4306f27fd644ab62199def8aab.jpg')
message.channel.send(newEmbed);
}
I think you are missing the const before the "newEmbed" and you also can't have "newEmbed" twice, as it will return an error. Change it. E.g.
const newEmbed = new Discord.MessageEmbed()
Or you can have
const songList = new Discord.MessageEmbed()
The songList can be anything but just not the same for the other embeds you want.

Resources