aboutsummaryrefslogtreecommitdiff
path: root/src/modules/greeting.js
blob: f85bde9510323532256d1e542799c4ee1d8c664b (plain) (blame)
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
const path = require('path');
const fs = require('fs');
const config = require('../config');
const utils = require('../utils');

module.exports = ({ bot }) => {
  if (! config.enableGreeting) return;

  bot.on('guildMemberAdd', (guild, member) => {
    const guildGreeting = config.guildGreetings[guild.id];
    if (! guildGreeting || (! guildGreeting.message && ! guildGreeting.attachment)) return;

    function sendGreeting(message, file) {
      bot.getDMChannel(member.id).then(channel => {
        if (! channel) return;

        channel.createMessage(message || '', file)
          .catch(e => {
            if (e.code === 50007) return;
            throw e;
          });
      });
    }

    const greetingMessage = utils.readMultilineConfigValue(guildGreeting.message);

    if (guildGreeting.attachment) {
      const filename = path.basename(guildGreeting.attachment);
      fs.readFile(guildGreeting.attachment, (err, data) => {
        const file = {file: data, name: filename};
        sendGreeting(greetingMessage, file);
      });
    } else {
      sendGreeting(greetingMessage);
    }
  });
};