Skip to content

Instantly share code, notes, and snippets.

@ExtraConcentratedJuice
Last active October 16, 2020 18:13
Show Gist options
  • Save ExtraConcentratedJuice/bbb60839f249e7c68a15336b27ebef00 to your computer and use it in GitHub Desktop.
Save ExtraConcentratedJuice/bbb60839f249e7c68a15336b27ebef00 to your computer and use it in GitHub Desktop.
giveaway bot in js
const Discord = require("discord.js");
const fs = require('fs');
const schedule = require('node-schedule');
const jsonfile = require('jsonfile');
const sqlite3 = require('sqlite3').verbose();
const config = require("./config.json");
const db = new sqlite3.Database('./data/data.db');
db.serialize(function() {
db.run("CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY, url TEXT)");
db.run("CREATE TABLE IF NOT EXISTS entries(id INTEGER PRIMARY KEY)");
db.run("CREATE TABLE IF NOT EXISTS giveaways(id INTEGER PRIMARY KEY, msgid INTEGER)");
});
function insert_user(id) {
var stmt = db.prepare('INSERT INTO entries VALUES (?)');
stmt.run(id)
stmt.finalize();
}
function insert_giveaway(id) {
var stmt = db.prepare('INSERT INTO giveaways (msgid) VALUES (?)');
stmt.run(id)
stmt.finalize();
}
function insert_tradeurl(id, tradeurl) {
var stmt = db.prepare('INSERT INTO users VALUES (?, ?)');
stmt.run(id, tradeurl);
stmt.finalize();
}
function update_tradeurl(id, tradeurl) {
var stmt = db.prepare('UPDATE users SET url = ? WHERE id = ?');
stmt.run(tradeurl, id);
stmt.finalize();
}
function clear_entries() {
db.run('DELETE FROM entries');
}
function send_prize(url) {
return true;
// DO STEAM STUFF HERE!
// RETURN FALSE OR TRUE SO THAT WE KNOW
// IF THE TRADE WAS A SUCCESS. IF NOT, IT
// WILL SEND A MESSAGE TO THE USER TELLING THEM SO.
}
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
console.log(`Ready to serve in ${client.channels.size} channels on ${client.guilds.size} servers, for a total of ${client.users.size} users.`);
// This ensures that our latest giveaway message is cached in the event of a bot restart.
// Uncached messages do not make the 'on reaction' event fire, and the giveaway message is uncached on restart.
latest_giveaway(function(msgid) {
console.log('Resuming giveaway ID #' + msgid);
client.channels.get(config.channel_id).fetchMessage(msgid);
});
});
client.on('messageReactionAdd', (reaction, user) => {
if (user.bot) {
return;
}
if (reaction.message.channel.id != config.channel_id) {
return;
}
if (reaction.emoji.name != "✅") {
return;
}
latest_giveaway(function(msgid) {
if (reaction.message.id != msgid) {
return;
}
db.get("SELECT * FROM entries WHERE id = ?", user.id, function(err, row) {
user_exists(user.id, function(user_exists) {
// Check if user exists in url table
if (!user_exists) {
user.send("Maybe you should register a tradeurl first. ``g>tradeurl <url>``");
return;
}
// Enter giveaway if row does not exist
if (!row) {
insert_user(user.id);
user.send("You've successfully entered the giveaway.");
}
});
});
});
});
client.on('message', msg => {
if (msg.author.bot) {
return;
}
if (msg.content.indexOf(config.prefix) !== 0) return;
const args = msg.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command == 'seturl') {
var invalid_args_embed = new Discord.RichEmbed()
.setTitle("Invalid arguments/trade URL!")
.setImage('https://i.imgur.com/PccU0kB.jpg')
.setDescription("Correct usage: ``g>seturl <your url here>``\nPlease enter a valid trade URL!\n\nYou can find your trade URL here: http://steamcommunity.com/id/me/tradeoffers/privacy#trade_offer_access_url")
.setColor(0x00FFFF);
if (args.length == 0) {
msg.author.send(invalid_args_embed);
return;
}
var tradeurl = args[0];
var match = tradeurl.startsWith('https://');
if (!match) {
msg.author.send(invalid_args_embed);
} else {
var embed = new Discord.RichEmbed()
.setTitle('Your trade URL has been successfully set.')
.setDescription('Your trade URL has been set!\nNow you can enter giveaways.')
.setColor(0x00FFFF);
db.get("SELECT * FROM users WHERE id = ?", msg.author.id, function(err, row) {
if (row) {
update_tradeurl(msg.author.id, tradeurl);
embed.setTitle('Your trade URL has been successfully updated.');
embed.setDescription(`It has been set to: ${tradeurl}.`);
msg.author.send(embed);
} else {
insert_tradeurl(msg.author.id, tradeurl);
msg.author.send(embed);
}
});
}
}
if (command == 'info') {
var embed = new Discord.RichEmbed()
.setTitle(`Bot Information`)
.addField('Library', 'discord.js')
.addField('Author', 'Maze')
.addField('Description', 'Maze is bad at coding so I am a bad bot.')
msg.channel.send(embed);
}
});
var j = schedule.scheduleJob('*/5 * * * * *', function() {
console.log('Job fired. Next giveaway beginning.');
// Don't worry about this - it just selects at random for you.
// var winner is the winner's ID; winner is null if no entrants.
select_winner(function(winner) {
if (!winner) {
var embed = new Discord.RichEmbed()
.setTitle("Nobody entered...")
.setImage("https://i.imgur.com/GM2eXY5.gif")
.setDescription('It seems that nobody entered the giveaway. Oh well.')
client.channels.get(config.channel_id).send(embed);
} else {
var embed = new Discord.RichEmbed()
.setTitle("Daily Giveaway Results")
.setImage("https://i.imgur.com/vX9WPTJ.png")
.setDescription(`The winner of daily giveaway is <@${winner}>!\nA new giveaway is beginning shortly.`)
client.channels.get(config.channel_id).send(embed);
// Gets url, sends prize to winner.
get_url(winner, function(url) {
var embed = new Discord.RichEmbed()
.setTitle("You won!")
.setDescription(`Congratulations, you won!\nI am sending a trade to the tradeurl: ${url}.`)
client.fetchUser(winner).then((User) => {
User.send(embed);
});
// CHECK ABOVE FOR send_prize FUNCTION. FILL IT IN.
if (!send_prize(url)) {
// Add something here to handle if the tradeurl was invalid.
client.fetchUser(winner).then((User) => {
User.send("You entered an invalid trade url. Tough luck.");
});
}
});
}
});
clear_entries();
setTimeout(function() {
var embed = new Discord.RichEmbed()
.setTitle("Daily Giveaway")
.setDescription(`Every 24 hours a random amount of items is given to a lucky winner.\n**Items can be Rare or Premium quality!**\nTo enter the giveaway please react with ✅ to this message!\n(If the bot DMs you, you are entered. If not, something is wrong. You cannot back out once you enter.)`)
client.channels.get(config.channel_id).send(embed).then((m) => {
m.react("✅");
insert_giveaway(m.id);
});
}, 3000);
});
// Callbacks
function latest_giveaway(callback) {
db.get("SELECT CAST(msgid AS TEXT) AS msgid FROM giveaways WHERE id = (SELECT MAX(id) FROM giveaways);", function(err, row) {
if (row) {
callback(row.msgid);
} else {
callback(null);
}
});
}
function user_exists(id, callback) {
db.get("SELECT * FROM users WHERE id = ?", id, function(err, row) {
var exists = false;
if (row) {
exists = true;
}
callback(exists);
});
}
function get_url(id, callback) {
db.get("SELECT * FROM users WHERE id = ?", id, function(err, row) {
if (!row) {
callback(null);
} else {
callback(row.url);
}
});
}
function select_winner(callback) {
// I hate Javascript. Why can't it handle big integers? REEEEEEEE
// AND THE CALLBACKS KILL ME
db.get("SELECT CAST(id AS TEXT) AS id FROM entries ORDER BY RANDOM() LIMIT 1;", function(err, row) {
if (row) {
callback(row.id);
} else {
callback(null);
}
});
}
client.login(config.token);
{
"token" : "ur token here",
"prefix" : "g>",
"channel_id" : "ur giveaway channel here"
}
@jonas-ell
Copy link

It works?

Copy link

ghost commented Jan 12, 2020

It works?

nah

@misty0123
Copy link

whats the commands

@misty0123
Copy link

please tell me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment