I have a problem I almost resolved but i'm now stuck.
I want to make my bot send a message in a channel at mirror hours (00h00, 01h01, 02h02...) for a running gag with my friends and currently I made this:
At the top of my code I have var currentdate = new Date();
And then, later in my source code:
if(currentdate.getMinutes() == currentdate.getHours())
{
bot.channels.get('SPECIFICCHANNELID').send('Touchez votre nez :nose:');
}
It's sort of working since the message is sent by the bot in the right channel, but the message is only sent when the bot detects a message, so if during any mirror hour, no one send a message, then the bot will not send anything.
And if there is multiples messages during this interval of time, the bot will also send the message multiple times, of course I want it to send the message only 1 time for exemple at 11:11:00.
Thank you for the help and sorry if my english is bad !
You need to be checking at some interval whether or not to send a message.
Something like setInterval would work.
setInterval(function(){
if(currentdate.getMinutes() == currentdate.getHours())
{
bot.channels.get('SPECIFICCHANNELID').send('Touchez votre nez :nose:');
}
}, MIN_INTERVAL)
You want MIN_INTERVAL to be the minimum amount of time in milliseconds to check for sending messages.
If you want to check every minute
const MIN_INTERVAL = 1000 * 60
You have to use if statement and you didn't specified hour or minutes, so the bot can't send message.
async function verifyTime() {
var d = new Date();
if (d.getHours() == d.getMinutes()) {
//your code goes here
} catch (error) {
console.log(error);
}
setTimeout(() => {
verifyTime();
}, 61 * 1000);
} else {
setTimeout(() => {
verifyTime();
}, 1000);
}
}
client.login(token);
//⬇ remember to place this under your client.login
setTimeout(() => {
verifyTime();
}, 5000);
Related
I've been trying to take advantage of the Binance Websocket to trigger buys and sells based on the live price with my own logic. I know the WebSocket is sending back live data and there might be even 5-6 or more responses at the same time, but how do I make sure I get only 1 when I close the Websockets?
I am trying to make sure it will trigger only 1 buy or 1 sell when that happens.
I am using: (works great)
'node-binance-api'
The Websocket starts from here:
binance.websockets.bookTickers('BNBBUSD', (mainTicker) => {
var priceNow = mainTicker.bestBid;
liveStrategy(priceNow).then(isSold => {
// console.log('THIS IS WHEN IS CHECKED ->>>>>>');
if (isSold == true) {
console.log('JUST SOLD -> Setting the count to 10');
sleep(3000).then(() => {
console.log("Countdown finished: ", count);
profitCalculations(mainCurrency);
count = 10;
});
}
if (isSold == false) {
console.log('THIS WAS A BUY ->');
count = 10;
}
}).catch((isSoldErr) => {
console.warn('Error:', isSoldErr.message);
dumpError(isSoldErr);
});
});
The price is being sent back into the function, this function runs continuously until a buy or a sell happens. Before triggering a buy or a sell I close the WebSocket with:
let endpoints = binance.websockets.subscriptions();
for ( let endpoint in endpoints ) {
console.log("..terminating websocket: "+endpoint);
let ws = endpoints[endpoint];
ws.terminate();
}
This code stops the WebSocket, but it does take about 3 seconds so I trigger the buy/sell after this like:
if (priceNow > buyPrice) {
terminateAllWebsockets();
return new Promise((resolve) => {
sleep(5000).then(sleep => {
marketBuyFromNoLossStrategyAmount(buySymbol,buyAmount);
resolve(false);
})
})
}
When it returns it basically sends back to my liveStrategy(priceNow) to trigger the profit calculations. The profitCalculations(mainCurrency); might get triggered 3-4 times or even the buy or sell. Is it something that I can do for that not to happen? So the profit or the buy & sell will trigger only once? How do I make sure that happens with my setup?
Any thoughts are most welcome!
The main problem was that the WebSocket was real-time and when 2 or more trades were getting executed at the same time reaching the target set in the algorithm, it would trigger multi-buy or multi-sell. Writing the data within a public variable and reading with a simple timer that executed the function every second was the best solution.
I am making a Google Assistant Discord bot, but I want to know how your bot will reply to your second message. For example:
first, you say hey google, then the bot says I'm listening, and then you say what time is it and he says 2.40 pm.
I did the first part but I don't know how to make it replying to the second argument. Can someone help me with it?
You can use a message collector. You can send an I'm listening message and in the same channel set up a collector using createMessageCollector.
For its filter, you can check if the incoming message is coming from the same user who want to ask your assistant.
You can also add some options, like the maximum time the collector is collecting messages. I set it to one minute, and after a minute it sends a message letting the user know that you're no longer listening.
client.on('message', async (message) => {
if (message.author.bot) return;
if (message.content.toLowerCase().startsWith('hey google')) {
const questions = [
'what do you look like',
'how old are you',
'do you ever get tired',
'thanks',
];
const answers = [
'Imagine the feeling of a friendly hug combined with the sound of laughter. Add a librarian’s love of books, mix in a sunny disposition and a dash of unicorn sparkles, and voila!',
'I was launched in 2021, so I am still fairly young. But I’ve learned so much!',
'It would be impossible to tire of our conversation.',
'You are welcome!',
];
// send the message and wait for it to be sent
const confirmation = await message.channel.send(`I'm listening, ${message.author}`);
// filter checks if the response is from the author who typed the command
const filter = (m) => m.author.id === message.author.id;
// set up a message collector to check if there are any responses
const collector = confirmation.channel.createMessageCollector(filter, {
// set up the max wait time the collector runs (optional)
time: 60000,
});
// fires when a response is collected
collector.on('collect', async (msg) => {
if (msg.content.toLowerCase().startsWith('what time is it')) {
return message.channel.send(`The current time is ${new Date().toLocaleTimeString()}.`);
}
const index = questions.findIndex((q) =>
msg.content.toLowerCase().startsWith(q),
);
if (index >= 0) {
return message.channel.send(answers[index]);
}
return message.channel.send(`I don't have the answer for that...`);
});
// fires when the collector is finished collecting
collector.on('end', (collected, reason) => {
// only send a message when the "end" event fires because of timeout
if (reason === 'time') {
message.channel.send(
`${message.author}, it's been a minute without any question, so I'm no longer interested... 🙄`,
);
}
});
}
});
I am new in this world and I am trying things.
I was trying to build a timer bot... And now I have a little problem, I would like to stop my timer whenever I want.
bot.on('message', message => {
let timer = setInterval(() => {
if (message.content.startsWith('!start'))
message.channel.send("I print something");
}, 10 * 1000)
if (message.content.startsWith('!stop')) {
message.channel.send("Interaval Cleared");
clearInterval(timer);
}})
When I type !stop in my discord channel, it displays me the message but it doesn't stop my timer... I tried with a return; but it didn't work.
Could you help me please ?
Thanks,
Have a good day !
You're starting a new interval each time you run the function. Also, your timer value is scoped to each function call, and not "shared" between calls, you need to make it available between them. The behavior you want should look something like this instead:
bot = {}
bot.timer = 0; // ensures clearInterval doesn't throw an error if bot.timer hasn't been set
bot.listen = message =>{
if(message == 'start'){
clearInterval(bot.timer); // stops the interval if it been previously started
bot.timer = setInterval(()=>console.log('I print something'),1000)
}
if(message == 'stop') clearInterval(bot.timer);
}
I want my bot to give coins to members that spent 1 minute in any voice channel. When I'm sitting in voice channel it's working good, but if I am quitting a channel, the bot still gives me 1 coin per minute. What did I do wrong?
I tried to stop a function when the user leaves a channel, tried to clear a timeout function, but it's still working that way:
bot.on("voiceStateUpdate",(oldMember,newMember)=>{
let nuc = newMember.voiceChannel
if(nuc !== undefined){
function smth() {
setTimeout(function coin() {
db.add(`money_${newMember.id}`, 1)
setTimeout(coin, 60000);
}, 60000)}
smth()
newMember.send('You're in voicechannel')
} else {
return newMember.send('You're out of voicechannel')
}
})
Does anyone know how to check if someone is sending the same message two times in the same channel, in an interval of 5 seconds (there may be other messages from other people between the two messages) ?
(I'm new with Javascript and Discord.js)
If someone could help me, it would be great.
You can use TextChannel.awaitMessages()
client.on('message', message => {
// this function can check whether the content of the message you pass is the same as this message
let filter = msg => {
return msg.content.toLowerCase() == message.content.toLowerCase() && // check if the content is the same (sort of)
msg.author == message.author; // check if the author is the same
}
message.channel.awaitMessages(filter, {
maxMatches: 1, // you only need that to happen once
time: 5 * 1000 // time is in milliseconds
}).then(collected => {
// this function will be called when a message matches you filter
}).catch(console.error);
});