Discord.JS | Music Bot "Error: Video Unavailable" - javascript

I'll list the command logic itself and all installed dependencies below. Basically, whenever I run the command in Discord with any youtube link I've given it so far, the bot joins and everything runs correctly but then shortly after, the bot errors out in VSC with the error "Video Unavailable". I've looked through all kinds of forums and watched a lot of videos and I can't find any solution at all.
Play Command Logic:
if (musicArgs.startsWith('play')) {
let musicPlayPrefix = 'play';
let musicPlayArgs = musicArgs.slice(musicPlayPrefix.length).trim();
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
const dispatcher = connection.play(await ytdl(musicPlayArgs), { type: 'opus'})
dispatcher.on('error', console.error);
dispatcher.on('start', () => {
message.channel.send(`**Now Playing:** *${musicPlayArgs}`);
});
dispatcher.on('finish', () => {
message.channel.send(`**Music Finished!**`);
});
}
else {
message.channel.send(`You're not in a voice channel! Retry the command inside of one.`);
}
}
Dependencies in Package.json:
"dependencies": {
"#discordjs/opus": "github:discordjs/opus",
"discord.js": "^12.3.1",
"ffmpeg-static": "^4.2.7",
"hypixel-api-reborn": "^2.2.4",
"libsodium-wrappers": "^0.7.8",
"ytdl-core-discord": "git+https://github.com/amishshah/ytdl-core-discord.git"
}

Related

How to open a file in folders with discord.js

I am now coding a Discord bot in a folder named "bot", and I am making it play audio file. But I face a problem. If every files I want to make it play are stored in "bot", the folder will look mess. So I want to create a new folder named "music" in "bot". But I don't know to open the file in this way. Here is a part of my original code:
if (cmd === "play" && message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
const dispatcher = connection.play('01. Snow halation.flac');
dispatcher.on('start', () => {
console.log('Now playing!');
});
dispatcher.on('finish', () => {
console.log('Finished playing!');
connection.disconnect();
});
dispatcher.on('error', console.error);
I want let file "01. Snow halation.flac" be in "music", and how can I make it play?
const dispatcher = connection.play('./music/01. Snow halation.flac');

Discord.js | Bot doesn't join VC and doesn't give error

so basically when I execute my play cmd with the song I want while I am in VC, my bot does not respond to it and doesn't give any errors but if I just type play without the song I want, I get my Please provide song response.
This is the main file
const distube = require('distube');
client.distube = new distube(client, { searchSongs: true, emitNewSongOnly: true })
client.distube
.on('playSong', (message, queue, song) => message.channel.send(
`Playing \`${song.name}\` - \`${song.formattedDuration}\`\nRequested by: ${song.user}\n${status(queue)}`,
))
.on('addSong', (message, queue, song) => message.channel.send(
`Added ${song.name} - \`${song.formattedDuration}\` to the queue by ${song.user}`,
))
.on('error', (message, e) => {
message.channel.send(`An error occured: ${e}`)
})
and this is the play cmd:
const distube = require("distube");
module.exports = {
name: 'play',
aliases: ['p'],
description: 'play a song!',
async execute(client, message, args) {
const VC = message.member.voice.channel;
if(!VC) return message.reply('Join VC or no music!');
const music = args.join(" ");
if(!music) return message.reply("Please provide me a song name");
await client.distube.play(message, music);
}
}
the packages I use are:
npm i distube
npm i #discordjs/opus
npm i ffmpeg-static
for references, these are the things that I looked at:
https://distube.js.org/guide/example-bot.html
https://www.youtube.com/watch?v=tbPqM6JcGA4&t=883s
This is also not the first time I'm getting this error. I tried using different packages before but still didn't work. All of them don't respond when I provide the song I want. Basically, my only problem is that the bot doesn't join the VC. Does anyone know how to fix this?
In order to operate distube, you also require ytdl-core in your arsenal of packages, which you can install with the same npm install command as always.
This is due to you enables searchSongs but doesn't listen to searchResult event.
Simply edit searchSongs: false in your DisTube constructor to fix this.

Dialogflow fulfilment : agent.add() not returning response to webhook (twilio), works good with dialogflow console and google assistant

I'm creating a chatbot using dialogflow, firebase and twilio on Whatsapp. The interaction works well using the responses from the Intents and using the inline editor function, writes data to the firebase database too. But when I try to return the response from the fulfilment inline editor using the agent.add() method the responses are shown only in the dialogflow console interaction (and the google assistant as well), but not in the Twilio-whatsapp webhook integration. The logs in the GCP show that the data is being read when a request is made from using a text from twilio-whatsapp number.
I just want that the agent.add() text to be returned to twilio message body.
Or if there is some other possible way to do it, so that I can generate dynamic responses based on the data being read from the database.
Response in Dialogflow console
The code in my inline editor.
index.js
// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
"use strict";
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const { WebhookClient } = require("dialogflow-fulfillment");
process.env.DEBUG = "dialogflow:debug"; // enables lib debugging statements
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(
(request, response) => {
const agent = new WebhookClient({
request,
response,
});
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function saveUserDataHandler(agent) {
const firstname = agent.parameters.firstname;
const lastname = agent.parameters.lastname;
const phoneno = agent.parameters.phonenumber;
const dialogflowAgentRef = db.collection("users").doc();
return db
.runTransaction((t) => {
t.set(dialogflowAgentRef, {
firstname: firstname,
lastname: lastname,
phoneno: phoneno,
});
return Promise.resolve("Write complete");
})
.then((doc) => {
agent.add(
` Wrote "${firstname} ${lastname}, ${phoneno}" to the Firestore database.`
);
console.log("wrote to db", firstname, lastname, phoneno);
})
.catch((err) => {
console.log(`Error writing to firestore : ${err}`);
agent.add(
` Failed to write "${firstname} ${lastname}, ${phoneno}" to the Firestore database.`
);
});
}
function readUserDataHandler(agent) {
const dialogflowAgentDoc = db.collection("users");
return dialogflowAgentDoc
.get()
.then((snapshot) => {
snapshot.forEach((doc) => {
if (!doc.exists) {
agent.add("No Data found in the database");
} else {
agent.add(doc.data().firstname);
agent.add(doc.data().lastname);
agent.add(doc.data().phoneno);
console.log(doc.data());
}
return Promise.resolve("Read complete");
});
})
.catch((err) => {
agent.add("Error reading entry from the Firestore database.");
console.log(err);
});
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
// Run the proper function handler based on the matched Dialogflow intent name
let intentMap = new Map();
intentMap.set("Default Welcome Intent", welcome);
intentMap.set("Default Fallback Intent", fallback);
intentMap.set("Get User Data", saveUserDataHandler);
intentMap.set("Read User Data", readUserDataHandler);
agent.handleRequest(intentMap);
}
);
package.json
{
"name": "dialogflowFirebaseFulfillment",
"description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
"version": "0.0.1",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"engines": {
"node": "8"
},
"scripts": {
"start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
"deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
},
"dependencies": {
"actions-on-google": "^2.5.0",
"dialogflow": "^4.0.3",
"dialogflow-fulfillment": "^0.6.1",
"firebase-admin": "^6.4.0",
"firebase-functions": "^2.1.0"
}
}
Links referred : fulfillment-firestore-nodejs, updating dependencies
In the twilio debugger I get a response that the message body is invalid.
MESSAGE
Message body must be specified
Invalid Body
Warning - 14103
Message Invalid Body
The Message body does not contain valid text or a media URL
Something mentioned here too, but the comments there didn't help.
Am I missing something, or is it a bug as others are facing it too??
Thanks in advance.

Discord JS (Bot Presence)

So, in Discord, users can have a custom status, however, when I try to set my bot up with one nothing happens...Even though CUSTOM_STATUS is available
I have bot.user.setPresence({ activity: { name: "Testing", type: "CUSTOM_STATUS" }, status: "online" });
inside of the ready event. I was just wondering why this doesn't work and if there is a work around
According to the docs.
Bots cannot set a CUSTOM_STATUS, it is only for custom statuses received from users
The valid types you could choose from are:
PLAYING
STREAMING
LISTENING
WATCHING
Try client.user.setActivity(Your Status)
I am using this and its working fine
If you are using v12 then i cant help you
You should make sure that your setPresence command is in your ready event. For example, this is my ready command:
const {PREFIX} = require('../config.json');
const { Message } = require('discord.js');
const message = require('./message.js');
//must update when new module.exports event happens
const leaveEvent = require('../util/guildMemberRemove');
const invitecounterEvent = require('../util/guildMemberAddinvitecounter');
const modmailEvent = require('../util/modmail');
module.exports = (client, message) => {
//must update when new module.exports event happens
leaveEvent(client);
invitecounterEvent(client);
modmailEvent(client);
console.log(' ');
console.log(`Hi, ${client.user.username} is now online! My Prefix is ${PREFIX}`);
console.log(`Bot has started, with ${client.users.size} users, in ${client.channels.size} channels of ${client.guilds.size} guilds.`);
//client.user.setActivity(`Serving ${client.guilds.size} servers`); (big servers only)
client.user.setActivity('U', { type: 'WATCHING' }) //PLAYING, STREAMING, LISTENING, WATCHING, CUSTOM_STATUS
.then(presence => console.log(`Activity set to: WATCHING ${presence.activities[0].name}`))
.catch(console.error);
console.log(`Ready as ${client.user.tag} to serve in ${client.channels.cache.size} channels on ${client.guilds.cache.size} servers, for a total of ${client.users.cache.size} users.`);
client.generateInvite(['SEND_MESSAGES', 'MANAGE_GUILD', 'MENTION_EVERYONE', 'ADMINISTRATOR',])
.then(link => {
console.log(`Generated bot invite link: ${link}`);
// eslint-disable-next-line no-undef
inviteLink = link;
});
};
The part that should help you is client.user.setActivity('U', { type: 'WATCHING' })
The different types you can do are PLAYING, STREAMING, LISTENING, and WATCHING.

Discord.js fired several times

The code that I made is fired several times, I have tried to add returns but it doesn't matter. I'm running the code with a raspberry pi 3.
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!')
})
client.on('error', console.error);
client.on('message', message =>{
if (message.channel.id == '...........') {
console.log(message.content);
}
if (message.content.startsWith(`${prefix}ping`)) {
if (message.member.roles.some(role => role.name === '⚙️ | Manager'))
{message.channel.send('Pong!');} else {
message.channel.send('Not enough rights! :no_entry:');
}}
if (message.content.startsWith(`${prefix}test`)) {
if (message.author.id == '.........') {
const role = message.guild.roles.find('name', 'test');
message.member.addRole(role);
message.channel.send('test');
}}});
client.login(token);
I expect it to output it onces, but I don't get it to work.
This is the output:
I want him to do it only once.
Yeah I've had that problem before, simply turn off the bot from everything you're hosting it on, you were probably logged in on it multiple times, that might be because you're running it on a raspberry pi and did not properly shut it.

Categories

Resources