Skip to content

Instantly share code, notes, and snippets.

@WiLuX-Source
Last active December 16, 2022 19:20
Show Gist options
  • Save WiLuX-Source/a9193d79f6649a64ca890ccc8be80ef5 to your computer and use it in GitHub Desktop.
Save WiLuX-Source/a9193d79f6649a64ca890ccc8be80ef5 to your computer and use it in GitHub Desktop.
Pylon Epic Freebie Feed Script
// @ts-nocheck
// Don't forget to give me a star to support!
// Don't forget to change the permissions for slash-commands through your server!
// Don't forget to give credit if you decide to make something from this!
// Don't forget to check about command to learn how to use it!
// /epic command only works for your started commands instance and can only be used once.
// Disclaimer: None of the devs take responsibility.
// Code By WiLuX-Source
// Embed Styling & Sub-Command System By PhantomNimbi
class epic_freebie_instance {
embed = {
footer_text: 'Powered by Pylon',
footer_icon: 'https://i.imgur.com/2QOYggo.png',
thumbnail_icon:
'https://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Epic_Games_logo.svg/1764px-Epic_Games_logo.svg.png',
};
firsttime = true;
command = discord.interactions.commands;
channel_storage = new pylon.KVNamespace('channels');
staff_commands = ['test', 'set [channel]'];
info_commands = ['about'];
permission = discord.Permissions.MANAGE_CHANNELS;
interval: string | undefined;
constructor(
config = {
localization: '',
interval: '0 5 15 * * Thu *',
cron_name: 'epic_freebie_cron',
channel: null,
}
) {
this.interval = config.interval;
this.channel = config.channel;
this.localization = config.localization;
this.cron_name = config.cron_name;
this.crontask(config.cron_name);
}
async checkepic() {
await fetch(
`https://store-site-backend-static-ipv4.ak.epicgames.com/freeGamesPromotions${
this.localization == ''
? ''
: '?locale=' +
this.localization.toLowerCase() +
'&country=' +
this.localization.toUpperCase()
}`
)
.then((res) => res.json())
.then((res) =>
res.data.Catalog.searchStore.elements
.map((x) => {
return {
title: x.title,
url: `${
x.productSlug == null
? x.catalogNs.mappings[0].pageSlug
: x.productSlug
}`,
seller: x.seller.name,
image:
x.keyImages.find((a) => a.type == 'OfferImageWide')?.url ||
x.keyImages.find((a) => a.type == 'DieselStoreFrontWide')?.url,
price: x.price.totalPrice.fmtPrice.originalPrice,
discountprice: x.price.totalPrice.discountPrice,
type: x.categories[0].path,
description: x.description,
dates: x.promotions,
};
})
.filter((x) => x.dates !== null)
.filter((x) => x.dates.promotionalOffers.length !== 0)
.filter((x) => x.discountprice === 0)
)
.then((x) => this.postepic(x));
}
async postepic(games) {
if (this.firsttime) await this.defaultchannel();
let channel = await discord.getTextChannel(this.channel);
let embed = new discord.Embed();
for (let i of games) {
embed.setAuthor({
name: `${
i.type === 'freegames'
? 'New weekly freebie is available!'
: 'New vault freebie is available!'
}`,
});
embed.setTitle(i.title);
embed.setUrl(`https://store.epicgames.com/p/${i.url}`);
embed.setDescription(i.description);
embed.setFields([
{
name: 'Publisher',
value: '```\n' + i.seller + '\n```',
inline: true,
},
{ name: 'Price', value: '```\n' + i.price + '\n```', inline: true },
{
name: 'Expiry',
value: `<t:${Math.floor(
new Date(
i.dates.promotionalOffers[0].promotionalOffers[0].endDate
).getTime() / 1000
)}>`,
inline: false,
},
]);
embed.setImage({ url: i.image });
embed.setThumbnail({ url: this.embed.thumbnail_icon });
channel?.sendMessage({ content: '', embed: embed }); // ping a certain role
}
}
async crontask(cron) {
pylon.tasks.cron(cron, this.interval, () => {
this.checkepic();
});
}
async defaultchannel() {
if (this.channel == null)
this.channel = await this.channel_storage.get('epic_channel');
if (this.channel == undefined)
throw new Error('Please configure your channel.');
this.firsttime = false;
}
startCommands() {
this.command.register(
{
name: 'epic',
description: 'Pylon Epic Feed',
options: (opts) => ({
command: opts.string({
name: 'command',
description: 'Command to execute.',
required: true,
choices: ['about', 'test', 'set'],
}),
channel: opts.guildChannel({
name: 'channel',
description: 'Set channel for feed.',
required: false,
}),
}),
ackBehavior: this.command.AckBehavior.AUTO_EPHEMERAL,
},
async (interaction, { command, channel }) => {
try {
if (command == 'about') {
let staff_list = this.staff_commands
.toString()
.replaceAll(',', '\n - ');
let info_list = this.info_commands
.toString()
.replaceAll(',', '\n - ');
let embed = new discord.Embed();
embed.setTitle('Pylon Epic Feed');
embed.setDescription(
[
'Epic Feed commands for Pylon.',
'',
'To use the above commands type: `/epic [command]`',
'Make sure to replace the `[command]` flag with the specified command.',
'',
'***Made by [WiLuX](https://github.com/WiLuX-Source) & [PhantomNimbi](https://github.com/PhantomNimbi)***',
].join('\n')
);
embed.setFields([
{
name: 'Staff Commands',
value: '```\n - ' + staff_list + '\n```',
inline: false,
},
{
name: 'Info Commands',
value: '```\n - ' + info_list + '\n```',
inline: false,
},
]);
embed.setTimestamp(new Date().toISOString());
embed.setThumbnail({ url: this.embed.thumbnail_icon });
embed.setFooter({
text: this.embed.footer_text,
iconUrl: this.embed.footer_icon,
});
await interaction.respond({ embeds: [embed] });
} else if (command == 'test') {
if (!interaction.member.can(this.permission))
return await interaction.respondEphemeral(
':x: `Permissions Error` You need the permission **Manage Channels** to use this command.'
);
try {
await this.checkepic();
await interaction.respondEphemeral('Running Test!');
} catch (err) {
console.log(err);
await interaction.respond(
':warning: **__Error Triggered__** :warning:\n[```ts\n' +
err +
'\n```]'
);
}
} else if (command == 'set' && channel !== undefined) {
if (!interaction.member.can(this.permission))
return await interaction.respondEphemeral(
':x: `Permissions Error` You need the permission **Manage Channels** to use this command.'
);
await this.channel_storage.put('epic_channel', channel.id);
this.channel = channel.id;
interaction.respondEphemeral('Channel selected successfully.');
}
} catch (_) {
console.log(
`>> | (${_.code}) ${_.name}: ${_.message} \n------------------------------------------------------------\n${_.stack}`
);
let channel = await discord.getTextChannel(this.channel);
let embed = new discord.Embed();
embed.setTitle(':warning: Error Triggered :warning:');
embed.setFields([
{
name: 'Error Code',
value: '```ts\n' + _.code + '\n```',
inline: true,
},
{
name: 'Error Name',
value: '```ts\n' + _.name + '\n```',
inline: true,
},
{ name: 'Error Message', value: _.message, inline: false },
{
name: 'Error Stack',
value: ['```ts', `${_.stack}`, '```'].join('\n'),
inline: false,
},
]);
embed.setTimestamp(new Date().toISOString());
embed.setFooter({
text: this.embed.footer_text,
iconUrl: this.embed.footer_icon,
});
await channel?.sendMessage(embed);
}
}
);
}
}
new epic_freebie_instance({
localization: '', // localization of your country don't work for every country so please test.
interval: '0 6 15 * * * *', // Pylon don't allow dynamic intervals so you gotta write your own I left a list below to choose yours.
cron_name: 'epic_freebie_cron', // Change name if you are planning to use this in more than one channel.
channel: null, // Leave it null if you want to use the saved channel from the KVDatabase.
}).startCommands(); // call it with startCommands() if you want to use the embedded command system for that specific instance.
/*
Every Interval settings you will ever need:
0 5 15 * * * * - Every day vault games but with daylight change five to six if you want other.
0 5 15 * * Thu * - Every Thursday regularly check freebies same thing also applies to it.
Pylon has limitations this was the best result I could achieve you can always send a pr for improvement.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment