はじめに#
今回は、完全に趣味でDiscordのbotを作ってまとめれそうだったのでQiita初投稿です。
目的#
discordの自作botでYoutubeを再生したい!
あわよくばmp3とかのリンクで再生したい!
環境#
DiscordのAPIのNode.js wrapperとしてErisを使っています。
デプロイはHerokuで行っています。
Youtubeからの音声取得はytdl-coreを使用しています。
Eris : https://abal.moe/Eris/
ytdl-core : https://www.npmjs.com/package/ytdl-core
※ytdl-coreをHerokuで使用する際ffmpegを導入しなくてはいけません。
こちらのサイト様を参考にさせていただきました。
http://dosukoikoi.sub.jp/blog/archives/248
コード#
const eris = require("eris");
const ytdl = require('ytdl-core');
var bot = new eris(== 自分で取得したDiscordBotのToken ==);
//メッセージが作られた際に反応
bot.on("messageCreate", (msg) => {
//BOTのメッセージには反応しない
if (msg.author.bot) return;
console.log(msg.content);
MusicPlay(msg);
});
// Discordに接続します
bot.connect();
// 音楽の再生
const streamOptions = { seek: 0, volume: 0.06 };
function MusicPlay(msg) {
// メッセージ投稿メンバーが通話に存在しない場合はスルー
if (!IsVoiceChannel(msg.member.voiceState.channelID)) return;
// URLを抜き出す
let match = (msg.content).match(/(?:^|[\s ]+)((?:https?|ftp):\/\/[^\s ]+)/);
if (!match) return;
let url = match[1];
console.log("再生するURL : " + url);
let channelId = msg.member.voiceState.channelID;
// ボイスチャンネルに参加して再生
bot.getChannel(channelId).join().then(connection => {
if (url.indexOf("youtube") == -1) {
// Youtube以外の場合
connection.play(url, streamOptions);
return;
}
// Youtubeの場合
const stream = ytdl(msg.content, { filter: 'audioonly' });
connection.play(stream, streamOptions);
}).catch(console.error);
};
Erisには標準でmp3のリンクから音声を再生する機能がありますが、
Youtubeを再生する場合ytdlの機能を使用しての、音声streamを渡す必要がありました。
const stream = ytdl(msg.content, { filter: 'audioonly' });
connection.play(stream, streamOptions);
まとめ#
今回はユーザーが音のURLを投稿したときボイスチャンネルに参加して音を再生するBotを作成しました。
初の記事なので至らない点が多いと思いますが手助けになれば幸いです。
間違っている点や改善点等あればコメントにて教えていただける助かります。