Watch a live Youtube stream directly on Discord using discord.js!

Recently, I've been experimenting with creating a custom Discord bot as a way to have some fun and help out my friends. One of the features I'm trying to implement is streaming a live video in a voice chat whenever someone uses the !play study command. However, I keep encountering the same frustrating error message when using ytdl-core-discord:

Error: Error parsing info: Unable to retrieve video metadata...

After doing some research, many suggest that updating ytdl should fix this issue. Despite installing it today and confirming that it's up-to-date, I still can't get the music to play in the voice channel, even though the bot successfully joins the channel.

Here's a snippet from my code (foo.ts):

import {MessageEmbed, Message} from 'discord.js';
import config from '../../GGBot.config.js';
import ytdl from 'ytdl-core-discord';

export default async (msg: Message) => {
    if(!msg.member?.voice.channelID){
        msg.channel.send(
            new MessageEmbed()
            .setColor(config.embedColor)
            .setTitle('You Must Be In A Voice Channel To Play Audio')
            .setThumbnail(msg.author.displayAvatarURL())
            .setDescription('Please join a voice channel to play audio')
        )
        return;
    }

    const connection = await msg.member.voice.channel?.join();
    const stream = await ytdl('w2Ov5jzm3j8', {filter:'audioonly'});
    connection?.play(stream, {seek:0, volume:1})
        .on('finish', () => msg.member?.voice.channel?.leave());
    console.log('playing')
        
}

Answer №1

After researching the documentation, it appears that passing an ID directly to the ytdl function may not be possible; instead, you should provide a URL. For example, something along the lines of

"https://www.youtube.com/watch?v= ${videoId}"

Additionally, here is the link to the official ytdl-core documentation: docs. It's important to note that ytdl-core-discord serves as a wrapper for this core functionality.

Answer №2

To enhance the audio quality, simply select a number between 93 and 95 (this method has been effective for me)

const connection = await msg.member.voice.channel?.join();
const stream = await ytdl('streamlink', {filter:'audioonly'}, {quality: '94'});
connection?.play(stream, {seek:0, volume:1})
.on('finish', () => msg.member?.voice.channel?.leave());
console.log('playing')

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can someone please point me in the right direction to locate a Typescript project within Visual Studio

I've been struggling with this issue for days and still can't find a solution. After installing the Typescript tool for Visual Studio 2015, it appears to be successfully installed. https://i.stack.imgur.com/nlcyC.jpg However, I am unable to loc ...

Unveiling the Power of Angular2: Enhancing Functionality

Struggling to implement a lowercase pipe in angular2 and encountering syntax errors with ';' syntax errors got ';' app/lowercase.ts import {Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'lowercase1'} ...

Starting up the Angular 2 Bootstrap Datepicker

For my Angular 2 application, I am using the Bootstrap datepicker plugin () but encountering some initialization issues. The code snippet below is currently working for initializing the datepicker in my component, however, it does not look very clean: ng ...

Preserve the checkbox state upon refreshing the page

I am facing an issue with keeping the checkbox state saved after a page reload. Currently, I have stored my unchecked checkboxes in localStorage, but I am unsure about what steps to take next. In simple terms, I want the checkbox to remain unchecked when I ...

New feature incorporated at the end of choices in MUI auto-suggest widget

Currently, I'm working on enhancing a category adder feature. Previously, I had limited the display of the "add category chip" to only appear for the no-options render scenario. However, I came across an issue where if there was a category like "softw ...

Sending an array of files with JSON through axios: A guide

Working on a React project with TypeScript and Axios, I am faced with the challenge of sending an array of images to the server. Can this be achieved using JSON instead of FormData? Upon setting the array named images, the files received on the server are ...

Enhancing User Authentication: Vue 3 with TypeScript Login

Recently, I came across a new technology called Supabase and noticed that most resources mention registration on JavaScript instead of TypeScript. As I started working on a project using Vue 3 + TypeScript, I encountered some errors that I need help resolv ...

The setter of the computed property is failing to execute

Currently, I am working with a computed property that represents an object of a specific type defined within my Vuex Store. The goal is to utilize this property in my component using v-model. I have thoroughly set up getters and setters for this property a ...

Creating an npm library using TypeScript model classes: A step-by-step guide

Currently, I am working on a large-scale web application that consists of multiple modules and repositories. Each module is being developed as an individual Angular project. These Angular projects have some shared UI components, services, and models which ...

Angular 4 - Automatically scroll to specific list item based on search query input

While I can achieve this with custom JavaScript, I'm curious if Angular 4 has any built-in features that could help. I have a list of checkboxes that are scrollable and a search input above them. My goal is to enable users to quickly jump to a section ...

Incorrect typings being output by rxjs map

combineLatest([of(1), of('test')]).pipe( map(([myNumber, myString]) => { return [myNumber, myString]; }), map(([myNewNumber, myNewString]) => { const test = myNewString.length; }) ); Property 'length' does not ...

Disregarding extraneous object attributes that come with a Back-End object

Seeking advice on how to handle unnecessary object properties that come with a Back-End model. Could you please share your thoughts? Imagine an API returning the following object: export class TodoObject{ public name: string; public id: number, publi ...

Ways to enhance a component by incorporating default properties in React/TypeScript

I am looking to enhance a React/TS component (specifically the @mui/x-data-grid DataGrid) by populating the classes prop with my own application classes. Initially, I thought about creating a new component called CustomDataGrid like this: import React fro ...

StartWith in RxJS: Conditional Implementation

My objective here is to utilize startWith conditionally based on the value of another observable. I attempted using mergeMap instead of map and encapsulated the return values with 'of' but it didn't yield the desired results. fromEvent(ele ...

Tips for simulating Firebase authentication providers like FacebookAuthProvider?

My goal is to create a mock for the firebase.auth object in react-native-firebase, specifically targeting the signInWithCredential method. This mock will allow me to test my code effectively. The code I am testing looks like this: public async FacebookSi ...

Using RXJS with Typescript to wait for an observable to emit until another observable of type boolean evaluates to false

In my current setup, when a user navigates in a view, an API call is made to fetch the data for that specific view. This data is then used later on to decide whether a dialog should pop up when a user performs an action. While the solution is functional a ...

The function is failing to trigger when clicked within an Angular 5 app

Hey everyone, I'm facing a minor issue with my Angular 5 project. I am trying to use a common session check method from a shared TypeScript file. This method is used both when the page loads and when the logout button is clicked to redirect the user t ...

I'm having trouble locating a declaration file for the module 'vue-prism-component'

Currently utilizing Vue 3 (Composition API), Vite, and Typescript but encountering a missing module issue with vue-prism-component. <script lang="ts" setup> import 'prismjs' import 'prismjs/themes/prism-tomorrow.css' imp ...

What are the steps to transpile NextJS to es5?

Is it possible to create a nextjs app using es5? I specifically require the exported static javascript to be in es5 to accommodate a device that only supports that version. I attempted using a babel polyfill, but after running es-check on the _app file, ...

Tips on incorporating toggle css classes on an element with a click event?

When working with Angular typescript instead of $scope, I am having trouble finding examples that don't involve $scope or JQuery. My goal is to create a clickable ellipsis that, when clicked, removes the overflow and text-overflow properties of a spec ...