-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
183 lines (160 loc) · 6.64 KB
/
index.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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
// Require the necessary discord.js classes
const { Client, EmbedBuilder, Events, GatewayIntentBits, time } = require('discord.js');
const { token, guildID, channelID, chatsThreadID, emailsThreadID, testChannelID } = require('./config.json');
const fs = require('fs');
const { createHash } = require('node:crypto');
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// When the client is ready, run this code (only once)
// We use 'c' for the event parameter to keep it separate from the already defined 'client'
client.once(Events.ClientReady, c => {
console.log(`Ready! Logged in as ${c.user.tag}`);
});
// Log in to Discord with your client's token
client.login(token);
const FAST_INTERVAL = 15
const SLOW_INTERVAL = 60
const FASTS_BEFORE_SLOW = 2
client.on('ready', async () => {
const md5 = (str) => createHash('md5').update(str).digest('hex')
const fetchEmails = async () => {
console.log((new Date()).toISOString(), "Fetching Emails");
const res = await fetch("https://sekiguchigenetics.jp/api/mail-history", {
"credentials": "omit",
"referrer": "https://sekiguchigenetics.jp/mailbox-MGj67PK",
"body": "{\"token\":\"charon\"}",
"method": "POST",
"mode": "cors"
});
return res.json()
}
const fetchChat = async () => {
console.log((new Date()).toISOString(), "Fetching Chat");
const res = await fetch("https://traxus.global/api/chat-history", {
"credentials": "omit",
"referrer": "https://traxus.global/",
"body": "{\"token\":\"serpent\"}",
"method": "POST",
"mode": "cors"
});
return res.json()
}
const readFromJSON = async (fileName) => {
const buffer = fs.readFileSync(fileName)
return JSON.parse(buffer.toString('utf8'))
}
const writeFromJSON = async (fileName, obj) => {
fs.writeFileSync(fileName, Buffer.from(JSON.stringify(obj, null, 2), 'utf8'))
}
const sendMessage = (thread, message) => {
// CHANGE TO THE #marathon CHANNEL FOR PRODUCTION (channelID)
// const channelID = testChannelID
const threadID = thread === 'chat' ? chatsThreadID : emailsThreadID
client.channels.cache.get(channelID).threads.cache.get(threadID).send(message)
}
const sendEmail = async (email) => {
// todo: translate
const fields = [
{ name: "From", value: email.from, inline: true },
{ name: "To", value: email.to, inline: true },
{ name: "Date (fictional)", value: email.maildate, inline: true },
{ name: "Date (IRL)", value: time(new Date(email.date + 'Z')), inline: true },
{ name: "Subject", value: email.subject },
{ name: "Content", value: email.content }
]
if (email.attachement) fields.push(
{ name: "Attachment", value: email.attachement ?? 'None' }
)
sendMessage('email', {
embeds: [{
color: 5763719,
timestamp: email.date,
author: { name: "Sekiguchi Genetics Email" },
fields
}]
})
}
const buildChat = (chat) => {
const fields = [
{ name: "From", value: chat.from, inline: true },
{ name: "Sent", value: time(new Date(chat.timestamp + 'Z')), inline: true },
{ name: "Valid Until", value: time(new Date(chat.valid_until + 'Z')), inline: true },
{ name: "Content", value: chat.message },
]
if (chat.attachment) fields.push(
{ name: "Attachment", value: chat.attachment.metadata.fileName }
)
return {
color: 5763719,
timestamp: chat.timestamp,
author: { name: "Traxus Chat Message" },
fields
}
}
let fetchesWithoutUpdates = 0
const checkForUpdates = async () => {
const emails = await fetchEmails()
const lastEmails = await readFromJSON('emails.json')
const emailIDs = emails.map(email => email.id)
const lastEmailIDs = lastEmails.map(email => email.id)
const newEmailIDs = emailIDs.filter(id => !lastEmailIDs.includes(id))
const newEmails = emails.filter(email => newEmailIDs.includes(email.id))
newEmails.forEach((email) => {
console.log((new Date()).toISOString(), 'New email with id', email.id, 'and subject', email.subject)
sendEmail(email)
})
const chats = await fetchChat()
const lastChats = await readFromJSON('chat.json')
const chatHashes = chats.map(chat => ({ ...chat, hash: md5(JSON.stringify(chat)) }))
const lastChatHashes = lastChats.map(chat => md5(JSON.stringify(chat)))
const newChats = chatHashes.filter(({ hash }) => !lastChatHashes.includes(hash))
if (newChats.length > 0) {
const embeds = newChats.map(buildChat)
const messageEmbeds = [[]]
embeds.forEach((embed) => {
const latest = messageEmbeds[messageEmbeds.length - 1]
if (latest.length === 10) {
messageEmbeds.push([embed])
} else {
latest.push(embed)
}
})
messageEmbeds.forEach((embeds) => {
sendMessage('chat', { embeds })
})
newChats.forEach((chat) => {
console.log((new Date()).toISOString(), 'New chat with timestamp', chat.timestamp, 'and hash', chat.hash)
})
}
if (newChats.length > 0) {
fetchesWithoutUpdates = 0
if (loopSpeed === SLOW_INTERVAL) {
console.log((new Date()).toISOString(), 'Speeding up')
setLoopSpeed(FAST_INTERVAL)
}
}
if (newChats.length === 0) {
fetchesWithoutUpdates++
if (loopSpeed === FAST_INTERVAL && fetchesWithoutUpdates > FASTS_BEFORE_SLOW) {
console.log((new Date()).toISOString(), 'Slowing down')
setLoopSpeed(SLOW_INTERVAL)
}
}
writeFromJSON('emails.json', emails)
writeFromJSON('chat.json', chats)
}
const loop = () => {
checkForUpdates().catch((e) => {
console.error((new Date()).toISOString(), e)
})
}
let interval = null
let loopSpeed = SLOW_INTERVAL
const setLoopSpeed = (delay) => {
if (interval) clearInterval(interval)
loopSpeed = delay
interval = setInterval(loop, delay * 1000)
}
checkForUpdates() // first run
setLoopSpeed(SLOW_INTERVAL) // subsequent runs
})