Discord button only works once discord.js - node.js

I have posted a button but it only works once
but after that when I use it again
Also
How can I reply to message if I use deferUpdate it shows
Code
client.on('ready', () => {
client.user.setActivity('people and managing the server', {
type: 'WATCHING',
});
const channel = client.channels.cache.get('894171605608042496');
const row = new MessageActionRow().addComponents(
new MessageButton()
.setCustomId('openTicket')
.setLabel('Create ticket')
.setEmoji('📩')
.setStyle('SECONDARY')
);
channel
.send({
embeds: [
{
title: 'SGAS Tickets',
color: '#388e3c',
description: 'To create a ticket react with 📩',
},
],
components: [row],
})
.then(() => {
const filter = () => {
return true;
};
const collector = channel.createMessageComponentCollector({
filter,
time: 15 * 1000,
});
collector.on('collect', (i) => {
i.deferUpdate().then(() => {
Ticket.count({}, (err, result) => {
if (err) {
console.log(err);
} else {
const ticketNumber = result + 1;
const ticketString = convertNumber(ticketNumber);
const ticket = new Ticket({
tickedId: ticketString,
});
ticket.save((err) => {
if (err) {
console.log(err);
} else {
const myguild = client.guilds.cache.get('887277806386565150');
if (!myguild) {
console.log('guild not found');
return;
}
const category = myguild.channels.cache.find(
(c) =>
c.id === '887277807279947826' &&
c.type == 'GUILD_CATEGORY'
);
if (!category) {
console.log('category not found');
return;
}
myguild.channels
.create(`Ticket#${ticketString}`, {
type: 'GUILD_TEXT',
})
.then(async (myc) => {
myc.setParent(category).then(() => {
myc.send(
`Hello <#${i.user.id}>, your question will be solved here shortly`
);
i.reply({
content: `Go to <#${myc.id}>, for your question`,
ephemeral: true,
});
});
});
}
});
}
});
});
});
});
});

you are using a component collector - which expires in 15 seconds, as seen in your code. That means after 15 seconds your bot stops listening for button clicks. My recommendation is to use the interactionCreate event to listen for that button: see docs https://discord.js.org/#/docs/main/stable/class/ButtonInteraction
Example:
client.on("interactionCreate", (interaction) => {
if(!interaction.isButton()) return;
if(interaction.customId === "openTicket") {
// your ticket code here
}
});

Related

Gpay payment-gateway integration in NodeJS

I tried it in Html and Javascript it's working perfect in web (mobile's browser).I am using angular for frontend and node for backend but not getting any proper solution for redirect Playstore or Gpay for mobile browser. Basically I want to implement for mobile browser.
this is my node for backend code & for frontend I already paste static. So, request you that please check & get back to me proper resolution or tutorial. Thanks & Regards--
const canMakePaymentCache = 'canMakePaymentCache';
onBuyClicked();
function readSupportedInstruments() {
let formValue = {};
formValue['pa'] = keys.GPAY_MERCHANT_ID;//merchantId
formValue['pn'] = `Test_Gpay_Name`;//transactionId
formValue['tn'] = 'Testing Messages ';//message
formValue['mc'] = 'merchant Code';//
formValue['tr'] = 'Transaction Reference';
formValue['tid'] = 'Transaction id';
formValue['url'] = 'http://localhost.co/';
return formValue;
}
function readAmount() {
//const pay_amount = parseInt(req.body.amount) * 100;
return parseInt(req.body.amount) * 100;
}
function onBuyClicked() {
// if (!window.PaymentRequest) {
// console.log('Web payments are not supported in this browser.');
// return;
// }
let formValue = readSupportedInstruments();
const supportedInstruments = [
{
supportedMethods: ['https://pwp-server.appspot.com/pay-dev'],
data: formValue,
},
{
supportedMethods: ['https://tez.google.com/pay'],
data: formValue,
},
];
const details = {
total: {
label: 'Total',
amount: {
currency: 'INR',
value: readAmount(),
},
},
displayItems: [
{
label: 'Original amount',
amount: {
currency: 'INR',
value: readAmount(),
},
},
],
};
const options = {
requestShipping: false,
requestPayerName: false,
requestPayerPhone: false,
requestPayerEmail: false,
shippingType: 'shipping',
};
let request = null;
try {
//const PaymentRequest = {};
//request = PaymentRequest(supportedInstruments, details, options);
request ={supportedInstruments, details, options};
} catch (e) {
return;
}
if (!request) {
console.log('Web payments are not supported in this browser.');
return;
}
var canMakePaymentPromise = checkCanMakePayment(request);
canMakePaymentPromise
.then((result) => {
showPaymentUI(request, result);
})
.catch((err) => {
console.log('Error calling checkCanMakePayment: ' + err);
});
}
function checkCanMakePayment(request) {
//if (sessionStorage.hasOwnProperty(canMakePaymentCache)) {
//return Promise.resolve(JSON.parse(sessionStorage[canMakePaymentCache]));
//}
var canMakePaymentPromise = Promise.resolve(true);
if (request.canMakePayment) {
canMakePaymentPromise = request.canMakePayment();
}
return canMakePaymentPromise
.then((result) => {
canMakePaymentCache = result;
return result;
})
.catch((err) => {
console.log('Error calling canMakePayment: ' + err);
});
}
function showPaymentUI(request, canMakePayment) {
if (!canMakePayment) {
redirectToPlayStore();
return;
}
let paymentTimeout = window.setTimeout(function () {
window.clearTimeout(paymentTimeout);
request.abort()
.then(function () {
console.log('Payment timed out after 20 minutes.');
})
.catch(function () {
console.log('Unable to abort, user is in the process of paying.');
});
}, 20 * 60 * 1000); /* 20 minutes */
request.show()
.then(function (instrument) {
window.clearTimeout(paymentTimeout);
processResponse(instrument); // Handle response from browser.
})
.catch(function (err) {
console.log(err);
});
}
function processResponse(instrument) {
var instrumentString = instrumentToJsonString(instrument);
console.log(instrumentString);
fetch('/buy', {
method: 'POST',
headers: new Headers({ 'Content-Type': 'application/json' }),
body: instrumentString,
credentials: 'include',
})
.then(function (buyResult) {
if (buyResult.ok) {
return buyResult.json();
}
console.log('Error sending instrument to server.');
})
.then(function (buyResultJson) {
completePayment(
instrument, buyResultJson.status, buyResultJson.message);
})
.catch(function (err) {
console.log('Unable to process payment. ' + err);
});
}
function completePayment(instrument, result, msg) {
instrument.complete(result)
.then(function () {
console.log('Payment completes.');
console.log(msg);
document.getElementById('inputSection').style.display = 'none'
document.getElementById('outputSection').style.display = 'block'
document.getElementById('response').innerHTML =
JSON.stringify(instrument, undefined, 2);
})
.catch(function (err) {
console.log(err);
});
}
console.log(`in line 448....`);
function redirectToPlayStore() {
//if (confirm('Tez not installed, go to play store and install?')) {
//window.location.href = 'https://play.google.com/store/apps/details?id=com.google.android.apps.nbu.paisa.user.alpha'
//res.writeHead( "https://play.google.com/store/apps/details?id=com.google.android.apps.nbu.paisa.user.alpha" );
const response_data = axios
.post(
'https://play.google.com/store/apps/details?id=com.google.android.apps.nbu.paisa.user.alpha',
)
console.log(`in line no. 459... ${response_data}`);
return response_data;
//};
}
function instrumentToJsonString(instrument) {
var instrumentDictionary = {
methodName: instrument.methodName,
details: instrument.details,
shippingAddress: addressToJsonString(instrument.shippingAddress),
shippingOption: instrument.shippingOption,
payerName: instrument.payerName,
payerPhone: instrument.payerPhone,
payerEmail: instrument.payerEmail,
};
return JSON.stringify(instrumentDictionary, undefined, 2);
}

display questions based on user type MERN

I have two collections from one questions for admin comes and from other questions for user comes.
I am unable to show the questions in React using redux store.
store/action
import { QUESTIONS } from '../../constants/actionTypes';
import * as api from '../../services/api';
import * as paths from '../../constants/apiPaths';
const TOTAL_QUESTIONS = 60;
export const fetcQuestions = (router) => async (dispatch) => {
try {
const user = await api.get(paths.FETCH_USER);
const userType = user.type;
console.log(userType + "userType");
if((userType === "Student") || (userType === "STUDENT"))
{
const {questions, assessment, options} = await api.get(paths.FETCH_QUESTIONS);
console.log(api.get(paths.FETCH_QUESTIONS) + "Question path");
dispatch({ type: QUESTIONS, questions, assessment, options });
if(assessment.responded === TOTAL_QUESTIONS) {
router.push('/advice');
}
}
else
if((userType === "Admin") || (userType === "ADMIN"))
{
console.log(userType + "type of user");
const {questions, assessment, options} = await api.get(paths.FETCH_QUESTIONS);
console.log(api.get(paths.FETCH_QUESTIONS) + "Question path");
dispatch({ type: QUESTIONS, questions, assessment, options });
if(assessment.responded === TOTAL_QUESTIONS) {
console.log("thank you");
}
}
} catch (error) {
console.log(error);
}
};
export const postAssessment = (data, router) => async (dispatch) => {
try {
const {questions, assessment, options} = await api.post(paths.POST_ASSESSMENT, data);
console.log(paths.POST_ASSESSMENT + "assessment");
dispatch({ type: QUESTIONS, questions, assessment, options });
if(assessment.responded === TOTAL_QUESTIONS) {
console.log("Thank you");
}
} catch (error) {
console.log(error);
}
};
please help me looking out whats wrong I am doing here. Thank You.
Reducer:
import * as actionType from '../../constants/actionTypes';
const assessmentReducer = (state = { questions: null, assessment: null, options: null }, action) => {
switch (action.type) {
case actionType.QUESTIONS:
return { ...state, questions: action?.questions, assessment: action?.assessment, options: action?.options, loading: false, errors: null };
default:
return state;
}
};
export default assessmentReducer;
NodeJS controller:
const TOTAL_QUESTIONS = 120;
export const fetchQuestions = async (req, res) => {
try {
const user = await db.findOne('USER', { _id: req.userId});
console.log(user + "user data");
let answerdQuestions = [];
let nextQuestions;
let assessment;
if (user.assessment) {
assessment = await db.findOne('ASSESSMENT', { user: req.userId });
answerdQuestions = assessment.responses.map(response => response.number)
}
nextQuestions = getNextQuestions(answerdQuestions);
if ((user.type === "STUDENT") || (user.type === "student")) {
console.log(user.type + "type");
const questions = await db.find('QUESTIONG', { number: { $in: nextQuestions } });
console.log(questions.number + "quesstudent");
res.status(200).json({ questions, assessment: { id: assessment?._id, responded: answerdQuestions.length }, options: options });
return answerdQuestions;
}
else {
console.log(user.type + "typegh");
const questions = await db.find('QUESTION', {number: { $in: nextQuestions }});
console.log(questions.question + "quesdata");
res.status(200).json({ questions, assessment: { id: assessment?._id, responded: answerdQuestions.length }, options: options });
return answerdQuestions;
}
} catch (err) {
console.log(err)
res.status(500).json({ message: "Something went wrong" });
}
};
export const postResponses = async (req, res) => {
try {
let responses = req.body.responses;
let assessmentId = req.body.id;
responses = responses.map(response => {
return {
score: Number(response.value),
number: response.number,
category: response.category,
question: response._id
}
});
const user = await db.findOne('USER', {_id: req.userId});
console.log( user.type + "typeofuser");
let assessment = await db.findOne('ASSESSMENT', { _id: assessmentId });
if (assessment?.responses.length === TOTAL_QUESTIONS) {
res.status(200).json("completed");
}
if (!assessment) {
//
let response = {
user: req.userId,
responses: responses,
responded: responses.length
}
assessment = await db.create('ASSESSMENT', response);
await db.findOneAndUpdate('USER', { _id: req.userId }, { assessment: assessment._id });
} else {
assessment = await db.findOneAndUpdate('ASSESSMENT', { _id: assessment._id }, { $push: { responses: { $each: responses } } });
}
let answerdQuestions = assessment.responses.map(response => response.number);
const nextQuestions = getNextQuestions(answerdQuestions);
if (answerdQuestions.length === TOTAL_QUESTIONS) {
console.log("You win");
]
}
if((user.type === "STUDENT") || (user.type==="student") ){
console.log("type" + user.type);
const questions = await db.find('QUESTIONG', { number: { $in: nextQuestions } });
res.status(200).json({ questions, assessment: { id: assessment?._id, responded: answerdQuestions.length }, options: options });
} else
{
console.log(user.type + "typeg");
const questions = await db.find('QUESTION', { number: { $in: nextQuestions } });
res.status(200).json({ questions, assessment: { id: assessment?._id, responded: answerdQuestions.length }, options: options });
}
}catch (err) {
console.log(err)
res.status(500).json({ message: "Something went wrong" });
}
};
//export default fetchQuestions;
I have added reducer and NodeJS controller also, Based on user type the questions are to be shown. Please help. If type is student then the questions are not getting displayed else condition the questions are getting displayed
What I can see is, you have mentioned wrong database when you are trying to fetch data for usertype student. Here is your code:
if (user.type === 'STUDENT' || user.type === 'student') {
console.log(user.type + 'type');
const questions = await db.find('QUESTIONG', { number: { $in: nextQuestions } });
You need to correct the database name, and everything will work fine:
const questions = await db.find('QUESTION', { number: { $in: nextQuestions } });
Hope this works!!!

Don't know how to form a short question so any help would be appreciated

So I made this poll command that people without admin could make polls. To prevent spam, there is a verify step for everyone without admin. But when you react to the poll to verify it, it only works for the person making the poll. And not the admin that's supposed to check if it's not spam.
So when the admin reacts nothing happens but when the person that made the poll reacts to it, it verifies the poll and sends it to the main channel.
Code is down below is someone could help! 'Appreciate it!
const {Client, Collection, GuildMember, User, MessageEmbed, Message} = require("discord.js");
const ms = require("ms");
const delay = (msec) => new Promise((resolve) => setTimeout(resolve, msec));
module.exports.run = async(client, message, args, user, reaction) => {
var woord = '!poll'
var question = args.slice(0).join(' ')
var poll = new MessageEmbed()
.setTitle(`${message.author.username} wil een poll maken.`)
.setDescription(question)
.setColor('#eb8dd8')
.setFooter(`Poll gemaakt door: `+ message.author.username)
var success = new MessageEmbed()
.setDescription(question)
.setColor('#eb8dd8')
.setFooter("Poll started door: "+ message.author.username)
if(message.content.includes(woord)) {
message.delete({timeout:0})
}
if(!message.member.roles.cache.some(r => r.name === 'Barman')) {
if(message.channel.name.includes("🙇-poll")) {
if(args[0]) {
message.delete()
message.guild.channels.create(message.author.username, { permissionOverwrites:[
{
deny: 'VIEW_CHANNEL',
id: message.guild.id
},
{
allow: 'VIEW_CHANNEL',
id: message.author.id
},
],
}).then(channel => {
channel.send(poll).then(poll => {
poll.react('✅')
.then(() => poll.react('❌'));
})
})
} else {
message.delete()
}
}
} else {
var pollChannel = client.channels.cache.get('876531134702448701')
pollChannel.send(success).then(success => {
success.react('✅')
.then(() => success.react('❌'))
})
}
client.on('messageReactionAdd', (reaction, user) => {
const deleteChannel = message.guild.channels.cache.find(channel => channel.name.toLowerCase() === user.username);
var pollChannel = client.channels.cache.get('876531134702448701')
if(reaction.emoji.name === '✅') {
if(message.guild.channels.cache.find(channel => channel.name.toLowerCase() === user.username)) {
deleteChannel.delete()
.then(channel => {
pollChannel.send(success).then(success =>{
success.react('✅')
.then(() => success.react('❌'))
})
})
}
} if(reaction.emoji.name === '❌') {
if(message.guild.channels.cache.find(channel => channel.name.toLowerCase() === user.username)) {
deleteChannel.delete()
}
}
})
}
module.exports.help = {
name: "poll"
}
At the start of your function you can do this:
const questions = new Collection();
questions.set("What is the color of healthy grass?", "green");
questions.set("How many vowels are there in these letters: apple", "2");
const chosen = questions.randomKey()
await message.channel.send(`Please answer the question. This is to prevent spam. Make sure your spelling is correct. You have 30 seconds —> ${chosen}`)
try {
await message.channel.awaitMessages((m) => m.author.id === message.author.id && m.content.toLowerCase() === questions.get(chosen), {
time: 30000,
max: 1
})
} catch(err) {
return message.channel.send("You ran out of time to answer correctly!")
}
//code to make poll
Your awaitMessages syntax may be different on v13. You can also replace my questions, and add as many as you want!

Trying to edit a message multiple times with timeout / discord.js

I'm working on a bot and I want to do a message that gets edited multiple times with a timeout function. What I'm trying to do is a loading thing. Here is my code:
const discord = require('discord.js');
const bot = new Discord.Client();
bot.on("message", message => {
if(message.content.startsWith("$load")){
const usere = message.mentions.users.first();
if(usere){
try{
message.channel.send(`Loading.`)
.then(message => { setTimeout(function() { message.edit(`Loading..`) }, 10000)})
.then(message => { setTimeout(function() { message.edit(`Loading...`) }, 10000)})
}catch(e){
}
}
}
})
bot.login('Token');
You tring to get promise message of set timeout function, and its will return undefined, you need use somethink like this:
bot.on("message", message => {
if (message.content.startsWith("$load")) {
const usere = message.mentions.users.first();
if (usere) {
message.channel.send(`Loading.`)
.then(msg => {
setTimeout(function() {
msg.edit(`Loading..`)
}, 10000);
setTimeout(function() {
msg.edit(`Loading...`)
}, 12000)
})
}
}
})
bot.login('Token');
Or you can use inteval, for edit every 10 second , just set Loading... as varivale and change it after every call.
bot.on("message", message => {
if (message.content.startsWith("$load")) {
const usere = message.mentions.users.first();
if (usere) {
message.channel.send(`Loading.`)
.then(msg => {
setInterval(function() {
msg.edit(`Loading..`)
}, 10000);
})
}
}
})

Trouble with promise in firebase functions

This code either runs once or a max of 100 times. I have a dummy data file with 6000 records as this is the average that it will have to handle.
Currently using the Blaze plan.
The code was working somewhat, I set up a new project and now I get this issue.
export const uploadPatrons = functions.storage
.object()
.onFinalize((object, context) => {
let patronPromise: any[];
patronPromise = [];
if (object.name === 'patrons/upload.csv') {
admin
.storage()
.bucket()
.file('/patrons/upload.csv')
.download({})
.then(data => {
Papa.parse(data.toString(), {
header: true,
skipEmptyLines: true,
complete: result => {
result.data.forEach(x => {
x.inside = false;
x.arrived = false;
x.img = false;
x.arrivedTime = null;
const newPromise = admin
.firestore()
.collection('patrons')
.add({ ...x })
.then(doc => {
console.log(doc);
})
.catch(err => {
console.log(err);
});
patronPromise.push(newPromise);
});
}
});
})
.catch(err => {
console.log(err);
});
}
return Promise.all(patronPromise)
.catch(err => {
console.log(err);
});
});
All it has to do is read the file from the storage, parse it and add each record to the firebase collection
Function returned undefined, expected Promise or value
This is the error I get in the logs
Because of your first promise may be shutdown even it not finish. So try to follow the rule promise/always-return
export const uploadPatrons = functions.storage
.object()
.onFinalize((object, context) => {
if (object.name === 'patrons/upload.csv') {
return admin.storage().bucket()
.file('/patrons/upload.csv')
.download({})
.then(data => {
let patronPromise: any[];
patronPromise = [];
Papa.parse(data.toString(), {
header: true,
skipEmptyLines: true,
complete: result => {
result.data.forEach(x => {
x.inside = false;
x.arrived = false;
x.img = false;
x.arrivedTime = null;
const newPromise = admin.firestore()
.collection('patrons')
.add({
...x
})
patronPromise.push(newPromise);
});
}
});
return Promise.all(patronPromise)
})
.then(result=>{
//return Promise.resolve or something
})
.catch(err=>{
console.log(err)
})
}
else{
//also return if it's nothing
}
});
You're ignoring the promise that admin.storage().bucket().file('/patrons/upload.csv').download({}) returns, which means that the function may get aborted.
I think it should be closer to this:
export const uploadPatrons = functions.storage
.object()
.onFinalize((object, context) => {
let patronPromise: any[];
patronPromise = [];
if (object.name === 'patrons/upload.csv') {
return admin.storage().bucket()
.file('/patrons/upload.csv')
.download({})
.then(data => {
Papa.parse(data.toString(), {
header: true,
skipEmptyLines: true,
complete: result => {
result.data.forEach(x => {
x.inside = false;
x.arrived = false;
x.img = false;
x.arrivedTime = null;
const newPromise = admin.firestore()
.collection('patrons')
.add({
...x
})
patronPromise.push(newPromise);
});
// TODO: return the Promise.all(patronPromise) here
}
});
})
}
});

Resources