So I created a poll command, but when I type in the command, there are commas between each word.
exports.run = async (bot, message, args) => {
let text = message.content.slice('__poll'.length);
if (!args) return message.reply("You must have something to vote for!")
message.channel.send(`:ballot_box: ${message.author.username} started a poll! React to my next message to vote on it. :ballot_box: `);
const pollTopic = await message.channel.send(`${args}`);
pollTopic.react(`✅`);
pollTopic.react(`⛔`);
};
when I want the question to be What is up, this happens
what,is,up!
By default, when translating an array into a string, JavaScript will separate each element by a comma. To change the delimiter, you can use Array.join().
Example:
const arr = ['How', 'are', 'you?'];
console.log(`Original: ${arr}`);
const str = arr.join(' ');
console.log(`Joined: ${str}`);
Related
in a scenario, WalletA is receiving TokenB in a regular basis from AddressC.
AddressC only sends TokenB, nothing else.
in etherscan or bscscan it is simple to see how much of TokenB is received in WalletA and "from" field is there so you can do some math to get total.
How can this be done using web3? I couldn't find any relevant api call in web3 documents.
I can get total balance of TokenB in WalletA by web3.js but I need the count of tokens only sent from AddressC.
Thanks.
As per the ERC-20 standard, each token transfer emits a Transfer() event log, containing the sender address, receiver address and token amount.
You can get the past event logs using the web3js general method web3.eth.getPastLogs(), encode the inputs and decode the outputs.
Or you can supply ABI JSON of the contract (it's enough to use just the Transfer() event definition in this case) and use the web3js method web3.eth.Contract.getPastEvents(), which encodes the inputs and decodes the outputs for you based on the provided ABI JSON.
const Web3 = require('web3');
const web3 = new Web3('<provider_url>');
const walletA = '0x3cd751e6b0078be393132286c442345e5dc49699'; // sender
const tokenB = '0xdAC17F958D2ee523a2206206994597C13D831ec7'; // token contract address
const addressC = '0xd5895011F887A842289E47F3b5491954aC7ce0DF'; // receiver
// just the Transfer() event definition is sufficient in this case
const abiJson = [{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}];
const contract = new web3.eth.Contract(abiJson, tokenB);
const fromBlock = 10000000;
const toBlock = 13453500;
const blockCountIteration = 5000;
const run = async () => {
let totalTokensTranferred = 0;
for (let i = fromBlock; i <= (toBlock - blockCountIteration); i += blockCountIteration) {
//console.log("Requesting from block", i, "to block ", i + blockCountIteration - 1);
const pastEvents = await contract.getPastEvents('Transfer', {
'filter': {
'from': walletA,
'to': addressC,
},
'fromBlock': i,
'toBlock': i + blockCountIteration - 1,
});
}
for (let pastEvent of pastEvents) {
totalTokensTranferred += parseInt(pastEvent.returnValues.value);
}
console.log(totalTokensTranferred);
}
run();
i have this reaction role system everything works up to the last part where the coulour slection happens
async run(message, client, con) {
await message.channel.send("Give the color for the embed.")
answer = await message.channel.awaitMessages(answer => answer.author.id === message.author.id,{max: 1});
var color = (answer.map(answers => answers.content).join()).toUpperCase()
if(color.toUpperCase()==='CANCEL') return (message.channel.send("The Process Has Been Cancelled!"))
function embstr(){
var finalString = '';
for(var i =0;i<n;i++){
finalString += b[i]+ ' - '+a[i] +'\n';
}
return finalString;
}
const botmsg = message.client.channels.cache.get(channel => channel.id === reactChannel)
const embed = new MessageEmbed()
.setTitle(embtitle)
.setColor(color)
.setDescription(embstr());
botmsg.send(embed);
message.channel.send("Reaction Role has been created successfully")
here is the error message
{
"stack": "TypeError: Cannot read property 'send' of undefined
at SlowmodeCommand.run (B:\\stuff\\Downloads\\Admeeeeeen bot\\src\\commands\\reactionroles\\createreactionrole.js:100:22)
at processTicksAndRejections (node:internal/process/task_queues:93:5)"
}
The .get() method takes in a snowflake as its parameter. AKA an ID of a certain object. It is not an iterator, meaning that what you're currently attempting to do is not right JavaScript wise.
Instead of passing in a parameter to represent a channel object, we'll just want to pass in the ID of the channel that we'd like to get. Alternatively, you could replace .get() with .find() there, which is in fact an iterator that uses this form of a callback, although it's insufficient in our case considering we can just use .get() which is more accurate when it comes to IDs.
/**
* Insufficient code:
* const botmsg = message.client.channels.cache.find(channel => channel.id === reactChannel)
*/
const botmsg = message.client.channels.cache.get(reactChannel /* assuming that reactChannel represents a channel ID */)
I want to make it so that if I do [prefix] [command] it will give the same effect as [mention bot] [command] but the way I create commands and args makes that difficult:
The prefix is stored as var prefix = '!3';
And this is how I create commands:
bot.on('message', msg => {
if (!msg.content.startsWith(prefix) || msg.author.bot)
return;
//the first message after '!13 '
//!
let args = msg.content.toLowerCase().substring(prefix.length).split(" ");
//^
//any capitalisation is allowed (ping,Ping,pIng etc.)
switch(args[1]) {
case 'ping': //if user inputs '!3 ping'
msg.channel.send('Pong!') //send a message to the channel 'Pong!'
}//switch (command) ends here
};//event listener ends here
You can have a list of predefined prefixes and loop over that to determine if the msg has a prefix from that list.
let prefixList = ['!31 ', '!asdf ', `<#${bot.user.id}> `, `<#!${bot.user.id}> `]
function hasPrefix(str) {
for(let pre of prefixList)
if(str.startsWith(pre))
return true;
return false;
}
<#${bot.user.id}> , <#!${bot.user.id}> will set up bot mention as a prefix.
Here's the shorter version of secretlyrice's answer:
const startsWithPrefix = (command) =>
['!prefix1 ', '!prefix2', <#botId>, <#!botId>].some(p => command.startsWith(p))
Nice code, but change it 1 to 0
switch(args[0]) {
case 'ping': //if user inputs '!3 ping'
msg.channel.send('Pong!') //send a message to the channel 'Pong!'
}
I assume you are running on an older version of Discord.js cause if you are using v13 message is depricated and should be messageCreate but this is what I used when I wasn't using slash commands.
const escapeRegex = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const prefix = '!'
bot.on('message', async msg => {
const prefixRegex = new RegExp(`^(<#!?${bot.user.id}>|${escapeRegex(prefix)})\\s*`)
if (!prefixRegex.test(message.content)) return
// checks for bot mention or prefix
const [, matchedPrefix] = message.content.match(prefixRegex)
const args = message.content.slice(matchedPrefix.length).trim().split(/ +/)
// removes prefix or bot mention
const command = args.shift().toLowerCase()
// gets command from next arg
if (command === 'ping') {
msg.channel.send('Pong!')
}
})
I'm trying to create a discord.js announcement bot ex. When I write ?Ann Hello Guys the bot delete my message and send Hello Guys but now if I write ?Ann Hello Guys the bot delete my message and send ?Ann Hello Guys the code is this
const client = new Discord.Client();
client.login('--------------');
const PREFIX = '?';
client.once('ready', () => {
console.log('Questo bot e online!');
});
client.on('message', message=>{
let args = message.content.slice(PREFIX.length).split(' ');
switch(args[0]){
case 'ann':
const embed = new Discord.MessageEmbed()
.addField('test', message.content );
message.channel.send(embed);
break;
}
})
Made a pen for this:
https://codepen.io/herbievine/pen/YzwNewQ
client.on('message', message=>{
let args
if (message.startsWith('?'))
args = message.content.replace('?', '').split(' ')
if (args[0].toLowerCase() === 'ann') {
const embed = new Discord.MessageEmbed()
.addField('test', message.contentreplace('?ann', ''));
message.channel.send(embed);
}
}
})
Hope it helps
message.content represents the whole message that you are sending, so in this case will be ?Ann Hello Guys.
DiscordJS doesn't understand what commands are, and it doesn't split this stuff out for you.
As your message is formatted as ?Mention <Command arguments here> you can split it via the space within the string.
let messageContent = message.content.split(" ")
This takes your string of "?Ann Hello Guys" and turns it into "?Ann", "Hello", "Guys"
.split(" ") separates your string via the spaces, and returns an array.
You can then do messageContent.pop() to remove the first element in the array, which is "?Ann".
You can then .join(" ") these back together, forming the string "Hello Guys" and send that. Fully formed code:
let splitMessage = message.content.split(" ")
splitMessage.pop();
const transformedMessage = splitMessage.join(" ")
so i'm trying this 8ball bot, and everything is working fine, but i can't get how can i leave in the condition that only when the bot get "!verda arg1 arg2" it answers one of the replies in the array.
meanwhile my condition is if the user type the prefix "!verda" only, it replies , i want to include the argument too in the condition
const Discord = require("discord.js");
const client = new Discord.Client();
const cfg = require("./config.json");
const prefix = cfg.prefix;
client.on("message", msg => {
if (!msg.content.startsWith(prefix) || msg.author.bot) return;
const args = msg.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase;
if (msg.content === prefix){
let replies = [
"Yes.",
"No.",
"I don't know.",
"Maybe."
];
let result = Math.floor((Math.random() * replies.length));
msg.channel.send(replies[result]);
}
else if (msg.content === "!help"){
msg.channel.send("I have only 1 command [!verda]");
}
})
client.login(cfg.token);
const command = args.shift().toLowerCase;
toLowerCase is a function and therefore should be
const command = args.shift().toLowerCase();
By doing msg.content === prefix, you are checking if the whole content of the message is equal to that of cfg.prefix
if(msg.content.startsWith(`${prefix}8ball`) {
}
The answer was simple as i figured it out, i simply had to join the spaces
if (msg.content === `${prefix} ${args.join(" ")}`)