UNPKG

1.36 kBPlain TextView Raw
1import handleMentions from './handleMentions'
2
3const log = logger.withScope('discord:sendMessage')
4
5import { DiscordMessageData } from '../createMessage/MessageData'
6
7export default async (channelId: string, { body, opts }: DiscordMessageData, image?: string) => {
8 // check if body is empty and there are no files
9 if (!body && !(opts.files && opts.files.length)) return log.warn('Not sending message, empty.')
10
11 // get channel
12 const channel = discord.getChannel(channelId)
13
14 // handle mentions
15 body = handleMentions(body, channel)
16
17 // find / create a webhook
18 let webhook = discord.webhooks.find(webhook => webhook.channelID === channel.id)
19 if (!webhook) {
20 const myself = channel.guild.members.find(member => member.id === discord.client.user.id)
21 if (!myself.hasPermission('MANAGE_WEBHOOKS')) {
22 log.warn(`Bot doesn't have permissions to post in channel #${channel.name} (${channel.id})`)
23 return
24 }
25
26 webhook = await channel.createWebhook(`Miscord #${channel.name}`.substr(0, 32), image || 'https://miscord.net/img/icon.png')
27 discord.webhooks.set(webhook.id, webhook)
28 }
29 log.trace('webhook', { webhook }, 1)
30
31 log.debug('Sending the message')
32 const sentMessage = await webhook.send(body, opts)
33
34 log.debug('Sent message on Discord')
35 log.trace('sent message', { sentMessage }, 1)
36
37 return sentMessage
38}