Skip to content

Instantly share code, notes, and snippets.

@PhantomNimbi
Last active July 5, 2022 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save PhantomNimbi/a1b745948138082db7bfd6c0023c6f99 to your computer and use it in GitHub Desktop.
Save PhantomNimbi/a1b745948138082db7bfd6c0023c6f99 to your computer and use it in GitHub Desktop.
Pylon Reddit Feeds
import * as app from '../config';
let config = {
reddit: {
check_interval: '0 1 15 * * Thu *',
},
slashCommands: discord.interactions.commands,
permissions: {
manage_channels: discord.Permissions.MANAGE_CHANNELS,
},
embeds: {
thumbnail_icon:
'https://raw.githubusercontent.com/NimbiDev/Pylon-Bot/main/.github/assets/reddit.png',
color: discord.decor.RoleColors.BLUE,
},
commands: {
staff: ['test', 'add [subreddit]', 'delete [subreddit]', 'set [channel]'],
info: ['about', 'list'],
},
};
let subreddit_storage = new pylon.KVNamespace('subreddits');
let channel_storage = new pylon.KVNamespace('channels');
let slashCommands = config.slashCommands;
let commands = {
subCommands: {
staff: config.commands.staff,
info: config.commands.info,
},
};
let embeds = {
thumbnail: {
icon: config.embeds.thumbnail_icon,
},
color: {
blue: config.embeds.color,
},
};
let permissions = config.permissions.manage_channels;
let check_interval = config.reddit.check_interval;
let subreddits: string[] = [];
let firstTime = true;
let firstTime2 = true;
let reddit_channel_id = '';
let staff_list = commands.subCommands.staff.toString().replaceAll(',', '\n - ');
let info_list = commands.subCommands.info.toString().replaceAll(',', '\n - ');
async function defaultchannel() {
// @ts-ignore
reddit_channel_id = await channel_storage.get('reddit_channel');
if (reddit_channel_id === undefined)
throw new Error('Please configure your channel.');
firstTime2 = false;
}
async function checkSubreddits() {
subreddits = await subreddit_storage.list();
firstTime = false;
}
async function createSubreddit(name: any) {
let array = name.split(' ');
for (let i of array) {
await subreddit_storage.put(i, []);
}
checkSubreddits();
}
async function deleteSubreddit(name: any) {
let array = name.split(' ');
for (let i of array) {
await subreddit_storage.delete(i);
}
checkSubreddits();
}
async function checkReddit() {
let lists: any = {};
if (firstTime2) await defaultchannel();
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: any) => x.data)
.filter((x: any) => !lists[i].includes(x.id))
)
// @ts-ignore
.then((posts) => Iterator(posts).then(AddToKVS(i, posts, lists[i])));
}
}
async function AddToKVS(key: any, postsw: any, list: any) {
let lista = list;
for (let i of postsw) {
lista.push(i.id);
}
await subreddit_storage.put(key, lista);
}
async function Iterator(posts: any) {
for (let i of posts) {
await sendDiscord(i);
}
}
async function sendDiscord(a: any) {
let self = await discord.getBotUser();
let channel = await discord.getTextChannel(reddit_channel_id);
let post_embed = new discord.Embed()
.setTitle(a.title)
.setDescription(a.selftext)
.setAuthor({
name: a.subreddit,
url: `https://reddit.com${a.permalink}`,
})
.setUrl(a.url)
.setColor(embeds.color.blue)
.setThumbnail({ url: embeds.thumbnail.icon })
.setImage({
url: `${
a.preview != null
? a.preview.images[0].source.url.replace(/&/g, '&')
: ''
}`,
})
.setFields([
{
name: 'Post Author',
value: '```\n' + a.author + '\n```',
inline: true,
},
{
name: 'Post Domain',
value: '```\n' + a.domain + '\n```',
inline: true,
},
])
.setTimestamp(new Date().toISOString())
.setFooter({
text: 'Powered by' + self.username,
iconUrl: self.getAvatarUrl(),
});
await channel?.sendMessage(post_embed);
}
pylon.tasks.cron('checkreddit', check_interval, async () => {
checkReddit();
});
pylon.tasks.cron('clearlist', '0 0 12 * * * *', async () => {
let lists: any = {};
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);
}
}
});
slashCommands.register(
{
name: 'reddit',
description: 'Pylon Reddit System',
options: (opts) => ({
text: opts.string({
name: 'command',
description: 'Command to execute.',
required: true,
choices: ['about', 'list', 'test', 'add', 'delete', 'set'],
}),
second: opts.string({
name: 'subreddit',
description: 'Add or delete subreddit.',
required: false,
}),
channel: opts.guildChannel({
name: 'channel',
description: 'Set channel for feed.',
required: false,
}),
}),
ackBehavior: slashCommands.AckBehavior.AUTO_EPHEMERAL,
},
async (interaction, { text, second, channel }) => {
let self = await discord.getBotUser();
try {
if (text == 'about') {
var reddit_about = new discord.Embed()
.setTitle('Pylon Reddit Feed')
.setDescription(
[
'Reddit feed for Pylon.',
'',
'To use the above commands type: `/reddit [command]`',
'Make sure to replace the `[command]` flag with the specified command.',
].join('\n')
)
.setFields([
{
name: 'Staff Commands',
value: '```\n - ' + staff_list + '\n```',
inline: false,
},
{
name: 'Info Commands',
value: '```\n - ' + info_list + '\n```',
inline: false,
},
])
.setTimestamp(new Date().toISOString())
.setColor(embeds.color.blue)
.setThumbnail({
url: embeds.thumbnail.icon,
})
.setFooter({
text: 'Powered by' + self.username,
iconUrl: self.getAvatarUrl(),
});
await interaction.respond({ embeds: [reddit_about] });
} else if (text == 'test') {
if (!interaction.member.can(permissions))
return await interaction.respondEphemeral(
':x: `Permissions Error` You need the permission **Manage Channels** to use this command.'
);
checkReddit();
await interaction.respondEphemeral('Running Test!');
} else if (text == 'list') {
if (firstTime) await checkSubreddits();
let res = subreddits.toString().replaceAll(',', '\n - ');
let reddit_list = new discord.Embed()
.setTitle('Pylon Reddit Feed')
.setDescription('Here is a list of all subscribed subreddits')
.setFields([
{
name: 'Subreddits',
value: '```\n - ' + res + '\n```',
inline: false,
},
])
.setTimestamp(new Date().toISOString())
.setFooter({
text: 'Powered by' + self.username,
iconUrl: self.getAvatarUrl(),
})
.setColor(embeds.color.blue);
await interaction.respond({ embeds: [reddit_list] }).catch((_) => {
interaction.respondEphemeral(
[
':warning: **__Error Triggered__** :warning:',
'',
'```ts',
`${_}`,
'```',
].join('\n')
);
console.log(
`>> | (${_.code}) ${_.name}: ${_.message} \n------------------------------------------------------------\n${_.stack}`
);
});
} else if (text == 'add' && second !== undefined) {
if (!interaction.member.can(permissions))
return await interaction.respondEphemeral(
':x: `Permissions Error` You need the permission **Manage Channels** to use this command.'
);
await createSubreddit(second).catch((_) => {
interaction.respondEphemeral(
[
':warning: **__Error Triggered__** :warning:',
'',
'```ts',
`${_}`,
'```',
].join('\n')
);
console.log(
// @ts-ignore
`>> | (${_.code}) ${_.name}: ${_.message} \n------------------------------------------------------------\n${_.stack}`
);
});
interaction
.respondEphemeral('Subreddit created successfully.')
.catch((_) => {
interaction.respondEphemeral(
[
':warning: **__Error Triggered__** :warning:',
'',
'```ts',
`${_}`,
'```',
].join('\n')
);
console.log(
`>> | (${_.code}) ${_.name}: ${_.message} \n------------------------------------------------------------\n${_.stack}`
);
});
} else if (text == 'delete' && second !== undefined) {
if (!interaction.member.can(permissions))
return await interaction.respondEphemeral(
':x: `Permissions Error` You need the permission **Manage Channels** to use this command.'
);
await deleteSubreddit(second).catch((_) => {
interaction.respondEphemeral(
[
':warning: **__Error Triggered__** :warning:',
'',
'```ts',
`${_}`,
'```',
].join('\n')
);
console.log(
`>> | (${_.code}) ${_.name}: ${_.message} \n------------------------------------------------------------\n${_.stack}`
);
});
interaction
.respondEphemeral('Subreddit deleted successfully.')
.catch((_) => {
interaction.respondEphemeral(
[
':warning: **__Error Triggered__** :warning:',
'',
'```ts',
`${_}`,
'```',
].join('\n')
);
console.log(
`>> | (${_.code}) ${_.name}: ${_.message} \n------------------------------------------------------------\n${_.stack}`
);
});
} else if (text == 'set' && channel !== undefined) {
if (!interaction.member.can(permissions))
return await interaction.respondEphemeral(
':x: `Permissions Error` You need the permission **Manage Channels** to use this command.'
);
// @ts-ignore
await channel_storage.put('reddit_channel', channel.id);
// @ts-ignore
reddit_channel_id = channel.id;
interaction.respondEphemeral('Channel selected successfully.');
}
} catch (_) {
console.log(
// @ts-ignore
`>> | (${_.code}) ${_.name}: ${_.message} \n------------------------------------------------------------\n${_.stack}`
);
let channel = await discord.getTextChannel(reddit_channel_id);
let embed = new discord.Embed();
embed.setTitle(':warning: Error Triggered :warning:');
embed.setFields([
{
name: 'Error Code',
// @ts-ignore
value: '```ts\n' + _.code + '\n```',
inline: true,
},
{
name: 'Error Name',
// @ts-ignore
value: '```ts\n' + _.name + '\n```',
inline: true,
},
// @ts-ignore
{ name: 'Error Message', value: _.message, inline: false },
{
name: 'Error Stack',
// @ts-ignore
value: ['```ts', `${_.stack}`, '```'].join('\n'),
inline: false,
},
]);
embed.setColor(discord.decor.RoleColors.DARK_RED);
embed.setTimestamp(new Date().toISOString());
embed.setFooter({
text: 'Powered by' + self.username,
iconUrl: self.getAvatarUrl(),
});
await channel?.sendMessage(embed);
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment