-
Notifications
You must be signed in to change notification settings - Fork 59
/
stickyMessageSet.ts
105 lines (91 loc) · 2.68 KB
/
stickyMessageSet.ts
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import {
ChannelType,
Message,
PermissionsBitField,
TextChannel,
} from 'discord.js'
import { StickyMessage } from '@prisma/client'
import { prisma } from '@/prisma'
import { Logger } from '@/types/Logger'
import { getCache, saveCache } from '@/utils/cache'
import { sendDm } from '@/utils/sendDm'
import { STICKY_CACHE_PREFIX } from './stickyMessages'
export async function stickyMessageSet(
message: Message,
log: Logger = console,
) {
if (!message.content.startsWith('?stickao-set')) {
return
}
// Check if it is a text channel
const channel = message.channel
if (channel?.type !== ChannelType.GuildText) {
await sendDm(message, {
content: 'Sticky text can only be created in a text channel.',
})
await message.delete()
return
}
// Check if the user has the 'MANAGE_MESSAGES' permission
const authorPermissions = channel.permissionsFor(message.author)
if (!authorPermissions?.has(PermissionsBitField.Flags.ManageMessages)) {
await sendDm(message, {
content:
'You must have the `Manage Messages` permission to use this command.',
})
await message.delete()
return
}
// Get content from the message
const messageContent = message.content.replace('?stickao-set', '').trim()
if (!messageContent) {
await sendDm(message, {
content: 'Please provide a valid message content for Stickao Message.',
})
await message.delete()
return
}
try {
const oldStickyMessage = getCache(
`${STICKY_CACHE_PREFIX}-${message.channelId}`,
) as StickyMessage
if (oldStickyMessage) {
const oldMessage = await message.channel.messages.fetch(
oldStickyMessage.messageId,
)
await oldMessage.delete()
}
// Send message
const sentMessage = await (channel as TextChannel).send({
content: messageContent,
})
// Save message
const stickyMessage = await prisma.stickyMessage.upsert({
create: {
messageId: sentMessage.id,
channelId: message.channelId,
message: messageContent,
},
update: {
messageId: sentMessage.id,
message: messageContent,
},
where: {
channelId: message.channelId,
},
})
saveCache(`${STICKY_CACHE_PREFIX}-${message.channelId}`, stickyMessage)
// Successfully create sticky message
log.info(`Sticky message saved: ${messageContent}`)
await sendDm(message, {
content: 'Successfully created sticky message.',
})
} catch (error) {
log.error(`Unable to create sticky message:`, error)
await sendDm(message, {
content: 'An error occurred while creating the sticky message.',
})
} finally {
await message.delete()
}
}