Skip to content

Instantly share code, notes, and snippets.

@apos37
Created August 12, 2022 21:26
Show Gist options
  • Save apos37/379b0b102e6f288c8ab84e7f8035753d to your computer and use it in GitHub Desktop.
Save apos37/379b0b102e6f288c8ab84e7f8035753d to your computer and use it in GitHub Desktop.
Pylon Bot WordPress Stack Exchange Feed
import { commands } from './command_group';
import { STACKEXCHANGE_API_CHANNEL_ID } from './ids';
/**
* KV Namespace
*/
const stackKv = new pylon.KVNamespace('stackexchange');
/**
* Command for listing all items in the KV Namespace
*/
commands.raw('stacklist', async (message) => {
const keys = await stackKv.list();
console.log(keys);
if (keys.includes('407247')) {
console.log('yes');
}
await message.reply(
`The ${keys.length} keys in the stackKv are:\n${keys.join('\n')}`
);
// Delete all except this one
// var omit = '875578052195778570';
// for (let i = 0; i < keys.length; i++) {
// if (keys[i] != omit) {
// stackKv.delete(keys[i]);
// }
// }
});
/**
* Fetch with a command
*/
commands.on(
{
name: 'stack',
description: 'Fetch stackexchange questions',
},
(args) => ({
qty: args.integer(),
}),
async (message, { qty }) => {
fetchStackExchangeQuestions(qty); // how many questions do we want to get?
}
);
// ┌───── Second (0-59)
// │ ┌───── Minute (0-59 or *)
// │ │ ┌───── Hour (0-23 or *)
// │ │ │ ┌───── Day of Month (1-31 or *)
// │ │ │ │ ┌───── Month (1-12, Jan-Dec, or *)
// │ │ │ │ │ ┌───── Day of Week (1-7, Mon-Sun, or *)
// │ │ │ │ │ │ ┌───── Year (optional, default: *)
// │ │ │ │ │ │ │
// * * * * * * *
// Ranges: Every hour from 11AM through 4PM (UTC) on Monday thru Friday: '0 0 11-16 * * Mon-Fri *'
// Lists: Every Monday, Wednesday, and Friday at 12PM (UTC): '0 0 12 * * Mon,Wed,Fri *'
// Intervals: Every 5th minute, starting from minute 0: '0 0/5 * * * * *'
const stackCountCron = '0 0/30 * * * 1-7 *';
pylon.tasks.cron('add_stack_questions', stackCountCron, async () => {
fetchStackExchangeQuestions(5); // how many questions do we want to try to get?
});
// Change the category name to include the number of members
async function fetchStackExchangeQuestions(qty: number) {
const channel = await discord.getGuildTextChannel(
STACKEXCHANGE_API_CHANNEL_ID
);
if (!channel) {
return;
}
const guild = await discord.getGuild(channel.guildId);
if (!guild) {
return;
}
// Options
const pageSize = qty * 10;
const order = 'desc';
const sort = 'creation';
// Stored question ids here for later
var storedKVS: number[] = [];
// Fetch WordPress StackExchange Questions
const _url =
'https://api.stackexchange.com/2.3/questions?pagesize=' +
pageSize +
'&order=' +
order +
'&sort=' +
sort +
'&site=wordpress';
await fetch(_url)
.then(function (response) {
// The API call was successful!
return response.json();
})
.then(async function (jsondata) {
// This is the JSON data
// console.log(jsondata);
// Count how many we are adding
let count = 0;
// Cycle through each question
for (var q = 0; q < pageSize; q++) {
///TODO: filter titles for characters
// This is the question data
const question = jsondata.items[q];
// Question id
const questionId = question.question_id;
// Add to KV array because we're storing how many we fetched, not how many we are posting
storedKVS.push(questionId);
// Skip if the item has already been added to the kv
const stackList = await stackKv.list();
if (stackList.includes(questionId.toString())) {
// console.log(questionId + ' has already been added.');
continue;
}
// Skip if the question is closed
const closed_date = question.closed_date;
if (closed_date && closed_date != '') {
// console.log(questionId + ' is closed.');
continue;
}
// Only log what we are displaying
// console.log(question);
// Continue if the question has not been answered
if (question.is_answered == false && count < qty) {
// Count it
count++;
console.log('Posting ' + count + ' out of ' + qty);
// Only log what we are posting
// console.log(question);
// Date
const timestamp = question.creation_date;
var date = new Date(timestamp * 1000);
var formattedDate = date.toDateString();
// Title
var title = question.title;
title = title
.replaceAll('&amp;', '&')
.replaceAll('&lt;', '<')
.replaceAll('&gt;', '>')
.replaceAll('&quot;', '"')
.replaceAll('&apos;', "'");
// Link
const link = question.link;
// User Name
const displayName = question.owner.display_name;
// User Avatar
const avatar = question.owner.profile_image;
// Tags Array
const tags = question.tags;
// Return it all
var embed = new discord.Embed({
title: `${title}`,
url: link,
description: `**TAGS: ${tags.join(
', '
)}**\n\n\nAsked on ${formattedDate}`,
thumbnail: {
url: avatar,
},
footer: {
text: `By ${displayName} on WordPress StackExchange\nhttps://wordpress.stackexchange.com/`,
},
});
channel.sendMessage({ embed: embed });
}
}
});
// Clear the KV so we can start over
await stackKv.clear();
// Add to KV
for (var kvq = 0; kvq < storedKVS.length; kvq++) {
await stackKv.put(storedKVS[kvq].toString(), 1);
// console.log('Stored question id: ' + storedKVS[kvq].toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment