Skip to content

Instantly share code, notes, and snippets.

@trueharuu
Last active June 27, 2022 04:32
Show Gist options
  • Save trueharuu/e1cc8f1f02269cd76ba0daad87bc99cd to your computer and use it in GitHub Desktop.
Save trueharuu/e1cc8f1f02269cd76ba0daad87bc99cd to your computer and use it in GitHub Desktop.
Pylon Reddit System
import * as config from '../modules/config';
const content = "sex!"
const group = config.CLIENT.INTERACTION_COMMANDS;
const subreddit_storage = new pylon.KVNamespace('subreddits');
let subreddits = [];
let firstTime = true;
const interval = config.REDDIT.INTERVAL;
const channel_id = config.CHANNEL.REDDIT;
const REDDIT_COMMAND = config.CLIENT.INTERACTION_COMMANDS;
async function checkSubreddits() {
subreddits = await subreddit_storage.list();
firstTime = false;
}
async function createSubreddit(name) {
let array = name.split(' ');
for (let i of array) {
await subreddit_storage.put(i, []);
}
checkSubreddits();
}
async function deleteSubreddit(name) {
let array = name.split(' ');
for (let i of array) {
await subreddit_storage.delete(i);
}
checkSubreddits();
}
async function checkReddit() {
let lists = {};
if (firstTime) await checkSubreddits();
for (let i in subreddits) {
lists[subreddits[i]] = await subreddit_storage.get(subreddits[i]);
}
for (let i of subreddits) {
await fetch(`https://www.reddit.com/r/${i}/new.json?limit=10`)
.then((res) => res.json())
.then((res) =>
res.data.children
.map((x) => x.data)
.filter((x) => !lists[i].includes(x.id))
)
.then((posts) => Iterator(posts).then(AddToKVS(i, posts, lists[i])));
}
}
async function AddToKVS(key, postsw, list) {
let lista = list;
for (let i of postsw) {
lista.push(i.id);
}
await subreddit_storage.put(key, lista);
}
async function Iterator(posts) {
for (let i of posts) {
await sendDiscord(i);
}
}
async function sendDiscord(a) {
let channel = await discord.getTextChannel(channel_id);
await channel?.sendMessage(
{
content,
embed: new discord.Embed({
title: a.title,
color: config.COLOR.BLUE,
url: a.url,
author: {
name: `New post on ${a.subreddit}`,
url: `https://reddit.com${a.permalink}`,
},
description: a.selftext,
image: {
url: `${
a.preview != null
? a.preview.images[0].source.url.replace(/&/g, '&')
: ''
}`,
},
thumbnail: {
url: config.IMAGES.REDDIT,
},
fields: [
{
name: 'Post Author',
value: a.author,
inline: true,
},
{
name: 'Post Domain',
value: a.domain,
inline: true,
},
],
footer: {
text: config.FOOTER.TEXT,
iconUrl: config.FOOTER.ICON,
},
timestamp: new Date(a.created * 1000).toISOString(),
})
}
);
}
pylon.tasks.cron('checkreddit', interval, async () => {
checkReddit();
});
pylon.tasks.cron('clearlist', '0 0 12 * * * *', async () => {
let lists = {};
for (let i in subreddits) {
lists[subreddits[i]] = await subreddit_storage.get(subreddits[i]);
if (lists[subreddits[i]].length >= 100) {
let newlist = lists[subreddits[i]].slice(-20);
await subreddit_storage.put(subreddits[i], newlist);
}
}
});
group.register(
{
name: 'reddit',
description: 'Pylon Reddit System',
options: (opts) => ({
text: opts.string({
name: 'command',
description: 'command to run',
required: true,
choices: ['about', 'list', 'test', 'add', 'delete'],
}),
second: opts.string({
name: 'subreddit',
description: 'add or delete subreddit',
required: false,
}),
}),
ackBehavior: group.AckBehavior.AUTO_EPHEMERAL;
},
async (interaction, { text, second }) => {
if (text == 'about') {
let embed = new discord.Embed()
.setDescription(
[
'**__Pylon Reddit System__**',
'Reddit commands for Pylon.',
'',
'**Staff Commands**',
'',
' - `test`: Test the current reddit feeds.',
' - `add [subreddit]`: Add a subreddit to the reddit feed.',
' - `remove [subreddit]`: Remove a subreddit from the reddit feed.',
'',
'**Info Commands**: ',
'',
' - `about`: Displays this page.',
' - `list`: List the current subreddits in the reddit feeds.',
'',
'To use the above commands type: `/reddit [command]`',
'Make sure to replace the `[command]` flag with the specified command.',
].join('\n')
)
.setTimestamp(new Date().toISOString())
.setColor(config.COLOR.BLUE)
.setThumbnail({
url: config.IMAGES.REDDIT,
})
.setFooter({
text: config.FOOTER.TEXT,
iconUrl: config.FOOTER.ICON,
});
await interaction.respond({ embeds: [embed] });
} else if (text == 'test') {
if (!interaction.member.can(discord.Permissions.MANAGE_CHANNELS))
return await interaction.respondEphemeral(
':x: `Permissions Error` You need the permission **Manage Channels** to use this command.'
);
try {
checkReddit();
await interaction.respond('Running Test!');
} catch (err) {
console.log(err);
await interaction.respond(':warning: **__Error Triggered__** :warning:\n[```ts\n' + err + '\n```]');
}
} else if (text == 'list') {
if (firstTime) await checkSubreddits();
let res = subreddits.toString().replaceAll(',', '\n - ');
let embed = new discord.Embed()
.setDescription(
[
'**__Pylon Reddit System__**',
'',
'**Subreddit List**',
'',
`- ${res}`,
'',
].join('\n')
)
.setTimestamp(new Date().toISOString())
.setFooter({
text: config.FOOTER.TEXT,
iconUrl: config.FOOTER.ICON,
})
.setColor(config.COLOR.BLUE);
await interaction.respond({ embeds: [embed] });
} else if (text == 'add' && second !== undefined) {
await createSubreddit(second);
interaction.respond('subreddit created successfully.');
} else if (text == 'delete' && second !== undefined) {
await deleteSubreddit(second);
interaction.respond('subreddit deleted successfully.');
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment