반응형

이번에 추가할 기능은 아래와 같습니다.

 

[

로컬 노래파일 재생,

로컬 사진 전송,

상태메세지 설정,

메세지 지우기

]

 


개발환경 : UBUNTU 18.04.3

개발언어: NODE JS V8

모듈 : discord.js v11

텍스트 에디터: ATOM (편하신거 사용하시면 됩니다.)

 

 

 

 

로컬 경로에 존재하는 mp3파일을 재생하는 기능입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  if (msg.content === 'r.play') {
    // Only try to join the sender's voice channel if they are in one themselves
    if (msg.member.voiceChannel) {
      msg.member.voiceChannel.join()
        .then(connection => { // Connection is an instance of VoiceConnection
          msg.reply('playing music!');
          const dispatcher = connection.playFile('./music.mp3');
          dispatcher.on("end", end => {});
        })
        .catch(console.log);
    } else {
      msg.reply('먼저 방에 들어가');
    }
  }
  if (msg.content === 'r.leave') {
    // Only try to join the sender's voice channel if they are in one themselves
    if (msg.member.voiceChannel) {
      msg.member.voiceChannel.leave();
      msg.reply('bye!');
    } else {
      msg.reply('이미 나왔는데..');
    }
  }
 
cs

 

r.play는 내가 들어간 음성 채팅방으로 들어가서 music.mp3를 재생합니다. (7행에서 파일명, 경로를 설정할 수 있습니다.)

내가 음성채팅방에 들어가 있지 않은 경우 12행 메세지를 출력합니다.

 

r.leave로 방을 나갈 수 있습니다.

 

 

 

 

오디오 재생시 오디오가 재생되지 않고 바로 종료되는 문제

또는 Error: FFMPEG not found 에러 발생시 아래 포스트 참조

 

https://mandu-mandu.tistory.com/381

 

discord js 설치 후 catch 오류 / 오디오 재생 오류 문제 해결

1. npm으로 discord.js 설치 후 봇 실행시 발생하는 오류 해결 /Client.js:39 } catch { ^ 봇 실행시 위와 같은 오류가 발생할 경우입니다. 저같은 경우에는 discord.js github에 나와있는 설치방법으로 설치를 했..

mandu-mandu.tistory.com

 

 

 


로컬경로에 존재하는 이미지를 채팅방에 전송하는 기능입니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  if (msg.content.startsWith('r.gif')) {
    const args = msg.content.split(' ').slice(1); // All arguments behind the command name with the prefix
    var no = args.join(' '); // Amount of messages which should be deleted
 
    if (!no) no = '1';
    if (isNaN(no) || no > 14return msg.reply('only number 1-14');
 
   // Create the attachment using Attachment
   var path = "./gif/";
   path = path.concat(no,".gif");
   console.log(path);
   const attachment = new Attachment(path);
   // Send the attachment in the message channel with a content
   msg.channel.send(attachment);
  }
cs

명령어는 r.gif n 입니다. n에는 정수가 들어갑니다. ex) r.gif 1

 

저는 gif 이미지를 보내도록 했습니다. 필요에 따라서 10번행의 확장자명을 gif에서 png, jpg등으로 바꾸실 수 있습니다.

저는 ./gif/ 디렉토리 안에 1.gif, 2.gif, 3.gif ... 파일을 넣어 놨습니다.

 

파일 명을 정수로 설정해주세요!

 

 

5번행은 명령어 뒤에 정수가 입력되지 않은 경우 자동으로 1로 하도록

6번행은 숫자인지 검증, 14까지만 입력되도록 한 것입니다.

 


 

상태메세지 설정은 아래 사진과 같이 별명 아래에 메세지를 표시하는 것입니다.

ready 안에 아래 코드 한줄을 추가만 해주시면 됩니다. (전체 코드는 밑에서 확인하실 수 있습니다.)

  client.user.setActivity('봇 만들자', { type: 'WATCHING' })

 

type에는 WATCHING (시청 중) 외에도 

  • PLAYING   (하는 중)
  • STREAMING
  • LISTENING

으로 설정하실 수 있습니다.

 

 

 


메세지 지우기 기능

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  if (msg.content.toLowerCase().startsWith("r.clear")) {
      const args = msg.content.split(' ').slice(1); // All arguments behind the command name with the prefix
      const amount = args.join(' '); // Amount of messages which should be deleted
 
      if (!amount) return msg.reply('You haven\'t given an amount of messages which should be deleted!'); // Checks if the `amount` parameter is given
      if (isNaN(amount)) return msg.reply('The amount parameter isn`t a number!'); // Checks if the `amount` parameter is a number. If not, the command throws an error
 
      if (amount > 10return msg.reply('You can`t delete more than 10 messages at once!'); // Checks if the `amount` integer is bigger than 100
      if (amount < 1return msg.reply('You have to delete at least 1 message!'); // Checks if the `amount` integer is smaller than 1
 
      msg.channel.fetchMessages({ limit: amount }).then(dmsg => { // Fetches the messages
      msg.channel.bulkDelete(dmsg // Bulk deletes all messages that have been fetched and are not older than 14 days (due to the Discord API)
      ).catch(console.log);});
    }
cs

 

r.clear n 과 같이 입력하면, n개의 메세지를 삭제해줍니다.

 

8행 9행에서 각각 최대 최소 개수를 설정할 수 있습니다.

 

 

 

 


전체 봇 소스코드 bot.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Extract the required classes from the discord.js module
const { Client, Attachment } = require('discord.js');
 
// Create an instance of a Discord client
const client = new Client();
 
 
client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
  client.user.setActivity('봇 만들자', { type: 'WATCHING' })
});
 
client.on('message', msg => {
  if (msg.content.startsWith('r.help')) {
    msg.reply('Powered by node.js\nMade by M4ndU');
  }
  if (msg.content.startsWith('r.gif')) {
    const args = msg.content.split(' ').slice(1); // All arguments behind the command name with the prefix
    var no = args.join(' '); // Amount of messages which should be deleted
 
    if (!no) no = '1';
    if (isNaN(no) || no > 14return msg.reply('only number 1-14');
 
   // Create the attachment using Attachment
   var path = "./gif/";
   path = path.concat(no,".gif");
   console.log(path);
   const attachment = new Attachment(path);
   // Send the attachment in the message channel with a content
   msg.channel.send(attachment);
  }
 
 
  if (msg.content === 'r.play') {
    // Only try to join the sender's voice channel if they are in one themselves
    if (msg.member.voiceChannel) {
      msg.member.voiceChannel.join()
        .then(connection => { // Connection is an instance of VoiceConnection
          msg.reply('playing music!');
          const dispatcher = connection.playFile('./music.mp3');
          dispatcher.on("end", end => {});
        })
        .catch(console.log);
    } else {
      msg.reply('먼저 방에 들어가');
    }
  }
  if (msg.content === 'r.leave') {
    // Only try to join the sender's voice channel if they are in one themselves
    if (msg.member.voiceChannel) {
      msg.member.voiceChannel.leave();
      msg.reply('bye!');
    } else {
      msg.reply('이미 나왔는데..');
    }
  }
 
  if (msg.content.toLowerCase().startsWith("r.clear")) {
      const args = msg.content.split(' ').slice(1); // All arguments behind the command name with the prefix
      const amount = args.join(' '); // Amount of messages which should be deleted
 
      if (!amount) return msg.reply('You haven\'t given an amount of messages which should be deleted!'); // Checks if the `amount` parameter is given
      if (isNaN(amount)) return msg.reply('The amount parameter isn`t a number!'); // Checks if the `amount` parameter is a number. If not, the command throws an error
 
      if (amount > 10return msg.reply('You can`t delete more than 10 messages at once!'); // Checks if the `amount` integer is bigger than 100
      if (amount < 1return msg.reply('You have to delete at least 1 message!'); // Checks if the `amount` integer is smaller than 1
 
      msg.channel.fetchMessages({ limit: amount }).then(dmsg => { // Fetches the messages
      msg.channel.bulkDelete(dmsg // Bulk deletes all messages that have been fetched and are not older than 14 days (due to the Discord API)
      ).catch(console.log);});
    }
 
  if (msg.content === 'r.whoami') {
    // Send the user's avatar URL
    msg.reply(msg.author.avatarURL);
  }
});
 
client.login('token');
 
cs

 

79행 token에 반드시 자신의 봇의 토큰값을 입력하세요

반응형

+ Recent posts