Streaming Audio over Discord via a bot

For a while I've been tinkering with bots and creating them for various Discord servers since the start of the year when Discord posted a blog post explaining how a group of dedicated users reverse engineered the client to map out an API then gone ahead and created a library to make use of said API.

Image from the blog post, The Robot Revolution has Unofficially Begun (Unofficial API)

Using the discordie library managed by qeled and created for node.js, I created a bot that accepts YouTube URLs to videos and plays the audio over VOIP to anyone in the same channel as the bot through FFMPEG's encoding.
The bot downloads the audio from the video by choosing the best quality possible (which is usually webm), and piping that stream directly into an AudioEncoder that's part of the library.

After ytdl returns all the information on the YouTube video, the below code block finds the best source available to stream from...

//Sort through all the available formats to find the best one
//If no best source is found, playback will not continue
var formats = object.formats.filter(f => f.container === 'webm').sort((a, b) => b.audioBitrate - a.audioBitrate);

var bestaudio = formats.find(f => f.audioBitrate > 0 && !f.bitrate) || formats.find(f => f.audioBitrate > 0);  
if(!bestaudio) return functions.SendMessage(channel, ':exclamation: No valid audio formats found');  

Then the source is plugged into the ExternalEncoder and let's the library take care of the rest.

//If found, use it as the source for the Encoder
encoder = info.voiceConnection.createExternalEncoder({  
    type: 'ffmpeg',
    source: bestaudio.url
});
var stream = encoder.play();  

Github link here. The README includes all the dependencies to run the bot

Tom Lynn

Read more posts by this author.

Australia http://rubbix.net