PronounsPage/server/calendarBot.js
2024-12-25 12:12:58 +01:00

178 lines
5.8 KiB
JavaScript

import './setup.ts';
import fs from 'fs';
import { AtpAgent, RichText } from '@atproto/api';
import * as Sentry from '@sentry/node';
import Mastodon from 'mastodon';
import fetch from 'node-fetch';
import Twitter from 'twitter';
import buildLocaleList from '../src/buildLocaleList.ts';
const __dirname = new URL('.', import.meta.url).pathname;
const locales = buildLocaleList('_');
const publishers = {
async twitter(tweet, _image, _rootId, previousId, _locale) {
const client = new Twitter({
consumer_key: process.env.TWITTER_CALENDAR_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CALENDAR_CONSUMER_SECRET,
access_token_key: process.env.TWITTER_CALENDAR_ACCESS_TOKEN_KEY,
access_token_secret: process.env.TWITTER_CALENDAR_ACCESS_TOKEN_SECRET,
});
try {
const tweetResponse = await client.post('statuses/update', {
status: tweet,
...previousId ? { in_reply_to_status_id: previousId } : {},
});
console.log(tweetResponse);
return tweetResponse.id_str;
} catch (error) {
Sentry.captureException(error);
}
},
async mastodon(tweet, image, _rootId, previousId, locale) {
const client = new Mastodon({
access_token: process.env.MASTODON_CALENDAR_ACCESS_TOKEN,
api_url: `https://${process.env.MASTODON_CALENDAR_INSTANCE}/api/v1/`,
});
const mediaIds = [];
if (image) {
try {
const mediaResponse = await client.post('media', {
file: image,
description: 'Screenshot of the link above',
});
console.log(mediaResponse);
mediaIds.push(mediaResponse.data.id);
} catch (error) {
Sentry.captureException(error);
}
}
try {
const tweetResponse = await client.post('statuses', {
status: tweet,
media_ids: mediaIds,
visibility: 'unlisted',
...previousId ? { in_reply_to_id: previousId } : {},
language: locale,
});
console.log(tweetResponse.data);
return tweetResponse.data.id;
} catch (error) {
Sentry.captureException(error);
}
},
async bluesky(tweet, image, rootId, previousId, locale) {
const agent = new AtpAgent({ service: 'https://bsky.social' });
await agent.login({
identifier: process.env.BLUESKY_CALENDAR_IDENTIFIER,
password: process.env.BLUESKY_CALENDAR_PASSWORD,
});
const media = [];
if (image) {
try {
const uploadResponse = await agent.uploadBlob(image, { encoding: 'image/png' });
console.log(uploadResponse);
media.push(uploadResponse.data.blob);
} catch (error) {
Sentry.captureException(error);
}
}
try {
const rt = new RichText({
text: tweet,
});
await rt.detectFacets(agent);
const postResponse = await agent.post({
$type: 'app.bsky.feed.post',
text: rt.text,
facets: rt.facets,
embed: {
$type: 'app.bsky.embed.images',
images: media.map((blob) => ({ image: blob, alt: '' })),
},
...previousId
? {
reply: {
root: rootId,
parent: previousId,
},
}
: {},
langs: [locale],
createdAt: new Date().toISOString(),
});
console.log(postResponse);
return {
uri: postResponse.uri,
cid: postResponse.cid,
};
} catch (error) {
Sentry.captureException(error);
}
},
};
const tmpDir = `${__dirname}/../cache/tmp`;
fs.mkdirSync(tmpDir, { recursive: true });
const imageTmpPath = `${tmpDir}/calendar-tmp.png`;
const rootPostId = {};
const lastPostId = {};
(async () => {
if (process.argv.length !== 4) {
console.error('Missing parameters. Usage: node server/calendarBot.js <locales> <publishers>');
return;
}
for (const locale of process.argv[2].split(',')) {
console.log('------------');
console.log(locales[locale].name);
try {
const { message, image } = await (await fetch(`${locales[locale].url}/api/calendar/today`)).json();
console.log('<<<', message, '>>>');
if (!message) {
continue;
}
fs.writeFileSync(imageTmpPath, Buffer.from(await (await fetch(image)).arrayBuffer()), { encoding: 'binary' });
let imageStream = null;
try {
imageStream = fs.createReadStream(imageTmpPath);
} catch {}
for (const publisher of process.argv[3].split(',')) {
if (!publisher) {
continue;
}
console.log(`Publishing: ${publisher}`);
const postId = await publishers[publisher](
message,
imageStream,
rootPostId[publisher],
lastPostId[publisher],
locale,
);
console.log(postId);
if (!rootPostId[publisher]) {
rootPostId[publisher] = postId;
}
lastPostId[publisher] = postId;
}
} catch (error) {
Sentry.captureException(error);
}
}
})();