I try to split more than 2000 chars from a file, but the
{ split: true }
seem not to work, any here know what I'm doing wrong.. here my full code:
const Discord = require("discord.js");
const fs = require('fs');
const date = require('date-and-time');
const readLastLines = require('read-last-lines');
const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const now = new Date();
var settings = require("./settings.js");
var channel = require("./settings.js");
var playlist = "text.txt"
bot.on("ready", function () {
console.log("ready");
// console.log("Stream ready - Starting live Playlist...." + date.format(now, 'DD/MM/YYYY'));
// bot.channels.cache.get(settings.discord_channel).send("Stream ready - Starting live Playlist...." + date.format(now, 'DD/MM/YYYY'));
});
fs.watchFile(playlist, (eventType, filename) => {
readLastLines.read(playlist, 255)
.then((lines) => bot.channels.cache.get(settings.discord_channel).send(lines, { split: true }));
});
bot.login(settings.bot_token);
The split option for MessageOptions was removed in v13. You now have to import the Util class and use it's splitMessage() method.
You'll need to split the message into chunks and then asynchronously loop through each chunk, awaiting the sending of each.
const { Util } = require('discord.js');
// Your code
readLastLines.read(playlist, 255)
.then(async lines => {
const channel = bot.channels.cache.get(settings.discord_channel);
// Splitting and sending
const messageChunks = Util.splitMessage(lines, {
maxLength: 2000,
char: ' '
});
messageChunks.forEach(async chunk => {
await channel.send(chunk);
});
});
Related
I recently started writing Discordbots and just can't seem to get anywhere pushing the slash commands. I already have a handler file (pushSlash.js) but for some reason the commands are never loaded or I get an error in the console (mostly simply this: chalk.blue is not a function). My bot also doesn't get the badge that it supports slash commands.
Can anyone help me further?
Here is my code (pushSlash.js):
module.exports = (client) => {
const fs = require('fs');
const { PermissionsBitField } = require('discord.js');
const { Routes } = require('discord-api-types/v9');
const { REST } = require('#discordjs/rest');
const AsciiTable = require('ascii-table');
const table = new AsciiTable().setHeading('Slash Commands', 'Stats').setBorder('|', '=', "0", "0");
const TOKEN = process.env.BOT_TOKEN;
const CLIENT_ID = process.env.CLIENT_ID;
const rest = new REST({ version: '9' }).setToken(TOKEN);
import( 'chalk').then(chalk => {
const slashCommands = [];
fs.readdirSync('/home/container/src/slashCommands/').forEach(async dir => {
const files = fs.readdirSync(`/home/container/src/slashCommands/${dir}/`).filter(file => file.endsWith('.js'));
for(const file of files) {
const slashCommand = require(`/home/container/src/slashCommands/${dir}/${file}`);
slashCommands.push({
name: slashCommand.name,
description: slashCommand.description,
options: slashCommand.options ? slashCommand.options : null,
default_permission: slashCommand.default_permission ? slashCommand.default_permission : null,
default_member_permissions: slashCommand.default_member_permissions ? PermissionsBitField.resolve(slashCommand.default_member_permissions).toString() : null
});
if(slashCommand.name) {
client.slashCommands.set(slashCommand.name, slashCommand);
table.addRow(file.split('.js')[0], '✅');
} else {
table.addRow(file.split('.js')[0], '⛔');
}
}
});
console.log(chalk.blue(table.toString()));
(async () => {
try {
await rest.put(
process.env.GUILD_ID ?
Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID) :
Routes.applicationCommands(CLIENT_ID),
{ body: slashCommands }
);
console.log(chalk.green('Successfully registered application commands.'));
} catch (error) {
console.log(error);
}
})();
});
};
I've already tried everything possible, but since I'm relatively new to discord.js, I don't know that much yet either.
Actually everything should work and exactly 2 different commands should be loaded, but I only get error messages or the handler was loaded on console but nothing is displayed on Discord.
first download chalk#4.1.2 with
npm install chalk#4.1.2
and import chalk normally.
const chalk = require('chalk')
There your code modified version:
module.exports = (client) => {
const fs = require('fs');
const { PermissionsBitField } = require('discord.js');
const { Routes } = require('discord-api-types/v9');
const { REST } = require('#discordjs/rest');
const AsciiTable = require('ascii-table');
const table = new AsciiTable().setHeading('Slash Commands', 'Stats').setBorder('|', '=', "0", "0");
const TOKEN = process.env.BOT_TOKEN;
const CLIENT_ID = process.env.CLIENT_ID;
const rest = new REST({ version: '9' }).setToken(TOKEN);
// Imported chalk normally
const chalk = require('chalk')
// removed `import( 'chalk').then(chalk => {})`
const slashCommands = [];
fs.readdirSync('/home/container/src/slashCommands/').forEach(async dir => {
const files = fs.readdirSync(`/home/container/src/slashCommands/${dir}/`).filter(file => file.endsWith('.js'));
for(const file of files) {
const slashCommand = require(`/home/container/src/slashCommands/${dir}/${file}`);
slashCommands.push({
name: slashCommand.name,
description: slashCommand.description,
options: slashCommand.options ? slashCommand.options : null,
default_permission: slashCommand.default_permission ? slashCommand.default_permission : null,
default_member_permissions: slashCommand.default_member_permissions ? PermissionsBitField.resolve(slashCommand.default_member_permissions).toString() : null
});
if(slashCommand.name) {
client.slashCommands.set(slashCommand.name, slashCommand);
table.addRow(file.split('.js')[0], '✅');
} else {
table.addRow(file.split('.js')[0], '⛔');
}
}
});
console.log(chalk.blue(table.toString()));
(async () => {
try {
await rest.put(
process.env.GUILD_ID ?
Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID) :
Routes.applicationCommands(CLIENT_ID),
{ body: slashCommands }
);
console.log(chalk.green('Successfully registered application commands.'));
} catch (error) {
console.log(error);
}
})();
};
Today I tried to start my bot but I got this error :
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
[Symbol(code)]: 'CLIENT_MISSING_INTENTS'
And this is my code:
const Discord = require('discord.js'),
client = new Discord.Client(),
nodeHtmlToImage = require('node-html-to-image'),
config = require('./config.json'),
puppeteer = require('puppeteer'),
express = require('express'),
app = express()
var mime = require('mime'),
fs = require('fs'),
path = require('path')
const port = 3e3
async function nitrogenerator(e, t) {
let a = formatAMPM(new Date())
let n = formatAMPM(new Date(Date.now() - 6e4)),
o = await fs.readFileSync(`${__dirname}/testingboost.html`, 'utf8')
;(datatosend = o),
(datatosend = datatosend.replace(
'FIRSTAUTHORURL',
e.author.displayAvatarURL()
)),
(datatosend = datatosend.replace('THEFIRSTAUTHOR', e.author.username)),
(datatosend = datatosend.replace(
'SECONDAUTHORURL',
client.users.cache.random().displayAvatarURL()
)),
(datatosend = datatosend.replace('THESECONDAUTHOR', t.shift())),
(datatosend = datatosend.replace('RESPONSETONITRO', t.join(' '))),
(datatosend = datatosend.replace('FIRSTAUTHORDATE', 'Today at ' + n)),
(datatosend = datatosend.replace('SECONDAUTHORDATE', 'Today at ' + a)),
app.get('/font', function (e, t) {
const a = `${__dirname}/Whitneyfont.woff`
t.sendFile(a)
}),
app.get('/', function (e, t) {
t.send(datatosend)
})
let r = app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
const s = await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox'],
}),
i = await s.newPage()
await i.goto(`http://localhost:${port}`),
await i.waitForSelector('.scrollerInner-2YIMLh')
const d = await i.$('.scrollerInner-2YIMLh')
let c = await d.screenshot({ type: 'png' })
await s.close()
const l = new Discord.MessageAttachment(c, 'NitroProof.png')
e.channel.send(`${e.author}`, l), r.close()
}
function formatAMPM(e) {
var t = e.getHours(),
a = e.getMinutes(),
n = t >= 12 ? 'PM' : 'AM'
return (t = (t %= 12) || 12) + ':' + (a = a < 10 ? '0' + a : a) + ' ' + n
}
client.on('ready', () => {
function randomStatus() {
let status = ['ShadowWLX#0001', 'Hehe Boy'] // You can change it whatever you want.
let rstatus = Math.floor(Math.random() * status.length)
// client.user.setActivity(status[rstatus], {type: "WATCHING"});
// You can change the "WATCHING" into STREAMING, LISTENING, and PLAYING.
// Example: streaming
client.user.setActivity(status[rstatus], {
type: 'LISTENING',
url: 'https://discord.gg/MZUHeefXqx',
})
}
setInterval(randomStatus, 5000) // Time in ms. 30000ms = 30 seconds. Min: 20 seconds, to avoid ratelimit.
console.log('Online.')
})
client.on('message', async (e) => {
if ('dm' === e.channel.type) return
if (e.author.bot) return
if (0 !== e.content.indexOf(config.prefix)) return
const t = e.content.slice(config.prefix.length).trim().split(/ +/g)
'boost' === t.shift().toLowerCase() && (await nitrogenerator(e, t))
}),
client.login(config.token)
I know I need to add intents but I don't know how and what intents to add. I think I need to add the GUILD_PRESENCE intent but I don't know how to add it.
You can add intents to the Client like this-
const client = new Discord.Client({
intents: ["GUILD"] //If you want to add all intents just type 32767 instead of array
})
You must add intents in main.js, where you initialize bot.
const myIntents = new Intents();
myIntents.add(Intents.FLAGS.GUILD_PRESENCES, Intents.FLAGS.GUILD_MEMBERS);
const client = new Client({ intents: myIntents });
List of all intents
GUILDS
GUILD_MEMBERS
GUILD_BANS
GUILD_EMOJIS_AND_STICKERS
GUILD_INTEGRATIONS
GUILD_WEBHOOKS
GUILD_INVITES
GUILD_VOICE_STATES
GUILD_PRESENCES
GUILD_MESSAGES
GUILD_MESSAGE_REACTIONS
GUILD_MESSAGE_TYPING
DIRECT_MESSAGES
DIRECT_MESSAGE_REACTIONS
DIRECT_MESSAGE_TYPING
GUILD_SCHEDULED_EVENTS
The problem is that I couldn't figure out a way to make this command only accessible by admins. I've tried using if statements, however, I failed. message. I am not sure if member. roles. cache. has( ' 732524984777572363 ' ) would allow members with the role ID 732524984777572363 to execute it since there's already an if statement.
const Discord = require('discord.js');
const fs = require('fs');
const cooldown = new Set();
module.exports.run = async (client, msg, args, config) => {
if(cooldown.has(msg.author.id)) {
msg.reply(`You need to wait ${config.COOLDOWN} minutes to use this command again!`)
.then((m) => {
msg.delete();
setTimeout(() => {
m.delete();
}, 5000);
});
} else {
fs.readFile('./accounts/crunchy.txt', 'utf8', function(err, data) {
if (err) throw err;
data = data + '';
var lines = data.split('\n');
let account = lines[Math.floor(Math.random() * 1)];
fs.writeFile('./accounts/crunchy.txt', lines.slice(1).join('\n'), function(err) {
if(err) throw err;
});
let embed = new Discord.RichEmbed()
.addField('Rate Us Here | قيمنا هنا ', `<#915***********80>`)
.addField('CrunchyRoll Account',`\n**${account}**`)
.setThumbnail('**************************')
.setColor("#363940")
.setFooter('Bot made by ******')
.setTimestamp();
msg.author.send(embed);
msg.reply('I\'ve sent you the account! Please check your DM!')
.then(m => {
setTimeout(() => {
m.delete();
}, 900000);
});
cooldown.add(msg.author.id);
setTimeout(() => {
cooldown.delete(msg.author.id);
}, config.COOLDOWN * 60 * 1000);
});
}
};
module.exports.help = {
name: `CrunchyRoll`,
description: `Sends you a CrunchyRoll account!`
};```
Simply adding a role check and a server check will prevent any issues!
The first line would be:
if(!msg.guild) return;
This line makes sure the user is running the command in a server(guild), this prevents a member role from being undefined or null.
The second line would be:
if(!msg.author.roles.cache.has('ROLE_ID_HERE')) return;
This prevents a user from running a command if they do not have a specific role.
The final code would be:
if(!msg.guild) return;
if(!msg.author.roles.cache.has('ROLE_ID_HERE')) return;
You will need to add this to the top of your code in order for it to work as you'd like.
const Discord = require('discord.js');
const fs = require('fs');
const cooldown = new Set();
module.exports.run = async (client, msg, args, config) => {
if(!msg.guild) return;
if(!msg.member.roles.cache.has('ROLE_ID_HERE')) return;
if(cooldown.has(msg.author.id)) {
msg.reply(`You need to wait ${config.COOLDOWN} minutes to use this command again!`)
.then((m) => {
msg.delete();
setTimeout(() => {
m.delete();
}, 5000);
});
} else {
fs.readFile('./accounts/crunchy.txt', 'utf8', function(err, data) {
if (err) throw err;
data = data + '';
var lines = data.split('\n');
let account = lines[Math.floor(Math.random() * 1)];
fs.writeFile('./accounts/crunchy.txt', lines.slice(1).join('\n'), function(err) {
if(err) throw err;
});
let embed = new Discord.RichEmbed()
.addField('Rate Us Here | قيمنا هنا ', `<#915***********80>`)
.addField('CrunchyRoll Account',`\n**${account}**`)
.setThumbnail('**************************')
.setColor("#363940")
.setFooter('Bot made by ******')
.setTimestamp();
msg.author.send(embed);
msg.reply('I\'ve sent you the account! Please check your DM!')
.then(m => {
setTimeout(() => {
m.delete();
}, 900000);
});
cooldown.add(msg.author.id);
setTimeout(() => {
cooldown.delete(msg.author.id);
}, config.COOLDOWN * 60 * 1000);
});
}
};
module.exports.help = {
name: `CrunchyRoll`,
description: `Sends you a CrunchyRoll account!`
};
I'm creating a React Native application. I want to create an image array because I need to upload them to the server. But when I upload multiple images they are not storing like an array. every time the imagesQueue array has only one image.
my code as follows.
const [filePath, setFilePath] = useState({
imagesQueue: []
});
const chooseFile = () => {
const options = {
title: 'Select an option',
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.showImagePicker(options, (response) => {
// console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else {
// let source = response;
// You can also display the image using data:
let source = {
uri: 'data:image/jpeg;base64,' + response.data
};
setFilePath({
...filePath,
imagesQueue: [source],
});
console.log("stored item : " + filePath.imagesQueue);
}
});
};
How to store multiple images in the same state. Thanks in advance.
the data probably will store in formData - it's easy format for later passing it to BE.
firstly You need store somewhere those data:
const [selectedFiles, setSelectedFiles] = useState([]);
Later there is possibility to use .concat() - that function connects 2 arrays:
setSelectedFiles(((prevState) => prevState.concat(fileData)));
And in the last step, You need to pass those data to Your form:
const formData = new FormData();
for (let i = 0; i < selectedFiles.length; i++) {
formData.append('Files', selectedFiles[i].File);
}
I'm trying to make a 'random meme' command for my Discord Bot. I'm new to working with APIs, but I've tried my best.
The problem is, when I type the command, nothing happens. There are no errors, but the bot doesn't send anything in discord.
This is my code:
if (command === "meme")
async (client, message, args) => {
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
const img = await randomPuppy(random);
const embed = new Discord.MessageEmbed()
.setColor(16776960)
.setFooter("test")
.setImage(img)
.setTitle(`Random Meme requested by <#${message.author.tag}>`)
.setURL(`https://reddit.com/r/${random}`)
message.channel.send(embed);
}
Here Is One That Will Show Info About The Meme
if(command === "meme") {
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
try {
const { body } = await snekfetch
.get('https://www.reddit.com/r/${random}.json?sort=top&t=week')
.query({ limit: 800 });
const allowed = message.channel.nsfw ? body.data.children : body.data.children.filter(post => !post.data.over_18);
if (!allowed.length) return message.channel.send('It seems we are out of memes');
const randomnumber = Math.floor(Math.random() * allowed.length)
const embed = new Discord.RichEmbed()
.setColor(0x00A2E8)
.setTitle(allowed[randomnumber].data.title)
.setDescription("Posted by: " + allowed[randomnumber].data.author)
.setImage(allowed[randomnumber].data.url)
.addField("Other info:", "Up votes: " + allowed[randomnumber].data.ups + " / Comments: " + allowed[randomnumber].data.num_comments)
.setFooter("r/" + random)
message.channel.send(embed)
} catch (err) {
return console.log(err);
}
}
Let Me Know If It Don't Work, But I Should
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === "meme") {
async (client, message, args) =>
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
const img = await randomPuppy(random);
const embed = new Discord.MessageEmbed()
.setColor(16776960)
.setFooter("test")
.setImage(img)
.setTitle(`Random Meme requested by <#${message.author.tag}>`)
.setURL(`https://reddit.com/r/${random}`)
message.channel.send(embed);
}
});
This should work, not quite sure, haven't tested it. (You can put in a command handler your self)
if (command === "meme")
async (client, message, args) => {
const fetch = require('node-fetch');
let userAvatar = message.author.avatarURL({ format: "png", dynamic: true, size: 2048 }); // this is just the users icon, u can remove it if you want.
fetch(`https://meme-api.herokuapp.com/gimme`)
.then(res => res.json())
.then(async json => {
const embed = new MessageEmbed()
.setAuthor(`${json.title}`, `${userAvatar + "?size=2048"}`, `${json.postLink}`)
.setImage(`${json.url}`)
.setFooter(`👍${json.ups} | ${json.subreddit}`)
.setColor("RANDOM")
message.channel.send(embed).catch((error) => {
console.log("An error has occured on the \"meme\" command\n", error)
})
}
Here you go! I've tested this on my own command handler.