How can i make it play music? - javascript

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');

Related

Discord.js Replit, cannot get my bot to respond to commands

I am currently developing a Discord bot for replit, and I am able to get it to post and even get it to send an intro message when joining a server, however whenever I try to get it to respond to a command I type it won't respond. The message for the first one client.on guild create works. However the client.on for async message will not work.
This is what I have so far.
const { Client } = require('discord.js');
const client = new Client({ intents: 32767 });
//const Discord = require('discord.js');
const keepAlive = require('./server');
require("dotenv").config();
//const client = new Discord.Client();
//const fetch = require('node-fetch');
const config = require('./package.json');
const prefix = '!';
const guild = "";
client.once('ready', () => {
console.log('Jp Learn Online');
});
// let defaultChannel = "";
// guild.channels.cache.forEach((channel) => {
// if(channel.type == "text" && defaultChannel == "") {
// if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
// defaultChannel = channel;
// }
// }
// })
//defaultChannel.send("This is a test message I should say this message when I join");
//if(guild.systemChannelId != null) return guild.systemChannel.send("This is a test message I should say this message when I join"), console.log('Bot entered new Server.')
// client.on('guildCreate', (g) => {
// const channel = g.channels.cache.find(channel => channel.type === 'GUILD_TEXT' && channel.permissionsFor(g.me).has('SEND_MESSAGES'))
// channel.send("This is a test message I should say this message when I join");
// });
client.on('guildCreate', guild => {
guild.systemChannel.send('this message wil print')
});
client.on('message', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/); // This splits our code into to allow multiple commands.
const command = args.shift().toLowerCase();
if (command === 'jhelp') {
message.channel.send('こんにちは、私はDiscordロボットです。始めたいなら、!jhelp タイプしてください。 \n\n Hello I am a discord bot built to help learn the Japanese language! \n\n If you want to access a japanese dictionary type !dictionary \n\n If you would like to learn a random Japanese Phrase type !teachme \n\n If you would like to answer a challenge question type !challenge1 through 5 each different numbered challnege will ask a different question \n (ie. !challenge1) this will ask the first question.')
}
please note. the lower parts of the code are simply commands. That expand further from jhelp I want to know mainly why my second client.on with messages wont work specifically in the context of working with replit.
Thanks for the help in advance.
I expected that maybe changing intents might work, I even went into the discord developer portal, and enabled options, and am still not able to get it working.
After Discord separated out the message intent as a privileged one, the bit field you need to use for all intents has changed. You need to use 131071.
I.e.
const { Client } = require('discord.js');
const client = new Client({ intents: 131071 });
//const Discord = require('discord.js');
const keepAlive = require('./server');
require("dotenv").config();
//const client = new Discord.Client();
//const fetch = require('node-fetch');
const config = require('./package.json');
const prefix = '!';
const guild = "";
client.once('ready', () => {
console.log('Jp Learn Online');
});
// let defaultChannel = "";
// guild.channels.cache.forEach((channel) => {
// if(channel.type == "text" && defaultChannel == "") {
// if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
// defaultChannel = channel;
// }
// }
// })
//defaultChannel.send("This is a test message I should say this message when I join");
//if(guild.systemChannelId != null) return guild.systemChannel.send("This is a test message I should say this message when I join"), console.log('Bot entered new Server.')
// client.on('guildCreate', (g) => {
// const channel = g.channels.cache.find(channel => channel.type === 'GUILD_TEXT' && channel.permissionsFor(g.me).has('SEND_MESSAGES'))
// channel.send("This is a test message I should say this message when I join");
// });
client.on('guildCreate', guild => {
guild.systemChannel.send('this message wil print')
});
client.on('messageCreate', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/); // This splits our code into to allow multiple commands.
const command = args.shift().toLowerCase();
if (command === 'jhelp') {
message.channel.send('こんにちは、私はDiscordロボットです。始めたいなら、!jhelp タイプしてください。 \n\n Hello I am a discord bot built to help learn the Japanese language! \n\n If you want to access a japanese dictionary type !dictionary \n\n If you would like to learn a random Japanese Phrase type !teachme \n\n If you would like to answer a challenge question type !challenge1 through 5 each different numbered challnege will ask a different question \n (ie. !challenge1) this will ask the first question.')
}
Yes! its the problem with your intents, for guildMemberAdd/Remove you require GuildMembers intents

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")

guildMemberAdd event handler issues

This will be my third question of the day because I am obviously not smart with this. I am using discord.js v12 and my issue this time is with an event handler. The event handler has worked fine so far with things so far like the message or ready. I am right now trying to get a guildMemberAdd event that gives a new person that joins a role and then sends a message in the logs chat indicating they joined. When a user joins, the bot crashes. The guildMemberAdd works on my main index.js file, but won't work under the event handler.
crash log: https://imgur.com/a/MrMi536
here are a few pieces of code if they are needed.
Event Handler:
const { readdirSync } = require('fs');
module.exports = (client) => {
const load = dirs => {
const events = readdirSync(`./events/${dirs}/`).filter(d => d.endsWith('.js'));
for(let file of events){
const event = require(`../events/${dirs}/${file}`);
let eventName = file.split('.')[0];
client.on(eventName, event.bind(null, client));
}
}
['client', 'guild'].forEach(x => load(x));
}
guildMemberAdd:
module.exports = (Discord, client, guildMember) => {
console.log(guildMember);
guildMember.roles.add(guildMember.guild.roles.cache.find(role => role.name === "Member"));
guildMember.channels.cache.get('767090422626779149').send('test');
}
index.js
// heads up that I'm using discord.js v12.4.1 because v13.1.0 is weird and I don't understand it lol
const fs = require('fs');
const Discord = require('discord.js');
require('dotenv').config();
const client = new Discord.Client(); // client = name of bot
// client.on('guildMemberAdd', (guildMember) => {
// guildMember.roles.add(guildMember.guild.roles.cache.find(role => role.name === "Member"));
// });
['aliases', 'commands'].forEach(x => client[x] = new Discord.Collection());
['command', 'event'].forEach(x => require(`./handlers/${x}`)(client));
client.login(process.env.CLIENT_TOKEN); // SECRET TOKEN
I haven't used discord.js or JavaScript in at least a year so any help is appreciated.
There seems to be a problem passing the guildMember object.
Maybe changing this can help you:
client.on(eventName, event.bind(null, client)); //change this
client.on(eventName, (...args) => event.bind(null, client, ...args)) //to this
Note: I am also not 100% sure if you can use guildMember or if you have to use member.

How do i make my discord bot respond to a message with prefix?

What I'm trying to do is set up a discord autoresponse bot that responds if someone says match prefix + respondobject like "!ping". I don't know why it doesn't come up with any response in the dispute. I've attached a picture of what it does. I can't figure out why it's not showing up with any responses in discord.
const Discord = require('discord.js');
const client = new Discord.Client({intents: ["GUILDS", "GUILD_MESSAGES"]});
const prefix = '!'
client.on('ready', () => {
let botStatus = [
'up!h or up!help',
`${client.users.cache.size} citizens!`,
`${client.guilds.cache.size} servers!`
]
setInterval(function(){
let status = botStatus[Math.floor(Math.random() * botStatus.length)]
client.user.setActivity(status, {type: 'WATCHING'})
}, 15000);
console.log(client.user.username);
});
client.on('message', message => {
if(!message.content.startsWith(prefix) || message.author.bot) return
const args = message.content.slice(prefix.length).split(/ +/)
const command = args.shift().toLowerCase()
const responseObject = {
"ping": `🏓 Latency is ${msg.createdTimestamp - message.createdTimestamp}ms. API Latency is ${Math.round(client.ws.ping)}ms`
};
if (responseObject[message.content]) {
message.channel.send('Loading data...').then (async (msg) =>{
msg.delete()
message.channel.send(responseObject[message.content]);
}).catch(err => console.log(err.message))
}
});
client.login(process.env.token);
Your main issue is that you're trying to check message.content against 'ping', but require a prefix. Your message.content will always have a prefix, so you could try if (responseObject[message.content.slice(prefix.length)]).
Other alternatives would be to add the prefix to the object ("!ping": "Latency is...")
Or, create a variable that tracks the command used.
let cmd = message.content.toLowerCase().slice(prefix.length).split(/\s+/gm)[0]
// then use it to check the object
if (responseObject[cmd]) {}

How do I make my music bot resume playing?

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.)

Categories

Resources