I'm new to discord bots.
I have a script that gives members a role if the join a VC, that way they can see a Text channel.
I want the channel to be cleared out.
This is what I have so far:
module.exports = (client) => {
// Clears chat?
client.on('messageCreate', async function (message) {
if (message.channel.id === '965002780878176286') { //Bar-Chat
var CheckMinutes = 1, CheckBAR = CheckMinutes * 60 * 1000;
setInterval(function () {
message.channel.messages.fetch({ limit: 100 }).then(function (deleteThese) { message.channel.bulkDelete(deleteThese); })
}, CheckBAR);
};
if (message.channel.id === '965266326828490792') { //Just-Chat
var CheckMinutes = 1, CheckJC = CheckMinutes * 60 * 1000;
setInterval(function () {
message.channel.messages.fetch({ limit: 100 }).then(function (deleteThese) { message.channel.bulkDelete(deleteThese); })
}, CheckJC);
};
if (message.channel.id === '965266431589613618') { //Game-Chat #1
var CheckMinutes = 1, CheckGC1 = CheckMinutes * 60 * 1000;
setInterval(function () {
message.channel.messages.fetch({ limit: 100 }).then(function (deleteThese) { message.channel.bulkDelete(deleteThese); })
}, CheckGC1);
};
if (message.channel.id === '965266551857115156') { //Game-Chat #2
var CheckMinutes = 1, CheckGC2 = CheckMinutes * 60 * 1000;
setInterval(function () {
message.channel.messages.fetch({ limit: 100 }).then(function (deleteThese) { message.channel.bulkDelete(deleteThese); })
}, CheckGC2);
};
if (message.channel.id === '965266660003049472') { //Game-Chat #3
var CheckMinutes = 1, CheckGC3 = CheckMinutes * 60 * 1000;
setInterval(function () {
message.channel.messages.fetch({ limit: 100 }).then(function (deleteThese) { message.channel.bulkDelete(deleteThese); })
}, CheckGC3);
};
});
}
Is there a better way of doing this?
Don't mind the short timer (still testing and don't want to wait like 15/30 mins).
Related
I'm getting memory leak warning in the console for my Electron app, i don't know what to do to increase limit. It's causing it everytime i run the app.
Does the error is linked to uiohook? Or did i miss something here?
How can i use emitter.setMaxListeners() in my case? I have no clue of how to fix it, and hwo to increase the memory leak.
[3452:1014/104426.056:ERROR:service_worker_storage.cc(1904)] Failed to delete the database: Database IO error
(node:21792) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 terminate-timer listeners added to [EventEmitter]. Use emitter.setMaxListeners() to increase limit
(Use `electron --trace-warnings ...` to show where the warning was created)
(node:21792) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 set-activity listeners added to [EventEmitter]. Use emitter.setMaxListeners() to increase limit
Electron
const electron = require('electron');
const BrowserWindow = electron.BrowserWindow;
const dialog = electron.dialog;
const desktopCapturer = electron.desktopCapturer;
const idle = electron.powerMonitor;
const remote = electron.remote;
const notification = electron.Notification;
const globalShortcut = electron.globalShortcut;
const screen = electron.screen;
const ipcMain = electron.ipcMain;
const app = electron.app;
const isDev = require('electron-is-dev');
const path = require('path');
const activeWindows = require('electron-active-window');
const activeWindowPage = require('active-win');
const BMParser = require('bookmark-parser');
const axios = require('axios');
const uiohook = require('uiohook-napi');
const { autoUpdater } = require("electron-updater");
const debug = require('debug')('Franz:ipcApi:autoUpdate');
const dns = require("dns");
const activity = { is_mouse: 0, is_keyboard: 0 };
const headers = {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Origin": "*",
"Accept": "application/json"
}
const sessionUser = null;
let updateInterval = null;
app.disableHardwareAcceleration();
electron.powerSaveBlocker.start('prevent-app-suspension');
//electron.commandLine.appendSwitch ("disable-http-cache");
// Change App Name on Windows
if (process.platform === 'win32')
{
app.setAppUserModelId('Rubii');
}
let apiEndpoint = "http://creaz:81/xorix/api"; // Brian
let frameUrl = 'http://localhost:3000'; // Brian
//if (isDev) { // or if(process.env.NODE_ENV)
// apiEndpoint = "http://creaz:81/xorix/api";
// frameUrl = 'http://localhost:3000';
//}
var internetAvailable = require("internet-available");
let isConnected = false;
let counterInternet = 0;
let allowSendInternetNotification = 1;
async function liveInternetCheck() {
var userSessionCheck = await getSessionUser();
// Most easy way
internetAvailable({
domainName: "rubii.com",
// Provide maximum execution time for the verification
timeout: 10000,
// If it tries 10 times and it fails, then it will throw no internet
retries: 10
}).then(() => {
// Available Internet
isConnected = true;
counterInternet++;
if(counterInternet > 3 && allowSendInternetNotification == 0) {
allowSendInternetNotification = 1;
}
}).catch(() => {
// Not available internet
isConnected = false;
if(isConnected == false && userSessionCheck && allowSendInternetNotification == 1) {
var message = 'Your internet has been disconnected! Please login again';
new notification({ title: 'Ooops', body: message }).show();
// Logout the user in the other end
win.webContents.send("terminate-timer", "hello");
allowSendInternetNotification = 0;
counterInternet = 0;
}
});
}
autoUpdater.on("update-available", (_event, releaseNotes, releaseName) => {
const dialogOpts = {
type: 'info',
buttons: ['Ok'],
title: 'Update Available',
message: process.platform === 'win32' ? releaseNotes : releaseName,
detail: 'A new version download started. The app will be restarted to install the update.'
};
dialog.showMessageBox(dialogOpts);
updateInterval = null;
});
autoUpdater.on("update-downloaded", (_event, releaseNotes, releaseName) => {
const dialogOpts = {
type: 'info',
buttons: ['Restart'],
title: 'Application Update',
message: process.platform === 'win32' ? releaseNotes : releaseName,
detail: 'A new version has been downloaded. Restart the application to apply the updates.'
};
dialog.showMessageBox(dialogOpts).then((returnValue) => {
if (returnValue.response === 0) autoUpdater.quitAndInstall()
});
});
function checkUpdate() {
updateInterval = setInterval(() => autoUpdater.checkForUpdates(), 600000);
}
let win;
ipcMain.on('close-me', (evt, arg) => {
new notification({ title: 'Ooops', body: 'We hope to see you again!' }).show();
app.quit()
});
function determineScreenShotSize() {
var screenSize = screen.getPrimaryDisplay().workAreaSize
return {
width: screenSize.width,
height: screenSize.height
}
}
async function takeScreenshot() {
var user = await getSessionUser();
var timer = await getSessionTimer();
if (user && timer) {
if (timer.timer == 1) {
//console.log('Gathering screens...');
//console.log(app.getPath('pictures'));
const thumbSize = determineScreenShotSize();
const workaroundTimestamp = Date.now();
const options = {
types: ['screen'],
thumbnailSize: { ...thumbSize, workaroundTimestamp }
};
desktopCapturer.getSources(options).then((sources) => {
console.log('Sources received:' + sources.length);
sources.forEach(function (source) {
const sourceName = source.name.toLowerCase();
//console.log(sourceName);
if (['entire screen', 'screen 1'].includes(sourceName)) {
var the_screenshot = source.thumbnail.toPNG();
var data = {
user_id: user.id,
company_id: timer.company_id,
image: the_screenshot.toString('base64')
}
axios.post(apiEndpoint + "/desktop/save_screenshots", data, {
headers: headers
})
.then((response) => {
// console.log(response);
})
.catch((error) => {
//console.log(error);
})
}
})
}).catch(console.error);
}
}
}
function saveSoftware() {
(async () => {
var options = [];
var software = await activeWindowPage();
var user = await getSessionUser();
var timer = await getSessionTimer();
if (user && timer) {
if (timer.timer == 1) {
software.user = user;
software.timer = timer;
axios.post(apiEndpoint + "/desktop/save_app", software, {
headers: headers
})
.then((response) => {
//console.log(response);
})
.catch((error) => {
//console.log(error);
})
}
}
})();
}
function getSessionUser() {
return win.webContents.executeJavaScript('sessionStorage.getItem("user");', true)
.then(result => {
if (result) {
return JSON.parse(result);
}
});
}
function getSessionTimer() {
return win.webContents.executeJavaScript('sessionStorage.getItem("timer");', true)
.then(result => {
if (result) {
return JSON.parse(result);
}
});
}
async function generateActivity() {
win.webContents.send("set-activity", activity);
// We reset after we send it
activity.is_mouse = activity.is_keyboard = 0;
}
function secondsToHms(d) {
d = Number(d);
var h = Math.floor(d / 3600);
var m = Math.floor(d % 3600 / 60);
var s = Math.floor(d % 3600 % 60);
var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
return hDisplay + mDisplay + sDisplay;
}
function createWindow() {
win = new BrowserWindow({
width: 1200,
height: 900,
frame: true,
webPreferences: {
webSecurity: false,
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
backgroundThrottling: false
}
});
//win.loadURL('https://desktop.rubii.com');
win.loadURL(frameUrl, { "extraHeaders": "pragma: no-cache\n" });
// http://localhost:3000
//win.webContents.openDevTools();
//win.removeMenu(); // Brian
// or set the Menu to null
//win.setMenu(null); // Brian
// Reload cache
win.webContents.reloadIgnoringCache();
// Keyboard activity
uiohook.uIOhook.on('keydown', (e) => {
//console.log('Keyboard!')
activity.is_keyboard = 1;
})
// Mouse activity
uiohook.uIOhook.on('mousemove', (e) => {
//console.log('mouse');
activity.is_mouse = 1;
})
// Start listener for keyboard and mouse
uiohook.uIOhook.start();
win.on('close', function () {
win = null;
})
}
app.whenReady().then(createWindow).then(checkUpdate);
app.on('window-all-closed', function () {
app.quit();
});
app.on('activate', function () {
if (win == null) {
createWindow();
}
})
setInterval(takeScreenshot, 10 * 60 * 1000); // 10 minutes
setInterval(saveSoftware, 5 * 1000); // 5 seconds
setInterval(generateActivity, 1 * 1000);
setInterval(function() { liveInternetCheck(); }, 10 * 1000); // 10 seconds
Render
ipcRenderer.on("terminate-timer", function (event, data) {
// Logout if there is no internet connection
handleLogout();
});
// Set activity if there were any keyboard, mouse
ipcRenderer.on("set-activity", function (event, data) {
// If the timer is on
if(timer) {
setActivity(data);
}
});
Help! I'm developing an RPG bot which it needs to detect reactions. But there are two problems:
It only reacts 1 emoji instead of 4
It tries to detect the reaction only once
Here's my code (There are some things which are in portuguese):
if (message.channel.name === "rpg") {
const HP = 0;
const atk = 0;
const def = 0;
const emoji = message.guild.emojis.cache.find(emoji => emoji.name === 'SurvivalManos');
message.react(emoji);
const random = Math.ceil(Math.random() * (3 - 0) + 0);
const rpgembed = new Discord.MessageEmbed()
.setColor('#ffd15e')
.setTitle('RPG')
.setThumbnail('https://cdn.discordapp.com/attachments/732552438283894824/733256439602086019/New_Project_3.png')
.setTimestamp()
.setFooter('Feito por R0dr1G02M4R5 com <3; Desenhos de Kunyk');
if (random == 1) {
const HP = 50;
const atk = 10;
const def = 5;
rpgembed.setDescription('Um slime verde selvagem apareceu!').setImage('https://media.discordapp.net/attachments/696805791319064618/733967904890159134/SPOILER_New_Piskel.png?width=585&height=585').addFields(
{ name: 'HP', value: HP, inline: true },
{ name: 'Atk', value: atk, inline: true },
{ name: 'Def', value: def, inline: true }
);
} else if (random == 2) {
const HP = 100;
const atk = 5;
const def = 10;
rpgembed.setDescription('Um slime vermelho selvagem apareceu!').setImage('https://media.discordapp.net/attachments/696805791319064618/733968480390610955/SPOILER_New_Piskel_1.png?width=585&height=585').addFields(
{ name: 'HP', value: HP, inline: true },
{ name: 'Atk', value: atk, inline: true },
{ name: 'Def', value: def, inline: true }
);
}
else if (random == 3) {
const HP = 25;
const atk = 10;
const def = 10;
rpgembed.setDescription('Um feiticeiro fantasma selvagem apareceu!').setImage('https://media.discordapp.net/attachments/696805791319064618/733968482122727494/SPOILER_New_Piskel_2.png?width=585&height=585').addFields(
{ name: 'HP', value: HP, inline: true },
{ name: 'Atk', value: atk, inline: true },
{ name: 'Def', value: def, inline: true }
);
}
message.channel.send(rpgembed).then(function(message) {
message.react('⚔').then(() => message.react('🛡')).then(() => message.react('🍖')).then(() => message.react('🏃'))
const filter = (reaction, user) => {
return ['⚔', '🛡', '🍖', '🏃'].includes(reaction.emoji.name) && user.id === message.author.id;
};
message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
console.log('he logs');
if (Discord.MessageReaction.emoji === '⚔') {
message.channel.send("He atacs");
console.log("He ataks");
act = false;
} else if (Discord.MessageReaction.emoji === '🛡') {
message.channel.send("He defens");
console.log("He defens");
act = false;
} else if (Discord.MessageReaction.emoji === '🍖') {
message.channel.send("He itz");
console.log("He itz");
act = false;
} else if (Discord.MessageReaction.emoji === '🏃') {
message.channel.send("He rans");
console.log("He rans");
act = false;
}
})
});
In the console.log('He logs') after message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] }) .then(collected => { const reaction = collected.first(); if you check the console, there's only one "He logs"
Plz help. Thanks
It only reacts 1 emoji instead of 4
message.react('⚔');
message.react('🛡');
message.react('🍖');
message.react('🏃');
It tries to detect the reaction only once
message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
Passing max: 1 makes it wait for only 1 reaction. More info here and here
I got a little problem with synchronous/asynchronous system in the function "Array.foreach".
I don't know how to force my code to wait its end.
I tried to use await/async system but my code did not wait the code in "async responseDB =>".
This is my class:
...
let responsesDTO = [];
await Array.prototype.forEach.call(await searchResponsesByQuestionAndUserId(questions[cpt].idquestion, idUser), async responseDB => {
if(responseDB !== undefined){
const responseDTO = {
response_id:0,
response_text:"",
response_type:""
}
const responseEntity = await searchResponseByResponseId(responseDB.response_id);
responseDTO.response_id = responseDB.response_id;
responseDTO.response_text= responseEntity.text;
responseDTO.response_type= responseDB.type;
responsesDTO.push(responseDTO);
}
});
questionResponse.responses=responsesDTO;
questionResponses[cpt]=questionResponse;
}
Could you help me please? Thanks in advance.
I had to mock your async functions. However, the relevant part is to use for..of instead of forEach
async function searchResponsesByQuestionAndUserId() {
let responsesDB = [];
for (let i = 0; i < 10; i++) {
responsesDB.push({
response_id: parseInt(1000 * Math.random(), 10),
type: 'whatever ' + i
});
}
return new Promise((res) => {
window.setTimeout(() => {
res(responsesDB);
}, 1500);
});
}
async function searchResponseByResponseId(response_id) {
return new Promise((res) => {
window.setTimeout(() => {
res({
text: 'text for response ' + response_id
});
}, 300);
});
}
async function getResponsesDTO() {
let responsesDTO = [],
responsesDB = await searchResponsesByQuestionAndUserId();
for (let responseDB of responsesDB) {
if (responseDB === undefined) {
continue;
}
let responseDTO = {
response_id: 0,
response_text: "",
response_type: ""
},
responseEntity = await searchResponseByResponseId(responseDB.response_id);
responseDTO.response_id = responseDB.response_id;
responseDTO.response_text = responseEntity.text;
responseDTO.response_type = responseDB.type;
responsesDTO.push(responseDTO);
console.log({responseDTO});
}
return responsesDTO;
}
getResponsesDTO().then(responsesDTO => {
console.log(responsesDTO);
});
I'm trying to make a trivia command for my bot and I want to make it so that it sends a message after the amount of time for the collection it says "Times up".
This is what I have written so far:
const Discord = require("discord.js")
exports.run = async(client, message, args) => {
const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, {
time: 10000
});
number = 1;
var random = Math.floor(Math.random() * (number - 1 + 1)) + 1;
switch (random) {
case 1:
{
message.channel.send("Case 1");
collector.on('collect', message => {
if (message.content == "1") {
return message.channel.send("Correct!");
} else {
message.channel.send("wrong!");
}
});
collector.on('end', message => {
message.channel.send("times up!")
});
}
}
};
When I do this it says send of undefined for the end event.
I've also tried this below, but it does nothing:
const Discord = require("discord.js")
exports.run = async(client, message, args) => {
const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, {
time: 10000
});
number = 1;
var random = Math.floor(Math.random() * (number - 1 + 1)) + 1;
switch (random) {
case 1:
{
message.channel.send("Case 1");
collector.on('collect', message => {
if (message.content == "1") {
return message.channel.send("correct!");
} else {
message.channel.send("wrong!");
}
});
collector.stop('end', message => {
message.channel.send("times up!");
});
}
}
};
The last thing I tried was this, but I got .stop of undefined:
const Discord = require("discord.js")
exports.run = async(client, message, args) => {
const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, {
time: 10000
});
number = 1;
var random = Math.floor(Math.random() * (number - 1 + 1)) + 1;
switch (random) {
case 1:
{
message.channel.send("Case 1");
collector.on('collect', message => {
if (message.content == "1") {
return message.channel.send("correct!");
} else {
message.channel.send("wrong!");
}
}).stop(["times up"]);
}
}
};
Also, how could I make the collection stop after the "Correct!" spot?
Try using:
collector.on('end', (collected, reason) => {
message.channel.send("times up!")
});
Like in the docs: https://discord.js.org/#/docs/main/stable/class/MessageCollector?scrollTo=e-end
I have a smol Discord bot (with discord.js-commando), I have this code:
var activevar = ["with the &help command.", "with the developers console", "with some code", "with JavaScript"];
var activities = activevar[Math.floor(Math.random()*activevar.length)];
client.on('ready', () => {
client.user.setActivity(activities);
}
But that only changes it when I restart the bot. Can someone help me out here?
Edited for users on v12 which now uses bot instead of client
const activities = [
"with the &help command.",
"with the developers console.",
"with some code.",
"with JavaScript."
];
bot.on("ready", () => {
// run every 10 seconds
setInterval(() => {
// generate random number between 1 and list length.
const randomIndex = Math.floor(Math.random() * (activities.length - 1) + 1);
const newActivity = activities[randomIndex];
bot.user.setActivity(newActivity);
}, 10000);
});
I changed it so you can change the status from playing to watching or listening.
const activities_list = [
"For Rule Breakers",
"The purple names",
"#general",
"The mods do their job"
]; // creates an arraylist containing phrases you want your bot to switch through.
client.on('ready', () => {
setInterval(() => {
const index = Math.floor(Math.random() * (activities_list.length - 1) + 1); // generates a random number between 1 and the length of the activities array list (in this case 5).
client.user.setActivity(activities_list[index], { type: 'WATCHING' }); // sets bot's activities to one of the phrases in the arraylist.
}, 10000); // Runs this every 10 seconds.
});
Considering how often this is viewed, I thought that I'd provide an updated and clearer response.
const state = 0;
const presences = [
{ type: 'PLAYING', message: 'a game' },
{ type: 'WATCHING', message: 'a video' }
];
setInterval(() => {
state = (state + 1) % presences.length;
const presence = presences[state];
client.user.setActivity(presence.message, { type: presence.type });
}, 10000);
This will also work on v13 too.
const statuses = [
{ name: "to nothing", type: "LISTENING" },
{ name: "something", type: "PLAYING" },
{ name: "your commands", type: "WATCHING" },
];
client.on("ready", () => {
setInterval(() => {
var randomStatus = statuses[Math.floor(Math.random() * statuses.length)];
client.user.setActivity(randomStatus);
}, 10000);
});
Haven't tested, but it should work in theory. It not, try to figure out what is wrong, it's good practice. Otherwise, let me know
client.on("ready", function() {
setInterval(function() {
var actID = Math.floor(Math.random() * Math.floor(activevar.length));
client.user.setActivity(activities);
}, 10000)
});
changes every 10s for playing, watching, listening activities
const activities_list = [
{ type: 'PLAYING', message: 'a game' },
{ type: 'WATCHING', message: 'a video' },
{ type: 'LISTENING', message: 'a music' }
];
client.on('ready', () => {
setInterval(() => {
const index = Math.floor(Math.random() * (activities_list.length - 1) + 1);
client.user.setActivity(activities_list[index].message, { type: activities_list[index].type });
}, 10000);
});
i'm use discord.js v12.
client.on("ready", () => {
console.log(`ok`);
const who = ["hi", "hello"];
setInterval(() => {
const burh = Math.floor(Math.random() * who.length);
client.user.setPresence({ activity: { name: who[burh]}, status: 'dnd'});
}, 5000);
});