디스코드 봇을 만들어보자(2)_채팅방 입장, 유튜브 검색

개미는뚠뚠·2024년 6월 9일
0

JavaScript

목록 보기
9/9
post-thumbnail

블로그를 열심히 써야하는건 알지만 플젝이 바쁜 관계로 디스코드 봇 만들면서 쉬고 있다 ㅋㅋ ㅠ
기능 관련해서는 해당 포스트에 추가할 예정이다.

🚀 완성 기능 리스트

  1. 음성채팅 in/out 기능(24-06-09)
  2. 유튜브 검색 기능(24-06-09)

1. 음성 채팅 in/out 기능

1-1. npm @discordjs/voice 추가

npm install discord.js @discordjs/voice

1-2. 음성 채널 입장 코드(in)

const { joinVoiceChannel } = require('@discordjs/voice'); 

module.exports = {
    name: '들어와',
    description: '음성채널에 봇이 들어옵니다.',
    run: async (client, msg) => {
      const channel = msg.member.voice.channel;

      joinVoiceChannel({
          channelId: channel.id,
          guildId: channel.guild.id,
          adapterCreator: channel.guild.voiceAdapterCreator,
      });
      msg.reply('음성 채널에 입장했습니다!');
    }
};

1-3. 음성 채널 퇴장 코드(out)

const { getVoiceConnection } = require('@discordjs/voice');

module.exports = {
    name: '나가',
    description: '봇이 음성 채널에서 나갑니다.',
    run: async (client, msg) => {
        const guildId = msg.guild.id;
        const voiceConnection = getVoiceConnection(guildId);
      
        if (voiceConnection) {	//bot이 채널에 있을 때 처리
            voiceConnection.destroy();
            msg.reply('음성 채널에서 나갔습니다!');
        } else {				//나갈 채널이 없을 때 처리
            msg.reply('나갈 음성 채널이 없습니다.');
        }
    }
};

2. 유튜브 검색 기능

2-1. npm youtube-search-api추가

npm install discord.js youtube-search-api

2-2. 유튜브 검색 코드 작성

const search = require('youtube-search-api');

module.exports = {
    name: '유튜브',
    description: '사용자 키워드로 유튜브 영상을 검색합니다.',
    run: async (client, msg) => {
        const args = msg.content.split(' ').slice(1).join(' ');
        if (!args) {
            return msg.reply('검색어를 입력해주세요.');
        }

        try {
            const results = await search.GetListByKeyword(args, false, 5);
            if (results.items.length > 0) {
                const firstResult = results.items[0];
                const videoUrl = `https://www.youtube.com/watch?v=${firstResult.id}`;
                msg.reply(`첫 번째 검색 결과: ${firstResult.title}\n${videoUrl}`);
            } else {
                msg.reply('검색 결과가 없습니다.');
            }
        } catch (error) {
            console.error(error);
            msg.reply('검색 중 오류가 발생했습니다.');
        }
    }
};

3. 추가 예정(06/15~06/16)

0개의 댓글