discord-home-cinema/main.js
2022-07-11 11:40:57 +02:00

95 lines
No EOL
2.2 KiB
JavaScript

import { overrideConsole } from 'nodejs-better-console';
import createFastify from 'fastify';
import Eris from 'eris';
import {
webPort,
webApiKey,
webRequestInterval,
botToken,
botWhitelist
} from './config.js';
overrideConsole();
const
fastify = createFastify(),
eris = new Eris(
botToken,
{ intents: ['directMessages'] }
);
let
url,
nextRequestTimestamp,
nextRequestTimeout;
fastify.get(
'/',
async (
request,
reply
) => {
if(request.query['apiKey'] !== webApiKey)
return reply.code(401).send();
reply.send(url);
url = '';
nextRequestTimestamp = Date.now() + webRequestInterval;
clearTimeout(nextRequestTimeout);
nextRequestTimeout = setTimeout(
async () => {
await eris.editStatus('idle');
},
webRequestInterval
);
await eris.editStatus('online');
}
);
eris.on(
'messageCreate',
async ({
guildID,
author: { id: authorID },
channel: { id: channelID },
id: messageID,
content
}) => {
if(
guildID
||
!botWhitelist.includes(authorID)
) return;
const reply = content => eris.createMessage(
channelID,
{
content,
messageReference: { messageID }
}
);
if(content){
try {
new URL(content);
url = content;
await reply(
nextRequestTimestamp && nextRequestTimestamp > Date.now()
? `ETA: ${Math.ceil((nextRequestTimestamp - Date.now()) / 1000)} seconds.`
: 'ETA: as soon as online.'
);
}
catch {
await reply('Invalid URL');
}
}
}
);
(async () => {
await fastify.listen({ port: webPort });
await Promise.all([
eris.connect(),
new Promise(resolve => eris.once('ready', resolve))
]);
await eris.editStatus('idle');
console.log('Ready');
})().catch(error => console.error(error));