Giter VIP home page Giter VIP logo

trialbot's Introduction

Contributors Forks Stargazers Issues


Logo

TrialBot

A bot that allows you to give roles to users on your Discord server for a certain amount of time.

Explore the docs »

My Discord · Report Bug · Request Feature · My Website

About The Project

This is a bot that allows you to grant users temporary access to different roles in your Discord servers. The bot is very helpful for server owners who have roles that allow different channels based on certain subscriptions or packages the users pay for. I would highly recommend checking out my website where I dive in deep to how the bot works, what all it does, and even share some walkthrough videos of it in action. Thanks for stopping by and reach out to me on Discord if you'd like to connect!

(back to top)

Use Cases - Running TrialBot

Manual Operations

  • Adding a role for a set amount of time /add @user @role (amount of time) (minutes/hours/days)
    • You can use the /add slash command to easily add a a role temporarily to a user in your server. This command must be run from a guild, and takes
    • Note - if the user already has an expiration date for that role in the future, this will extend that date

Automatic Operations

  • The bot will check for users roles that have expired every hour and remove them.

More functionality (coming soon)

  • You can designate the bot to automatically assign a role to users upon them joining your server for a set amount of time.
    • example: You have used the bots /set-role-on-join command for "My cool Role" to be added when new users join the guild and the time for the role to be one hour. Jim then joins your server and the bot grants him the role named "My cool Role". After one hour, the role "My cool Role" is automatically removed from Jim.
  • You can designate the bot to automatically assign a role to a user for a certain time period.
    • example: You have used the bots /set-role-for-period command to assign the role "My cool Role" to Jim for an event weekend. The dates of the weekend are September 3rd at noon until September 5th at midnight. The bot will automatically assign the role on September 3rd at noon and remove the role on September 5th at midnight.

Installing

  • requirements :

    • node v16.11.1
  • example install :

  • To start regular sync bot

    • node register.js (this registers the /add command for your bot)
    • node trialbot-lowdb.js

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

(back to top)

trialbot's People

Contributors

bababoi2222 avatar jonathonor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

trialbot's Issues

Some codes need to updates

I fixed and you can update your repo, and add Discord.js in package.json. Thanks.

Working codes;
`/*
expireBot, a super simple bot that gives you the ability to give a user a role for a
certain number of days, after the time is reached, the role is removed.
*/
var mysql = require('promise-mysql');
var schedule = require('node-schedule');

const Discord = require('discord.js');
const client = new Discord.Client();
var config = require('./config.json');
var pool = mysql.createPool({
connectionLimit: 100, //important
host: config.dbHost,
user: config.dbUsername,
password: config.dbPassword,
database: config.dbName,
debug: false
});
var connection;

client.on('ready', () => {
console.log('expireBot started.');
mysql.createConnection({
host: config.dbHost,
user: config.dbUsername,
password: config.dbPassword
}).then(conn => {
connection = conn;
return connection.query('SHOW DATABASES LIKE ?;', config.dbName);
}).then(rows => {
if (!rows[0]) {
console.log('database does not exist')
}
});
});

client.on('message', msg => {
if (msg.content.startsWith('!role')) {
if (verifyUser(msg.author.id)) {
let member = msg.mentions.members.first();
let role = msg.mentions.roles.first().id;
let days = parseInt(msg.content.split(" ")[3]);
if (Number.isInteger(days)) {
addRole(member, role, days);
} else {
const guild = client.guilds.cache.find(guild => guild.id === config.serverId);
const logChannel = guild.channels.cache.find(channel => channel.id === config.logChannelId);
logChannel.send(days + ' is not a valid number.');
}
}
}
});

addRole = (member, roleId, amountOfDays) => {
const guild = client.guilds.cache.find(guild => guild.id === config.serverId);
const logChannel = guild.channels.cache.find(channel => channel.id === config.logChannelId);
const roleToAdd = guild.roles.cache.find(r => r.id === roleId);
let checkSql = 'SELECT expires FROM users WHERE id = ? AND role = ?';
let checkParams = [member.user.id, roleId];
pool.getConnection().then(connection => {
connection.query(checkSql, checkParams).then(rows => {
connection.release();
if (rows[0]) {
let dateToAddTo = new Date(rows[0].expires);
updateExpirationDate(member.user.id, roleId, amountOfDays, dateToAddTo);
logChannel.send('Added ' + amountOfDays + ' days to ' + member.user.username + '\s subscription.');
} else {
insertMemberIntoDb(member.user.id, roleId, amountOfDays)
member.roles.add(roleToAdd).catch(err => console.log(err));
logChannel.send('Added "' + roleToAdd.name + '" role and ' + amountOfDays + ' days to ' + member.user.username + '\s subscription.');
}
});
});
}

updateExpirationDate = (memberId, roleId, amountOfDays, dateToAddTo) => {
let updateSql = 'UPDATE users SET expires = ? WHERE id = ? AND role = ?';
let expireDate = addDays(amountOfDays, dateToAddTo);
let updateParams = [expireDate, memberId, roleId];
pool.getConnection().then(connection => {
connection.query(updateSql, updateParams).then(rows => {
connection.release();
});
});
}

insertMemberIntoDb = (memberId, roleId, amountOfDays) => {
let insertSql = 'INSERT INTO users (id, role, expires) VALUES (?, ?, ?);';
let expireDate = addDays(amountOfDays);
let insertParams = [memberId, roleId, expireDate];
pool.getConnection().then(connection => {
connection.query(insertSql, insertParams).then(rows => {
connection.release();
});
});
}

addDays = (days, date) => {
var result = date ? new Date(date) : new Date();
result.setDate(result.getDate() + days);
return result;
}

verifyUser = (id) => {
const guild = client.guilds.cache.find(guild => guild.id === config.serverId);
let member = guild.members.cache.find(member => member.id === id);

return member.roles.cache.find(role => role.name === config.commanderRole);

}

removeRoles = () => {
let guild = client.guilds.cache.find(guild => guild.id === config.serverId);
let rowsToRemoveSql = 'SELECT * FROM users WHERE expires < CURRENT_TIMESTAMP()';
let logChannel = guild.channels.cache.find(channel => channel.id === config.logChannelId);

pool.getConnection().then(connection => {
    connection.query(rowsToRemoveSql).then(rows => {
        connection.release();
        if (rows.length > 0) {
            rows.forEach(row => {
                let guild = client.guilds.cache.find(guild => guild.id === config.serverId);
                let role = guild.roles.cache.find(r => r.id === row.role);
                let member = guild.members.cache.find(mem => mem.id === row.id);
                member.removeRole(role);
                logChannel.send('Removed "' + role.name + '" from ' + member.user.username);
            });
        }
    });
});

}

deleteExpiredUsers = () => {
let removeSql = 'DELETE FROM users WHERE expires < CURRENT_TIMESTAMP()';
pool.getConnection().then(connection => {
connection.query(removeSql).then(() => {
connection.release();
});
});

}

schedule.scheduleJob('0 */8 * * *', () => {
removeRoles();
deleteExpiredUsers();
});

client.login(config.token);`

i got an error after i type node register.js

]
}
PS C:\Users\PC\OneDrive\Masaüstü\TimerBot\trialbot> node register.js
Started refreshing application (/) commands.
(node:7604) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time
(Use node --trace-warnings ... to show where the warning was created)
DiscordAPIError[0]: 404: Not Found
at handleErrors (file:///C:/Users/PC/OneDrive/Masa%C3%BCst%C3%BC/TimerBot/trialbot/node_modules/@discordjs/rest/dist/index.mjs:588:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.runRequest (file:///C:/Users/PC/OneDrive/Masa%C3%BCst%C3%BC/TimerBot/trialbot/node_modules/@discordjs/rest/dist/index.mjs:969:23)
at async SequentialHandler.queueRequest (file:///C:/Users/PC/OneDrive/Masa%C3%BCst%C3%BC/TimerBot/trialbot/node_modules/@discordjs/rest/dist/index.mjs:810:14)
at async REST.request (file:///C:/Users/PC/OneDrive/Masa%C3%BCst%C3%BC/TimerBot/trialbot/node_modules/@discordjs/rest/dist/index.mjs:1335:22)
at async file:///C:/Users/PC/OneDrive/Masa%C3%BCst%C3%BC/TimerBot/trialbot/register.js:40:5 {
requestBody: {
files: undefined,
json: [ [SlashCommandBuilder], [SlashCommandBuilder] ]
},
rawError: { message: '404: Not Found', code: 0 },
code: 0,
status: 404,
method: 'PUT',
url: 'https://discord.com/api/v9/applications/1095615764507148340 / 1095615764507148340/commands'
}
PS C:\Users\PC\OneDrive\Masaüstü\TimerBot\trialbot> node trialbot-lowdb.js
(node:2828) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time
(Use node --trace-warnings ... to show where the warning was created)
C:\Users\PC\OneDrive\Masaüstü\TimerBot\trialbot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:250
throw new DiscordjsError(unrecoverableErrorCodeMap[error.code]);
^

Error [DisallowedIntents]: Privileged intent provided is not enabled or whitelisted.
at WebSocketManager.createShards (C:\Users\PC\OneDrive\Masaüstü\TimerBot\trialbot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:250:15)
at async Client.login (C:\Users\PC\OneDrive\Masaüstü\TimerBot\trialbot\node_modules\discord.js\src\client\Client.js:226:7) {
code: 'DisallowedIntents'
}

trial bot get trail

I have followed the steps.The issue is I have a channel name get-trial, which has a get trial button, it gives error, This interaction failed.

I have followed all the steps but I dont know where to run the add command. I nee it to be behind the get trial button so that everytime a user clicks this button it gives him the role(already created ) for 6 hours.

Morever the plus trial role is in 2nd number because at 1st, admin is pinned and cant be removed.

image

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.