hj-stream-bot/index.js
Henry Jameson f775f64034 docker
2026-01-14 15:14:14 +02:00

102 lines
2.2 KiB
JavaScript

import fetch from 'node-fetch';
const botBearer = process.env.BEARER;
const userBearer = process.env.USER_BEARER;
const instance = process.env.INSTANCE;
const videoId = process.env.VIDEO_ID;
const globalState = {
exit: false,
currentlyLive: false,
};
const headers = (bearer) => ({
accept: '*/*',
authorization: `Bearer ${bearer}`,
'cache-control': 'no-cache',
'content-type': 'application/json',
pragma: 'no-cache',
});
const post = ({
status,
spoiler_text,
visibility = 'direct',
content_type = 'text/plain',
}) =>
fetch(`https://${instance}/api/v1/statuses`, {
headers: headers(botBearer),
referrerPolicy: 'same-origin',
body: JSON.stringify({
spoiler_text,
status,
source: "HJ's twitch bot",
visibility,
content_type,
}),
method: 'POST',
mode: 'cors',
credentials: 'include',
});
const scrobble = ({ title, external_link }) =>
fetch(`https://${instance}/api/v1/pleroma/scrobble`, {
headers: headers(userBearer),
referrerPolicy: 'same-origin',
body: JSON.stringify({
title,
external_link,
}),
method: 'POST',
mode: 'cors',
credentials: 'include',
});
// await post({
// spoiler_text: 'Debug',
// status: '@hj twitch bot initialized',
// });
process.on('SIGINT', () => {
globalState.exit = true;
process.exit();
});
const loop = async () => {
const response = await fetch(
`https://tube.ebin.club/api/v1/videos/${videoId}`,
);
const { state } = await response.json();
const isLive = state.id === 1; // published
const stateChange = isLive !== globalState.currentlyLive;
globalState.currentlyLive = isLive;
if (stateChange) {
if (isLive) {
await post({
spoiler_text: 'Stream announcment',
status: [
'hj just went live on peertube',
'',
`https://tube.ebin.club/w/${videoId}`,
].join('\n'),
visibility: 'public',
});
await scrobble({
title: 'Streaming on PeerTube',
external_link: `https://tube.ebin.club/w/${videoId}`,
});
} else {
await scrobble({
title: 'Stream over',
});
}
}
if (!globalState.exit) setTimeout(loop, 30 * 1000);
};
loop();
console.info('Ready!');