So i wanna get started with quick.db for my discord.js bot. I asked someone to help me solve this issue but they seem to be unable to. So if theres anyone here that can help could you tell me whats wrong with my code
module.exports = (client) => client.on('messageCreate', async (message) => {
const prefix = [].concat(client.config.prefix);
const ms = require('ms');
if (
message.author.bot ||
!message.guild ||
!prefix.some((x) => message.content.toLowerCase().startsWith(x))
)
return;
const [cmd, ...args] = message.content
.slice(prefix
.filter((x) => message.content.toLowerCase().startsWith(x))
.sort((a, b) => b.length - a.length)[0].length
)
.trim()
.split(/ +/g);
const command =
client.commands.get(cmd.toLowerCase()) ||
client.commands.find((c) =>
[].concat(c.aliases).includes(cmd.toLowerCase())
);
if (!command) return;
const cd = client.cd.get(`${message.author.id}_${command.name}`);
const left = cd - Date.now();
if (left > 0) {
const msg = await message.channel.send(
`You are on cooldown, please wait **${ms(left)}** to use this command again`
);
return setTimeout(() => msg.delete(), left);
}
if (command.cooldown)
client.cd.set(
`${message.author.id}_${command.name}`,
Date.now() + ms(command.cooldown)
);
try {
await command.run(client, message, args);
} catch (error) {
message.channel.send(error.toString());
}
});
the above code is the working one but whenever i use this
module.exports = (client) => client.on('messageCreate', async (message) => {
const ms = require('ms');
const { QuickDB } = require('quick.db');
const db = new QuickDB();
const prefix = db.get(`newprefix_${message.guild.id}`) || config.prefix
if (!prefix) return;
if (!message.content.startsWith(prefix) || message.author.bot) return;
const [cmd, ...args] = message.content
.slice(prefix
.filter((x) => message.content.toLowerCase().startsWith(x))
.sort((a, b) => b.length - a.length)[0].length
)
.trim()
.split(/ +/g);
const command =
client.commands.get(cmd.toLowerCase()) ||
client.commands.find((c) =>
[].concat(c.aliases).includes(cmd.toLowerCase())
);
if (!command) return;
const cd = client.cd.get(`${message.author.id}_${command.name}`);
const left = cd - Date.now();
if (left > 0) {
const msg = await message.channel.send(
`You are on cooldown, please wait **${ms(left)}** to use this command again`
);
return setTimeout(() => msg.delete(), left);
}
if (command.cooldown)
client.cd.set(
`${message.author.id}_${command.name}`,
Date.now() + ms(command.cooldown)
);
try {
await command.run(client, message, args);
} catch (error) {
message.channel.send(error.toString());
}
});
it doesn't work, meaning my bot doesn't reply
Related
We have to create a Bingo game in React Native with Firebase Realtime Database on Android simulator. The app game is for 2 players. When the first player enter in the app, he create the game and wait for the second player to join.
we want to create a screen with the writing: "Waiting for another player" that appears to the first player until the second player connects then when the second player connects the card is shown.
We wrote this code but it return 'undefined' .
function Game(){
const authCtx = useContext(AuthContext);
const gameCtx = useContext(GameContext);
const [loadPlayer, setLoadPlayer] = useState(false);
useEffect(() => {
async function gamePlay(){
gameCtx.player1 = authCtx.token;
const play = await setGame(authCtx.token, gameCtx);
console.log(play); //return undefined
if(play == 'CREATE'){
setLoadPlayer(true);
}else if(play == 'UPDATE'){
setLoadPlayer(false);
}
if(loadPlayer){
return <LoadingOverlay message="Waiting for another player... " />;
}
}
gamePlay();
}, []);
return <Card />;
}
export default Game;
export function create(game){
const db = getDatabase();
const newGameKey = push(child(ref(db), 'GAME')).key;
set(ref(db, '/GAME/' + newGameKey), game)
.then(() => {console.log('Game Create!');})
.catch((error) => {console.log(error);});
}
export function setGame(email, game){
const dbRef = ref(getDatabase());
var player = false;
get(child(dbRef, 'GAME/')).then((snapshot) => {
if (snapshot.exists()) {
snapshot.forEach(function(childSnapshot) {
const key = childSnapshot.key;
const key1 = snapshot.child(key + '/player1').val();
const key2 = snapshot.child(key + '/player2').val();
if( key2 == "" && email != key1){
console.log('P2');
updateGame(email, key);
player = true;
return true;
}
});
if(player == false){
console.log('P1');
player = true;
create(game);
}
} else {
//create the first game!
create(game);
}
}).catch((error) => {
console.error(error);
});
}
export function updateGame(email, key){
console.log('Update: ' + key);
const db = getDatabase();
const updates = {};
updates['/GAME/' + key + '/player2'] = email;
return update(ref(db), updates);
}
We think this is due to "async" and "await" because not working correctly.
Do you have any suggestions?
How can we redirect the first player to a waiting screen?
is ref(getDatabase()) is promise?. if it is then use await before it.
and use async function before setGame if you are using await while calling.
export async function setGame(email, game){
const dbRef = await ref(getDatabase());
var player = false;
get(child(dbRef, 'GAME/')).then((snapshot) => {
if (snapshot.exists()) {
snapshot.forEach(function(childSnapshot) {
const key = childSnapshot.key;
const key1 = snapshot.child(key + '/player1').val();
const key2 = snapshot.child(key + '/player2').val();
if( key2 == "" && email != key1){
console.log('P2');
updateGame(email, key);
player = true;
return true;
}
});
if(player == false){
console.log('P1');
player = true;
create(game);
}
} else {
//create the first game!
create(game);
}
}).catch((error) => {
console.error(error);
});
}
Getting "spc message cannot be null" as response every time while providing implementation of Shaka player to play fairplay content on safari browser.Tried many ways to provide spc message in body and header also and we are actually sending it that i can see in network tab nut still cant find a solution. Here is the code below.
if (this.platform.getBrowserPlatform() === Constants.PLATFORMS.SAFARI_WEB) {
this.shakaPlayer.configure({
drm: {
servers: {
'com.apple.fps.1_0': `${this.config.baseUrl}${Constants.DRM_FAIRPLAY_LICENSE}`,
},
advanced: {
'com.apple.fps.1_0': {
serverCertificate: cert,
},
},
},
});
let that = this //,licenseUri;
this.shakaPlayer.configure('drm.initDataTransform', (initData) => {
const skdUri = shaka.util.StringUtils.fromBytesAutoDetect(initData);
var contentId = skdUri.substring(skdUri.indexOf('skd://') + 6);
// licenseUri = skdUri.replace('skd://', 'https://');
const url = new URL(contentId);
const urlParams = new URLSearchParams(url.search);
const cert = that.shakaPlayer.drmInfo().serverCertificate;
let id = urlParams.get('contentId');
that.id = id;
return shaka.util.FairPlayUtils.initDataTransform(initData, id, cert);
// let skdUrl = shaka.util.StringUtils.fromBytesAutoDetect(initData);
// licenseUri = skdUrl.replace('skd://', 'https://');
// const cert = that.shakaPlayer.drmInfo().serverCertificate;
// return shaka.util.FairPlayUtils.initDataTransform(initData, licenseUri, cert);
});
this.shakaPlayer.getNetworkingEngine().registerRequestFilter((type, request) => {
if (type != shaka.net.NetworkingEngine.RequestType.LICENSE) {
return;
}
let token = localStorage.getItem('auth');
let testToken = JSON.parse(token);
const originalPayload = new Uint8Array(request.body);
const base64Payload = shaka.util.Uint8ArrayUtils.toBase64(originalPayload);
const params = `{ "spc": "${base64Payload}", "assetId":"${that.id}"}`;
request.body = shaka.util.StringUtils.toUTF8(params);
request.headers['Content-Type'] = 'application/json';
request.headers['Authorization'] = `JWT ${testToken.access_token}`
console.log("request.body", request.body)
});
this.shakaPlayer.getNetworkingEngine().registerResponseFilter((type, response) => {
if (type != shaka.net.NetworkingEngine.RequestType.LICENSE) {
return;
}
console.log("license passed")
let responseText = shaka.util.StringUtils.fromUTF8(response.data);
responseText = responseText.trim();
if (responseText.substr(0, 5) === '<ckc>' &&
responseText.substr(-6) === '</ckc>') {
responseText = responseText.slice(5, -6);
}
response.data = shaka.util.Uint8ArrayUtils.fromBase64(responseText).buffer;
});
this.shakaPlayer.load(this.getProgramUrl(channel, program, restart)).then(() => {
console.log('1', this.shakaPlayer.isTextTrackVisible());
console.log('2', this.shakaPlayer.getTextTracks());
console.log('3', this.shakaPlayer.getTextLanguages());
}).catch((error) => {
console.log(error);
});
Smooth play of fairplay content on safari or some advise what can i do in this case
const [markets,setMarkets]=useState(false)
useEffect(() => {
if (socketConnection != null) {
socketConnection.on("url", (data) => {
getData();
markets.length > 0 &&
markets.map((market) => {
if (data.pair == market.pair) {
let newPrice = data.price.toFixed(data.decimalValue);
let oldData = markets.filter(
(market) => market.pair == data.pair
)[0];
let oldIndex = markets.findIndex(
(market) => market.pair == data.pair
);
let oldPrice = oldData.price.toFixed(oldData.decimalValue);
if (newPrice != oldPrice) {
markets[oldIndex].price = data.price;
markets[oldIndex].lastPrice = data.lastPrice;
markets[oldIndex].change = data.change;
markets[oldIndex].oldPrice = oldData.price;
}
}
});
});
setMarkets(markets);
}
}, [socketConnection]);
I am updating my state like this using socket.io-client but getting this error as Please Report : Excessive number of pending requests and app is hanged.Anyone plse help for the issue
Ok so my bot got rebuilt with a somewhat different code.
I'm using a somewhat more simplified fs command and events handler. My command works as intended.
But I'm wanting to add the amount pruned into the fields for the richEmbed and it keeps erroring out.
Here is my purge.js file
const Discord = require('discord.js')
module.exports = {
name: 'purge',
description: 'Purge up to 99 messages.',
execute(message, args) {
console.log("purging messages")
const embed = new Discord.RichEmbed()
.setTitle("Success")
.setColor(0x00AE86)
.setFooter("Guardian", "https://raw.githubusercontent.com/phantomdev-github/Resources/master/Discord%20Bots/Guardian/src/avatar.png")
.setThumbnail("https://raw.githubusercontent.com/phantomdev-github/Resources/master/Discord%20Bots/Guardian/src/avatar.png")
.setTimestamp()
.setURL("https://github.com/phantomdev-github/Resources/tree/master/Discord%20Bots/Guardian")
.addField("Bot Messages Purged", "missing code here", false)
.addField("User Pins Purged", "missing code here", false)
.addField("User Messages Purged", "missing code here", false)
.addField("Total Messages Purged", "missing code here", false)
message.channel.send({ embed });
const amount = parseInt(args[0]) + 1;
if (isNaN(amount)) {
return message.reply('that doesn\'t seem to be a valid number.');
} else if (amount <= 1 || amount > 100) {
return message.reply('you need to input a number between 1 and 99.');
}
message.channel.bulkDelete(amount, true).catch(err => {
console.error(err);
message.channel.send('there was an error trying to prune messages in this channel!');
});
},
};
If it helps this i my index.js
const fs = require('fs');
const Discord = require('discord.js');
const client = new Discord.Client();
const { token } = require('./token.json');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
console.log(file,command)
}
fs.readdir('./events/', (err, files) => {
if (err) return console.error(err);
files.forEach(file => {
if(!file.endsWith('.js')) return;
const eventFunction = require(`./events/${file}`);
console.log(eventFunction)
eventFunction.execute(client)
});
});
client.login(token);
and this is my message.js
const { prefix } = require('./prefix.json');
module.exports = {
name: 'message',
description: '',
execute:function(client) {
client.on('message',message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
})
}};
Basically I'm trying to figure out what to place into the "missing code here" sections. Also any way to lock it to people with Administrator permissions only would be useful as well. I attempted that but it failed to work with the embed.
If I understand you right you want to know how to get the amount of the purged pins, bot msgs and user msgs. For this you need to put your embed after you deleted the messages.
purge.js
const Discord = require('discord.js')
module.exports = {
name: 'purge',
description: 'Purge up to 99 messages.',
execute(message, args) {
console.log("purging messages")
const amount = parseInt(args[0]) + 1;
if (isNaN(amount)) {
return message.reply('that doesn\'t seem to be a valid number.');
} else if (amount <= 1 || amount > 100) {
return message.reply('you need to input a number between 1 and 99.');
}
message.channel.bulkDelete(amount, true).then(deletedMessages => {
// Filter the deleted messages with .filter()
var botMessages = deletedMessages.filter(m => m.author.bot);
var userPins = deletedMessages.filter(m => m.pinned);
var userMessages = deletedMessages.filter(m => !m.author.bot);
const embed = new Discord.RichEmbed()
.setTitle("Success")
.setColor(0x00AE86)
.setFooter("Guardian", "https://raw.githubusercontent.com/phantomdev-github/Resources/master/Discord%20Bots/Guardian/src/avatar.png")
.setThumbnail("https://raw.githubusercontent.com/phantomdev-github/Resources/master/Discord%20Bots/Guardian/src/avatar.png")
.setTimestamp()
.setURL("https://github.com/phantomdev-github/Resources/tree/master/Discord%20Bots/Guardian")
.addField("Bot Messages Purged", botMessages.size, false)
.addField("User Pins Purged", userPins.size, false)
.addField("User Messages Purged", userMessages.size, false)
.addField("Total Messages Purged", deletedMessages.size, false);
message.channel.send(embed);
}).catch(err => {
console.error(err);
message.channel.send('there was an error trying to prune messages in this channel!');
});
},
};
I'm facing a pretty ugly issue that I'm not able to overcome by myself, I just don't get it.
A short summary of my app purpose: You can find food around and make orders to restaurant owners.
I wrote a helper function that allows me to decide if the restaurant is open or closed based on its schedule “horarioSemanal” property.
This function take the restaurants queried from firestore as arguments and depending in some conditions it decide which value of the property “disponible” (available) it deserves.
The thing is that it works pretty well! So well that I published the changes through expo, and as expo has updates over-the-air and I have my app in both apptore and Google play it reached all my users…
None of my users were able to use my app until I removed the changes because I was unable to detect the issue. In my simulator it worked 100% but when the app was deployed crashed almost instantly.
Testing, testing, and testing I finally come to the issue but I still can't figure out what the hell should I do to overcome this situation.
The app while I use the js debugger it works perfectly! but when I turned off this new module I wrote doesn't work.
I recorded a video so you can see the same I'm watching on my screen:
https://www.youtube.com/watch?v=x9-t8-3XzKc
this is the action where im dispatching the action:
import { restaurantesHorarioValidado, validaDisponibilidadComidas } from '../../src/3-ResultadosComponents/Librerias/DisponibilidadHorario';
export const searchResultsInLocation = (ubicacion) => {
const db = firebase.firestore();
const docRef = db.collection('Restaurantes').where('abierto', '==', true).where(`zonaOperativa.zonaConsulta.${ubicacion}`, '==', true).get();
const restaurantesIDS = [];
return (dispatch) => {
const holder = [];
dispatch({
type: BUSQUEDA_DE_RESULTADOS,
});
docRef.then(querySnapshot => {
querySnapshot.forEach(doc => {
holder.push(doc.data());
restaurantesIDS.push(doc.data().id);
});
dispatch({
type: DESCARGA_RESTAURANTES_ABIERTOS,
restaurantes: restaurantesHorarioValidado(holder)
});
})
.then(() => {
const comidasRefs = [];
restaurantesIDS.forEach(restaurant => {
const ref = db.collection('Comidas').where('restaurantID', '==', `${restaurant}`).get();
comidasRefs.push(ref);
});
return Promise.all(comidasRefs).then(results => {
const comidas = [];
results.forEach(resto => {
resto.forEach(comida => comidas.push(comida.data()));
});
dispatch({
type: DESCARGA_COMIDAS,
comidas: validaDisponibilidadComidas(comidas, restaurantesHorarioValidado(holder))
});
})
.then(() => dispatch({
type: BUSQUEDA_DE_RESULTADOS,
}))
.catch(err => console.log('error; ', err));
});
};
};
here is how the reducer is handling the action:
case DESCARGA_COMIDAS:
return { ...state, comidas: action.comidas };
case DESCARGA_RESTAURANTES_ABIERTOS:
return { ...state, restaurantes: action.restaurantes };
this is the module I wrote and I'm using to create the object that the action creator send:
const diasDeSemana = ['Domingo', 'Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado'];
const today = new Date().getDay();
const hoyAbre = (horario) => {
if (horario) {
const JornadaHoy = horario.find(jornada => jornada.dia == diasDeSemana[today]);
return JornadaHoy;
}
return false;
};
export const isRestaurantAvalaible = (horario) => {
const Today = new Date();
if (hoyAbre(horario)) {
//Si el restaurant abre hoy
//Evalua si está abierto
const horarioApertura = () => {
const nuevoDia = new Date(`${Today.getFullYear()}, ${Today.getMonth() + 1} ${Today.getDate()} ${hoyAbre(horario).horario.apertura}:00`);
return nuevoDia;
};
const horarioCierre = () => {
//Si horario de cierre es hoy
const nuevoDia = new Date(`${Today.getFullYear()}, ${Today.getMonth() + 1} ${Today.getDate()} ${hoyAbre(horario).horario.cierre}:00`);
//Si el horario de cierre de hoy es pasado las 00:00
const cierraTomorrow = new Date(`${Today.getFullYear()}, ${Today.getMonth() + 1} ${Today.getDate() + 1} ${hoyAbre(horario).horario.cierre}:00`);
if (nuevoDia.getHours() <= 8) {
return cierraTomorrow;
}
return nuevoDia;
};
const isNowOpen = Today.getTime() >= horarioApertura().getTime();
const isNowClosed = Today.getTime() >= horarioCierre().getTime();
//Si está abierto
if (isNowOpen && !isNowClosed) {
return { estado: 'abierto' };
}
//Si abre mas rato
if (hoyAbre(horario) && (Today.getTime() < horarioApertura())) {
return { estado: 'abre pronto', horarioApertura: horarioApertura() };
}
//Si ya cerró
if (isNowOpen && isNowClosed) {
return { estado: 'ya cerro', horarioCierre: horarioCierre() };
}
}
//Si hoy no abre
if (!hoyAbre(horario)) {
return { estado: 'No abre hoy' };
}
};
export const restaurantesHorarioValidado = (restaurantes) => {
const restaurantesModificados = restaurantes.map(restaurant => {
return { ...restaurant, disponible: isRestaurantAvalaible(restaurant.horarioSemanal) };
});
const restaurantesAbiertos = restaurantesModificados.filter(restaurant => restaurant.disponible.estado == 'abierto');
const restaurantesProximosAbrir = restaurantesModificados.filter(restaurant => restaurant.disponible.estado == 'abre pronto');
const restaurantesCerrados = restaurantesModificados.filter(restaurant => restaurant.disponible.estado == ('ya cerro' || 'No abre hoy'));
return [...restaurantesAbiertos, ...restaurantesProximosAbrir, ...restaurantesCerrados];
};
export const validaDisponibilidadComidas = (comidas, restaurantes) => {
//Se le agrega la propiedad "disponible" del restaurant dueño
const comidasModificadas = comidas.map(comida => {
const Owner = restaurantes.find(restaurant => restaurant.id == comida.restaurantID);
return { ...comida, disponible: Owner.disponible };
});
const comidasDisponibles = comidasModificadas.filter(comida => comida.disponible.estado == 'abierto');
const comidasProximosAbrir = comidasModificadas.filter(comida => comida.disponible.estado == 'abre pronto');
const comidasNoDisponibles = comidasModificadas.filter(comida => comida.disponible.estado == ('ya cerro' || 'No abre hoy'));
return [...comidasDisponibles, ...comidasProximosAbrir, ...comidasNoDisponibles];
};
this is the error I get once I turned off the js debugger:
[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'restaurant.disponible.estado')]
Stack trace:
src/3-ResultadosComponents/Librerias/DisponibilidadHorario.js:65:98 in <unknown>
src/3-ResultadosComponents/Librerias/DisponibilidadHorario.js:65:62 in restaurantesHorarioValidado
store/actions/2-ResultadosActions.js:55:50 in <unknown>
node_modules/promise/setimmediate/core.js:37:14 in tryCallOne
node_modules/promise/setimmediate/core.js:123:25 in <unknown>
...
As it suggest there is some error with promises I tried making those functions work as promises. The errors disappear but the I didn't get the object back...
The question is this How the hell may this work just when the debugger it's on and not when it's turned off?
what should I do to get my life back?