How do I make my music bot resume playing? - javascript

Here's my play.js. I am not a coder, so I don't understand most of this code. It took a bit of troubleshooting for it to work.
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
module.exports = {
name: 'play',
description: 'plays a song or whatever.',
async execute(message, args) {
const voiceChannel = message.member.voice.channel;
if(!voiceChannel) return message.channel.send('lol u need to be in a voice channel first');
const permissions = voiceChannel.permissionsFor(message.client.user);
if(!permissions.has('CONNECT')) return message.channel.send('u dont have the correct permissions smh');
if(!permissions.has('SPEAK')) return message.channel.send('u dont have the correct permissions smh');
if(!args.length) return message.channel.send('ok, but u need to tell me what u want to play');
const validURL = (str) =>{
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
if(!regex.test(str)){
return false;
} else {
return true;
}
}
if(validURL(args[0])){
const connection = await voiceChannel.join();
const stream = ytdl(args[0], {filter: 'audioonly'});
connection.play(stream, {seek: 0, volume: 1})
.on('finish', () =>{
voiceChannel.leave();
message.channel.send('ok fine ill leave')
});
await message.reply(`ok ill play whatever that is`)
return
}
const connection = await voiceChannel.join();
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'});
connection.play(stream, {seek: 0, volume: 0.5})
.on('finish', () =>{
voiceChannel.leave();
});
await message.reply(`ok im now playing ***${video.title}***`)
} else {
message.channel.send('lol i cant find the video ur looking for.')
}
}
}
And here is my pause.js. I had a bit of problem with this one, but it took me a while and a few searches to fix it.
name: 'pause',
description: 'makes me pause or whatever',
async execute(message,args, command, client, Discord){
const ytdl = require('ytdl-core');
const stream = ytdl(args[0], {filter: 'audioonly'});
const voiceChannel = message.member.voice.channel;
const connection = await voiceChannel.join();
const streamOptions = {seek:0, volume:1}
DJ = connection.play(stream, streamOptions)
DJ.pause();
}
}
and finally, my resume.js (It doesn't work.)
name: 'resume',
description: 'makes me resume or whatever',
async execute(message,args, command, client, Discord){
const ytdl = require('ytdl-core');
const stream = ytdl(args[0], {filter: 'audioonly'});
const voiceChannel = message.member.voice.channel;
const connection = await voiceChannel.join();
const streamOptions = {seek:0, volume:1}
DJ = connection.play(stream, streamOptions)
DJ.resume();
}
}
I watched a tutorial on how to make a music bot. However, they didn't mention how to make a play/pause command. Whenever I ran the resume.js, it'd say Error: No video id found: undefined. This is the last command before I am done with my music bot (so far) It would be greatly appreciated if anyone can answer me. Thank you!

You will need an instance of StreamDispatcher to call the method on. You could try to retrieve that instance from the message object.
const dispatcher = message.guild.voice.connection.dispatcher;
dispatcher.pause();
But be aware that some of the properties could be undefined. So add safety checks.
if (!message.guild) return;
const voiceState = message.guild.voice;
if (!voiceState || !voiceState.connection) return;
const dispatcher = voiceState.connection.dispatcher;
if (!dispatcher) return;
dispatcher.pause();
And you could apply the same logic with dispatcher.resume().
EDIT: Answer matches with the first revision of the question. The OP made significant changes to his question before I was able to answer. (Also I didn't see that an edit was made to the question.)

Related

TypeError: client.voice.createBroadcast is not a function

This is my code:
const secret = require('./secret.json'); //file with your bot credentials/token/etc
const discord = require('discord.js');
const discordTTS = require('discord-tts');
const client = new discord.Client();
client.login(secret.token);
client.on('ready', () => {
console.log('Online');
});
client.on('message', msg => {
if(msg.content === 'say test 123'){
const broadcast = client.voice.createBroadcast();
const channelId = msg.member.voice.channelID;
const channel = client.channels.cache.get(channelId);
channel.join().then(connection => {
broadcast.play(discordTTS.getVoiceStream('test 123'));
const dispatcher = connection.play(broadcast);
});
}
});
Output comes out with an error:
TypeError: client.voice.createBroadcast is not a function
I am using Node:17.0.0 and Discord.js:13.1.0
I am not sure why I am getting this error.
Discord.js v13 no longer supports voice. The new way to join a VC and play audio is with the #discordjs/voice library.
const { joinVoiceChannel, createAudioPlayer } = require("#discordjs/voice")
const player = createAudioPlayer()
joinVoiceChannel({
channelId: msg.member.voice.channel.id,
guildId: msg.guild.id,
adapterCreator: msg.guild.voiceAdapterCreator
}).subscribe(player) //join VC and subscribe to the audio player
player.play(audioResource) //make sure "audioResource" is a valid audio resource
Unfortunately, discord-tts might be deprecated. You can record your own user client speaking the message and save it to an audio file. Then you can create an audio resource like this:
const { createAudioResource } = require("#discordjs/voice")
const audioResource = createAudioResource("path/to/local/file.mp3")

How can i make it play music?

I tried making a rickroll command like this:
client.on('message', message => {
if (message.content.startsWith('music plz')) {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) {
return message.reply(`Wow what a scrub, join a Voice Channel first`);
}
voiceChannel.join()
.then(connection => {
const stream = ytdl('https://www.youtube.com/watch?v=dQw4w9WgXcQ', { filter: 'audioonly' });
const dispatcher = connection.playStream(stream, streamOptions);
})
It joins the VC and gives an error when not in VC but does not play music what am I doing wrong? I use Discord.js v12.5 and I am new to
it.
Check the guide Here they have a guide of how to do this. Also please update to v13, it's much better. Something like this:
const fs = require('fs');
const broadcast = client.voice.createBroadcast();
// From a path
broadcast.play('audio.mp3');
// From a ReadableStream
broadcast.play(fs.createReadStream('audio.mp3'));
// From a URL
broadcast.play('http://myserver.com/audio.aac');

Discord js giveaway command

I am currently trying to make a Discord.js command where the first person who reacts wins the prize. There are 2 issues that I am encountering right now. First, the bot is picking up the last prize that was entered through with the command rather than the current one. Secondly, the giveaway sent before a bot restart won't work after the bot restarts.
Here is the code:
const DropModel = require('../modules/DropModel');
const { MessageEmbed, ReactionCollector } = require("discord.js")
const { COLOR, MONGO } = require("../util/BotUtil");
module.exports = {
name: "drop",
description: "First to react wins the giveaway!",
async execute(message, args) {
let prizes = args.slice(0).join(' ').toString()
if (!prizes) return message.channel.send("You didn't provide a prize.");
const newDrop = new DropModel({
guildId: message.guild.id,
prize: prizes,
channelId: message.channel.id,
createdBy: message.author,
timeCreated: new Date(),
});
newDrop.save();
let Drops = await DropModel.findOne({ guildId: message.guild.id, channelId: message.channel.id });
if (!Drops) return;
const { prize, createdBy } = Drops;
const DropEmbed = new MessageEmbed()
.setTitle(`${prize}`)
.setDescription(`First to React with 🎁 wins the giveaway
Hosted by: ${createdBy}`)
.setColor(COLOR)
.setTimestamp();
const dropMsg = await message.channel.send(`🎁 **giveaway** 🎁`, DropEmbed);
await Drops.remove();
await dropMsg.react('🎁');
const filter = (reaction, user) => !user.bot;
const reaction = new ReactionCollector(dropMsg, filter, { max: 1 });
reaction.on('collect', async (reaction, user) => {
const { embeds } = dropMsg;
const embed = embeds[0];
embed.setTitle(`Someone called giveaway!`);
embed.setDescription(`Winner: ${user.toString()}
Please contact ${createdBy} to claim your giveaway!`);
await dropMsg.edit(embed);
dropMsg.channel.send(`${user.toString()} won **${prize}**!`);
});
}
}
Any help regarding the issues mentioned above would be appreciated! Thanks!
You can save the giveaway end timestamp in JSON file or whatever database and then delete it when it's finished.

How to fix Discord API: Unknown Message error?

I'm trying to make a meme command but whenever I try to use it I get this error "DiscordAPIError: Unknown Message".
This was working earlier but when I came back to my PC it started glitching out.
Here's my code
const { RichEmbed } = require("discord.js");
const randomPuppy = require("random-puppy");
const usedCommandRecently = new Set();
module.exports = {
name: "meme",
aliases: ["memes", "reddit"],
category: "fun",
description: "Sends a random meme",
run: async (client, message, args) => {
if (message.deletable) message.delete();
var Channel = message.channel.name
//Check it's in the right channel
if(Channel != "memes") {
const channelembed = new RichEmbed()
.setColor("BLUE")
.setTitle(`Use me in #memes`)
.setDescription(`Sorry ${message.author.username} this command is only usable in #memes !`)
return message.channel.send(channelembed);
}
//Check cooldown
if(usedCommandRecently.has(message.author.id)){
const cooldownembed = new RichEmbed()
.setColor("GREEN")
.setTitle("Slow it down, pal")
.setDescription(`Sorry ${message.author.username} this command has a 30 second cooldown per member, sorry for any inconvenice this may cause`)
message.channel.send(cooldownembed)
} else{
//Post meme
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
const img = await randomPuppy(random);
const embed = new RichEmbed()
.setColor("RANDOM")
.setImage(img)
.setTitle(`From /r/${random}`)
.setURL(`https://reddit.com/r/${random}`);
message.channel.send(embed);
}
}
}
Im not sure, but maybe problem in your require block.
const { RichEmbed } = require("discord.js");
the right way its:
const Discord = require("discord.js");
let cooldownembed = new Discord.RichEmbed();
and why you use return here
return message.channel.send(channelembed);

Cannot leave voice channel

My bot cannot leave a voicechannel, but it can join in anyone. I have 2 codes, one is "leave" and the other one is "stopstream", It said " Cannot read property 'channelID' of undefined" and "(node:11416) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'voiceChannel' of undefined" with one complex code
I tried to use different code, one more complex than the other. And put "const ytdl = require('ytdl-core');
const streamOptions = { seek: 0, volume: 1 };" in the complex one.
//leave
const ytdl = require('ytdl-core');
const streamOptions = { seek: 0, volume: 1 };
exports.run = async (client, message, args, ops) => {
if (!message.member.voiceChannel) return message.channel.send('Please connect to a voice chanel, don\'t be afraid my child. Share you beautiful voice.');
if (!message.guild.mne.voiceChannel) return message.channel.send('Sorry, I\'m not connected to the guild.');
if (message.guild.me.voiceChannelID !== message.member.voiceChannelID) return message.chanel.send('Sorry, you aren\t connected to the same channel, I\'ll give you some PeterFriffinCoins, for free.');
message.guild.me.voiceChannel.leave();
message.channel.send('Leaving Channel... I\'m a free elf...')
}
//stopstream
exports.run = (client, message, args) => {
client.leaveVoiceChannel(message.member.voiceState.channelID);
message.channel.send('Thanks for tuning in!');
}
Try this in leave channel command
let authorVoiceChannel = message.member.voiceChannel;
if(!authorVoiceChannel) return message.channel.send("You are not in a voice channel")
if(authorVoiceChannel.id !== client.voiceChannel.id) return message.channel.send("We're not in the same voice channel")
authorVoiceChannel.leave()
message.channel.send("I left voice channel")

Categories

Resources