Added the chat AI feature (limited) and added Stripe payment integration

This commit is contained in:
ION606
2022-07-08 14:21:09 +03:00
parent 0d3935d5c6
commit 1d30414304
9 changed files with 523 additions and 47 deletions
+7
View File
@@ -1,5 +1,6 @@
const { MongoClient, ServerApiVersion, ConnectionClosedEvent } = require('mongodb');
const { exit } = require('process');
const { checkResponses } = require('./wordlist.js');
async function getResponse(convo, bot) {
@@ -45,6 +46,11 @@ async function convoManager(clientinp, bot, message) {
const doc = docs[0];
if (!doc) { return message.reply('You aren\'t currently in a conversation\nUse _!startconvo_ to start one!'); }
//Checking Section
const check = checkResponses(message.content, "I'm sorry, I can't do that");
if (check != null) { return message.reply(check); }
let convo = doc.convo;
convo += `\nHuman: ${message.content}\n`;;
@@ -62,6 +68,7 @@ async function convoManager(clientinp, bot, message) {
});
}
}
//"Hello! discord_user:"
module.exports = {
name: 'chat',
+175
View File
@@ -0,0 +1,175 @@
/*
-----WEBHOOKS ARE RECIEVED AND MONITORED HERE-----
https://glitch.com/edit/#!/selmer-bot-listener
--------------------------------------------------
*/
const { MongoClient, ServerApiVersion } = require('mongodb');
const { MessageActionRow, MessageSelectMenu } = require('discord.js');
//Called from the dropdown menu
async function createSubscriptionManual(bot, interaction, id, priceID) {
const stripe = bot.stripe;
const mongouri = bot.mongouri;
//Start Error Checking
if (!id) { console.log('....What? How?'); return interaction.editReply("Uh oh, something happened with the Stripe Discord ID check, please contact support!"); }
const client = new MongoClient(mongouri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
new Promise(async function(resolve, reject) {
client.connect(async (err) => {
if (err) { return console.log(err); }
const dbo = client.db('main').collection('authorized');
await dbo.findOne({'discordID': id}).then(async (doc) => {
var userID;
if (doc != undefined) {
client.close();
reject(`An account with the tag <@${id}> already exists!`);
} else {
const stripeUser = await stripe.customers.create({
metadata: { 'discordID': id }
});
userID = stripeUser.id;
//Add to the database (I have to wait for the insertion)
await dbo.insertOne({stripeID: userID, discordID: id, paid: false, startDateUTC: null, tier: 0}).then(() => { client.close(); resolve(userID); });
}
});
});
}).then(async (userID) => {
//Deal with the session
const billingPortalSession = await stripe.billingPortal.sessions.create({
customer: userID,
return_url: "https://linktr.ee/selmerbot",
});
const session = await stripe.checkout.sessions.create(
{
payment_method_types: ["card"],
line_items: [
{
price: priceID,
quantity: 1,
},
],
customer: userID,
mode: "subscription",
success_url: billingPortalSession.url,
cancel_url: "https://linktr.ee/selmerbot"
});
interaction.editReply(session.url);
}).catch((err) => { interaction.editReply(err); })
}
async function changeSubscriptionManual(bot, message) {
const stripe = bot.stripe;
const mongouri = bot.mongouri;
const id = message.author.id;
//Start Error Checking
if (!id) { return console.log('....What? How?'); }
const client = new MongoClient(mongouri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
new Promise(async function(resolve, reject) {
client.connect(async (err) => {
if (err) { return console.log(err); }
const dbo = client.db('main').collection('authorized');
await dbo.findOne({'discordID': id}).then(async (doc) => {
var userID;
if (doc != undefined) {
userID = doc.stripeID;
client.close();
resolve(userID);
} else {
client.close();
reject(`No user with the ID of <@${message.author.id}>`);
}
});
});
}).then(async (userID) => {
const session = await stripe.billingPortal.sessions.create({
customer: userID,
return_url: "https://linktr.ee/selmerbot",
});
message.reply(session.url);
// console.log(session.url);
}).catch((err) => {
message.reply(err);
// console.log(err);
});
}
function createDropDown(bot, message) {
// const stripe = bot.stripe;
const stripe = bot.stripe;
const pl = [];
const vl = [];
stripe.products.list({
limit: 3,
}).then((prod) => {
prod.data.forEach((obj) => {
const pricePromise = stripe.prices.retrieve(obj.default_price);
var newObj = {label: obj.name, description: null, value: `${obj.default_price}`}
pl.push(pricePromise);
vl.push(newObj);
});
let n = Promise.all(pl);
let i = 0;
n.then((t) => {
t.forEach(data => {
let price = data.unit_amount/100;
vl[i].description = `The $${price} tier`;
i++;
});
const row = new MessageActionRow()
.addComponents(
new MessageSelectMenu()
.setCustomId(`${message.author.id}|premium`)
.setPlaceholder('Nothing selected')
.addOptions(vl)
);
message.channel.send({ content: `Please choose a tier`, components: [row] });
});
});
}
function handleInp(bot, message) {
if (message.content == '!premium help') {
message.reply('Use _!premium buy_ to get premium or use _!premium manage_ to change or cancel your subscription\n_Disclaimer: Selmer Bot uses Stripe to manage payments. Read more at *https://stripe.com/ *_');
} else if (message.content == '!premium buy') {
createDropDown(bot, message);
} else if (message.content == '!premium manage') {
changeSubscriptionManual(bot, message)
}
}
module.exports = {
name: 'premium',
description: 'everything payment',
execute(message, args, Discord, Client, bot) {
message.reply("Please DM Selmer bot to use this command!");
}, handleInp, createSubscriptionManual
}
+34
View File
@@ -0,0 +1,34 @@
//Remember to strip all non-alpha chars from string (including ' )
wordlist = {
pay: ['pay me', 'give me money', 'send money', 'send me money', 'send cash', 'PayPal me', 'venmo me', 'cashapp me', 'cash app me'],
name: ['what is your name', 'whats your name', 'what are you called']
}
function checkResponses(convoOG, answer) {
if (answer.indexOf("I'm sorry, I can't do that") == -1) { console.log('what?'); return 'none'}
// remove all uneccesary chars
convo = convoOG.replace(/\W/g, ' ').toLowerCase();
var b = 'none';
wordlist.name.forEach((w) => { if (convo.includes(w)) { b = 'name'; return }})
wordlist.pay.forEach((w) => { if (convo.includes(w)) { b = 'pay'; return }})
if (b === 'pay') {
//Exctract the number
var amt = convoOG.match(/(\d+)/)[0];
if (matches) {
currency = convoOG[convoOG.indexOf(amt) - 1];
//Do something with pay API to get the amount here
}
} else if (b == 'name') {
return 'My name is Selmer Bot!';
} else { return null; }
return b;
}
module.exports = { checkResponses }
+60
View File
@@ -0,0 +1,60 @@
// EVERYTHING IN THIS FILE SHOULD BE ABLE TO RUN INDEPENDANTLY OF THE BOT
const Stripe = require('stripe');
const APIKey = process.env.APIKey // require('./config.json').APIKey;
const stripe = Stripe(APIKey);
const mongouri = process.env.APIKey // require('./config.json').mongooseURI;
const { MongoClient, ServerApiVersion } = require('mongodb');
function cleardb(db) {
//Triggers about a week before the end of the month and clears out all the "spam" entries
const client = new MongoClient(mongouri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
new Promise(async function(resolve, reject) {
client.connect(async (err) => {
const dbo = client.db('main').collection(db);
dbo.find({paid: false, tier: 0}).toArray((err, docs) => {
if (err) { return console.log(err); }
if (docs[0] != undefined) {
//Add them all to an array and resolve because deleting in a find() causes cyclic dependancies
resolve(docs);
} else {
reject();
}
});
});
}).then((docs) => {
const dbo = client.db('main').collection(db);
const d = new Date().toUTCString();
//Keep track of what was collected (chack later?)
var newObj = {db: db, date: d, count: 0, results: []};
docs.forEach(i => {
//{discord id, stripe id}
newObj.results.push({did: i.discordID, sid: i.stripeID});
newObj.count ++;
try {
//For some reason, these aren't deleted in Stripe, just archived so they can't do anything new
//See https://stripe.com/docs/api/customers/delete
stripe.customers.del(i.stripeID);
} catch (err) { console.log("err"); }
});
dbo.deleteMany({paid: false, tier: 0});
//Add the newObj to another collection (ordered by date?)
const spam_coll = client.db('main').collection("spam_collection_results");
spam_coll.insertOne(newObj);
}).catch((err) => { console.log('none'); });
client.close();
}
module.exports = { cleardb }
//Does not include the day check, see the "selmer-bot-listener" app for that
+3
View File
@@ -1,4 +1,5 @@
const { convoManager } = require('./API/chat.js');
const { handleInp } = require('./API/stripe');
const { MongoClient, ServerApiVersion, ConnectionClosedEvent } = require('mongodb');
function handle_dm(message, bot) {
@@ -24,6 +25,8 @@ function handle_dm(message, bot) {
});
client.close();
} else if (message.content.indexOf('!premium') != -1) {
handleInp(bot, message);
} else {
return message.reply('UNUSABLE DM COMMAND DETECTED');
}
+16 -3
View File
@@ -1,4 +1,5 @@
const { MongoClient, ServerApiVersion } = require('mongodb');
const { createSubscriptionManual } = require('./API/stripe.js');
async function handle_interaction(interaction, mongouri, turnManager, bot, STATE, items, xp_collection) {
@@ -65,8 +66,7 @@ async function handle_interaction(interaction, mongouri, turnManager, bot, STATE
//Menu Selection
else if (interaction.isSelectMenu()) {
const id = interaction.customId.substring(0, interaction.customId.indexOf('|'))
const command = interaction.customId.substring(interaction.customId.indexOf('|'), interaction.customId.length - interaction.customId.indexOf('|'))
console.log(command);
// const command = interaction.customId.substring(interaction.customId.indexOf('|'), interaction.customId.length - interaction.customId.indexOf('|'))
if (interaction.customId.toLowerCase().indexOf('|heal') != -1) {
const client = new MongoClient(mongouri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
@@ -107,6 +107,16 @@ async function handle_interaction(interaction, mongouri, turnManager, bot, STATE
});
} else if (interaction.customId.toLowerCase().indexOf('|item') != -1) {
} else if (interaction.customId.split('|')[1] == 'premium') {
//Check if the person subscribing and the person clicking are the same (group DM catch)
const user = interaction.customId.split('|')[0];
if (interaction.user.id == user) {
// await interaction.deferReply();
await interaction.update({ content: 'TIER SELECTED PLEASE HOLD', components: [] });
await createSubscriptionManual(bot, interaction, user, interaction.values[0]);
//Handle the interaction here
}
}
//menu else ifs here
@@ -114,4 +124,7 @@ async function handle_interaction(interaction, mongouri, turnManager, bot, STATE
}
module.exports = { handle_interaction }
module.exports = { handle_interaction }
//values: [ 'price_1LI5pzFtuywsbrwdlY1gWMkV' ]
//values: [ 'price_1LIpROFtuywsbrwdmxOb8Baj' ]