This is my code:
if (msg.content.includes('*stream')) {
var name=(msg.content).slice(8,80);
if (msg.member.voiceChannel) {
msg.member.voiceChannel.join()
.then(connection => {
console.log(name);
const dispatcher = connection.playFile(name);
dispatcher.setVolume(0.5);
})
.catch(console.log);
} else {
msg.reply('Enter channel first');
}
}
When I write in Discord *stream https://play.sas-media.ru/play, the console shows the full link (https://play.sas-media.ru/play), the bot enters the voice channel, but nothing else happens.
What am I doing wrong?
Related
I've been working on this code for a discord bot that tracks a the voice channels of a server until a specific person joins which then the bot joins and then plays an audio. However whenever I start up my file, it keeps on saying
[nodemon] starting `node index.js`
[nodemon] clean exit - waiting for changes before restart
I have no clue why, I've looked online and I haven't seen any other people having the same issue as me, and if they did the answer didn't help.
Here is my code.
const { Client, GatewayIntentBits } = require('discord.js');
const { Lavalink } = require('discord.js-lavalink');
class MyBot {
// The Discord.js client object that represents our bot
client;
// The ID of the specific person we want to track
userIdToTrack;
// The audio file to play when the specific person joins
audioFile;
constructor(client, userIdToTrack, audioFile) {
// Save the client object and user ID and audio file for later use
this.client = "[bot token]";
this.userIdToTrack = '[discord id]';
this.audioFile = '[file name]';
}
onGuildVoiceJoin(event) {
// Get the member who just joined the voice channel
const member = event.member;
// If the member is the specific person we want to track...
if (member.id === this.userIdToTrack) {
// Get the voice channel that the member joined
const voiceChannel = event.channel;
// Join the voice channel with the bot
voiceChannel.guild.voice.channel.join();
// Play the audio file using Lavalink
lavalink.play(voiceChannel, {
track: '[file name]',
});
const client = new Client({
token: 'bot token]',
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildPresences,
],
});
// Create a new instance of the Lavalink class and connect to the Lavalink nodes
const lavalink = new Lavalink({
client: client,
nodes: [
{ host: 'ratio-w', port: 2334, password: 'youshallnotpass' },
],
});
lavalink.connect();
client.on('ready', () => {
console.log('The bot is ready');
// Create a new instance of the bot, passing in the client object, user ID, and audio file
const bot = new MyBot("bot token", "user id", "file name");
// Listen for voice state update events, which are triggered when a user joins or leaves a voice channel
client.on('voiceStateUpdate', (oldState, newState) => {
// Check if the user we want to track has just joined a voice channel
if (newState.member.id === userIdToTrack && newState.channel) {
// Get the voice channel the user joined
const voiceChannel = newState.channel;
// Join the voice channel with the bot
voiceChannel.join().then(connection => {
// Play the audio file using Lavalink
lavalink.play(voiceChannel, {
track: audioFile,
});
});
}
});
client.on('messageCreate', message => {
if (message.content === 'ping') {
message.reply('hey <#user id>, you STINK!!!!111!');
}
});
client.on('messageCreate', message => {
if (message.content === 'shut up [redacted]') {
message.reply('yeah <#user id> shut up smelly');
}
});
client.on('messageCreate', message => {
if (message.content === 'stop being a nerd [redacted]') {
message.reply('<#user id> be like :nerd:');
}
});
});
process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Rejection at:', reason.stack || reason)
// Recommended: send the information to sentry.io
// or whatever crash reporting service you use
})
client.login('[bot id]');}}}
I tried fixing any possible syntax errors, I've tried looking online but no help was found, I've properly started lavalink (I think), I've edited some of the code so that all possible parts are fixed. I've downloaded all possible directories like updating discord.js, node.js, lavalink.js, and more I think.
I was planning to add some voice features to my discord bot, but for some reason when I run my code, it doesn't make sound while discord does show the green circle around my bot, showing that it's making sound. It also does't log any errors or anything else, does anyone know what's wrong with my code?
Code:
if (command == "soundtest") {
mongo().then(async (mongoose) => {
const { voice } = msg.member
if (voice.channelID) {
const vc = voice.channel
// console.log(channel)
try {
vc.join().then(connection => {
connection.play(path.join(__dirname, 'Bastille_Pompeii.mp3'))
})
} catch(e) {
console.log("error")
console.log(e)
}
} else {
msg.channel.send(`You must join a voice channel to use this command`)
}
})
}
Thanks for reading!
This code should work for you:
const { createReadStream } = require('fs');
const { join } = require('path');
const { createAudioResource, StreamType, createAudioPlayer, joinVoiceChannel } = require('#discordjs/voice');
const player = createAudioPlayer()
joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
}).subscribe(player)
let resource = createAudioResource(join('./folder/', '<song_name>.mp3'));
player.play(resource)
As you said, you tried to play file named Bastille_Pompeii.mp3, so you need to define resource like this: let resource = createAudioResource(join('./musicfiles/', 'Bastille_Pompeii.mp3'));
I am working on a bot for a friend that will play a sound while he is streaming. For this to work I would have the bot play the sound when someone in the stream chat types !scream or any other noise.
But the farthest I have gotten is to get the bot to join the channel and appear to be speaking (the green light around the bot avatar will light up), but it will not stop or play any sound. I have installed all of the necessary dependencies such as FFMPEG and node-opus
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
if(msg.content == '!leave') {
console.log("Left")
client.leaveVoiceChannel();
}
console.log(msg.id)
if (msg.content === "!join") {
msg.member.voiceChannel.join().then(connection => {
connection.playFile('J:/Discord-Bot/test.mp3');
console.log("played")
});
if (msg.content === '!ping') {
msg.reply('Pong!');
}
}});
client.login('TOKEN')
I followed a youtube coding tutorial on coding a music bot and then upgraded the command little by little, I tested everything personally until it worked perfectly. 1 Day later I'm getting errors when I'm trying to play music and I don't know what happened.
I tried deleting several stuff in my code that might've been the problem and in the end none of them were the actual problem
const YTDL = require('ytdl-core')
function play(connection, message)
{
var server = servers[message.guild.id]
server.dispatcher = connection.playStream(YTDL(server.queue[0], {filter: "audioonly"}))
server.dispatcher.on("end", function() {
if(server.queue[0])
{
play(connection, message)
const args = server.queue[0]
YTDL.getInfo(args, function(err, info) {
const title = info.title
message.channel.send(`:musical_note: **${title}** is now playing!`)
})
server.queue.shift()
}
else
{
connection.disconnect()
message.channel.send(":warning: There are no more songs in the queue!")
}
})
}
class playCommand extends commando.Command
{
constructor(client)
{
super(client, {
name: 'play',
group: 'simple',
memberName: 'play',
description: 'idfl'
})
}
async run(message, args)
{
if(!args[0])
{
message.channel.send("Please provide a link")
return;
}
if(!message.member.voiceChannel)
{
message.channel.send("You must be in a voice channel")
return;
}
if (message.content.includes("http://") || message.content.includes("https://")) {
if (message.content.includes("youtube") || message.content.includes("youtu.be")) {
if(!servers[message.guild.id]) servers[message.guild.id] = {queue: []}
var server = servers[message.guild.id]
server.queue.push(args)
if(!message.guild.voiceConnection) message.member.voiceChannel.join().then(function(connection) {
play(connection, message)
const args = message.content.split(" ").slice(1);
YTDL.getInfo(args.join(" "), function(err, info) {
const title = info.title
message.channel.send(`:musical_note: **${title}** is now playing!`)
})
server.queue.shift()
})
}
else
{
message.reply("Only youtube links!")
}
}
else
{
message.reply("Only youtube links!")
}
}
}
module.exports = playCommand;
What should've happened is: bot playing music and sending a message with what song he is playing, and that worked perfectly fine just 1 day ago. This is the error I've got.
C:\Users\Nume\Desktop\Bot\node_modules\opusscript\build\opusscript_native_wasm.js:8
var Module=typeof Module!=="undefined"?Module:{};var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}Module["arguments"]=[];Module["thisProgram"]="./this.program";Module["quit"]=function(status,toThrow){throw toThrow};Module["preRun"]=[];Module["postRun"]=[];var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_HAS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_HAS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";ENVIRONMENT_IS_NODE=ENVIRONMENT_HAS_NODE&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var scriptDirectory="";function locateFile(path){if(Module["locate
Error: This video is unavailable
at C:\Users\Nume\Desktop\Bot\node_modules\ytdl-core\lib\info.js:255:16
at Object.exports.<computed> [as getBasicInfo] (C:\Users\Nume\Desktop\Bot\node_modules\ytdl-core\lib\info.js:367:7)
at exports.getFullInfo (C:\Users\Nume\Desktop\Bot\node_modules\ytdl-core\lib\info.js:211:18)
at Function.exports.<computed> [as getInfo] (C:\Users\Nume\Desktop\Bot\node_modules\ytdl-core\lib\info.js:369:7)
at ytdl (C:\Users\Nume\Desktop\Bot\node_modules\ytdl-core\lib\index.js:17:8)
at play (C:\Users\Nume\Desktop\Bot\commands\simple\play.js:8:51)
at StreamDispatcher.<anonymous> (C:\Users\Nume\Desktop\Bot\commands\simple\play.js:13:17)
at StreamDispatcher.emit (events.js:209:13)
at StreamDispatcher.destroy (C:\Users\Nume\Desktop\Bot\node_modules\discord.js\src\client\voice\dispatcher\StreamDispatcher.js:294:10)
at AudioPlayer.destroyCurrentStream (C:\Users\Nume\Desktop\Bot\node_modules\discord.js\src\client\voice\player\AudioPlayer.js:77:18)
Emitted 'error' event on PassThrough instance at:
at C:\Users\Nume\Desktop\Bot\node_modules\ytdl-core\lib\index.js:19:14
at C:\Users\Nume\Desktop\Bot\node_modules\ytdl-core\lib\info.js:370:25
at C:\Users\Nume\Desktop\Bot\node_modules\ytdl-core\lib\info.js:255:7
at Object.exports.<computed> [as getBasicInfo] (C:\Users\Nume\Desktop\Bot\node_modules\ytdl-core\lib\info.js:367:7)
[... lines matching original stack trace ...]
at StreamDispatcher.emit (events.js:209:13)
Updated ytdl-core and it worked perfectly fine afterwards
I am making a discord bot that is being activated by voice recognition, im at the very beginning right now im making him join a voice channel (which is working), and im trying to make a command to make him leave.
const commando = require('discord.js-commando');
class LeaveChannelCommand extends commando.Command
{
constructor(client){!
super(client,{
name: 'leave',
group: 'music',
memberName: 'leave',
description: 'leaves a voice channel'
});
}
async run(message, args)
{
if(message.guild.voiceConnection)
{
message.guild.voiceConnection.disconnect();
}
else
{
message.channel.sendMessage("seccessfully left")
}
}
}
module.exports = LeaveChannelCommand;
right now you can type !leave from anywhere in the server and the bot leaves,
i want to make it possible to control him only from the same voice channel,
what should i do
It's fairly easy to do. All you need to do is grab the bot's voiceChannel and the user's voiceChannel (if he is in one) and check if they are the same.
Below you can find some example code. Give it a try and let me know how it goes.
async run(message, args)
{
// If the client isn't in a voiceChannel, don't execute any other code
if(!message.guild.voiceConnection)
{
return;
}
// Get the user's voiceChannel (if he is in one)
let userVoiceChannel = message.member.voiceChannel;
// Return from the code if the user isn't in a voiceChannel
if (!userVoiceChannel) {
return;
}
// Get the client's voiceConnection
let clientVoiceConnection = message.guild.voiceConnection;
// Compare the voiceChannels
if (userVoiceChannel === clientVoiceConnection.channel) {
// The client and user are in the same voiceChannel, the client can disconnect
clientVoiceConnection.disconnect();
message.channel.send('Client has disconnected!');
} else {
// The client and user are NOT in the same voiceChannel
message.channel.send('You can only execute this command if you share the same voiceChannel as the client!');
}
}