I have a few pictures, all on imgur with direct image link (format: https://i.imgur.com/XXXXXX.jpg), and a Discord bot made with NodeJS.
I send messages like this:
bot.sendMessage({
to: channelID,
message: "My Bot's message"
});
I have tried this:
bot.sendMessage({
to: channelID,
message: "My Bot's message",
file: "https://i.imgur.com/XxxXxXX.jpg"
});
but I only get the text. I have looked it up, and this question was the only one to even come close to saying what I need to do, and it didn't work.
So how am I supposed to do this?
Here is how the bot is created:
var bot = new Discord.Client({
token: auth.token,
autorun: true
});
bot.on('ready', function (evt) {
logger.info('Connected');
logger.info('Logged in as: ');
logger.info(bot.username + ' - (' + bot.id + ')');
});
bot.on('message', function (user, userID, channelID, message, evt) {
// My code
}
ClientUser.sendMessage is deprecated, as is the file parameter in its options. You should be using Channel.send(message, options), with files as an array of strings or FileOptions.
bot.on('messageCreate' message => {
message.channel.send("My Bot's message", {files: ["https://i.imgur.com/XxxXxXX.jpg"]});
});
If you want to stick to your deprecated methods, ClientUser.sendFile might be something of interest to you, though I do recommend you move over to the stuff that's more current.
You can send local files in v11.2 like this:
var Discord = require('discord.js');
var bot = new Discord.Client();
bot.on('message', message => {
var prefix = '!'
var msg = message.content;
if (msg === prefix + 'image') {
message.channel.send('Message that goes above image', {
files: [
"./image-to-send.png"
]
});
}
});
bot.login('TOKEN');
Since this is one of the top results on google in 2019, I'm adding the new method of how to upload files with discord.io
First thing that's different is the on() function takes some additional parameters.
Next is that there's a new method called uploadFile that takes an uploadFileOpts object. the file can take a string that is a local path from your bot file to the image.
uploadFileOpts = {
to: string,
file: string|Buffer,
filename?: string,
message?: string
}
So, if you place your image next to your bot script, your code should look like this
bot.on('message', function (user, userID, channelID, message, evt) {
bot.uploadFile({
to: channelID,
file: 'myImage.jpg'
});
}
If you still want to snag that image from the internet, you'll need to convert it into a Buffer object. However, storing the file locally is simpler.
If you're using discord.io instead of Discord.js, refer to this syntax:
https://izy521.gitbooks.io/discord-io/content/Methods/Channels.html
I'm still trying to get it to work.
Related
Now, before you say that this has been posted before, I have a different situation.
With that out of the way, let's get on with the question.
I am making a Discord bot for a friend that does duties for the group and things like that.
Quick note too, I am using the Sitepoint version of Discord.JS because I'm a beginner.
I want the bot to send a message to a certain channel when the show gets canceled for a reason. For example, they would send something like this:
afv!cancel Roblox went down.
or something similar.
But every time it sends a message, every space turns into a comma like this:
:x: The show has been cancelled because: "Roblox,went,down.". Sorry for that!
Here's the index.js code that handles executing commands:
bot.on('message', msg => {
const args = msg.content.split(/ +/);
const command = args.shift().toLowerCase();
const prefix = command.startsWith("afv!");
if (prefix == true) {
console.info(`Called command: ${command}`);
if (!bot.commands.has(command)) return;
msg.delete(1);
try {
bot.commands.get(command).execute(msg, args, bot);
} catch (error) {
console.error(error);
msg.reply('there was an error trying to execute that command!');
};
And the cancelled.js file:
module.exports = {
name: 'afv!cancel',
description: "in-case the show gets cancelled",
execute(msg, args, bot) {
if (msg.member.roles.find(r => r.name === "Bot Perms")) {
const reason = args.replace(/,/g, " ");
bot.channels.get('696135370987012240').send(':x: **The show has been cancelled** because: "' + args + '". *Sorry for that!*');
bot.user.setActivity("AFV! | afv!help", { type: 'PLAYING' });
} else {
msg.reply('you are missing the role: Bot Perms!');
}
},
};
By the way, upon executing the command, it prints this:
TypeError: args.replace is not a function
Thanks for reading! :)
From what I can see, here
const reason = args.replace(/,/g, " ");
bot.channels.get('696135370987012240').send(':x: **The show has been cancelled** because: "' + args + '". *Sorry for that!*');
you are making a const reason, wherein you try to handle that as a string and replace all commas with spaces. Unfortunately, even though it can be displayed in a string and looks to be one, in reality it is an array, so replace() won't work on it. To be able to use replace() you need to first transform your array to an actual string:
const reason = args.join().replace(/,/g, " ");
With that done you won't be seeing this pesky "not a function" error, and you can easily use reason to display your message:
bot.channels.get('696135370987012240').send(':x: **The show has been cancelled** because: "' + reason + '". *Sorry for that!*');
So, I'm creating the bot for my Discord channel. I created a special system based on requests. For example, the user sends a request to be added to the chat he wants. Each request is paired with a unique ID. The request is formed and sent to the service channel where the moderator can see those requests. Then, once the request is solved, moderator types something like .resolveRequest <ID> and this request is copied and posted to 'resolved requests' channel.
There is some code I wrote.
Generating request:
if (command === "join-chat") {
const data = fs.readFileSync('./requestID.txt');
let requestID = parseInt(data, 10);
const emb = new Discord.RichEmbed()
.setTitle('New request')
.setDescription('Request to add to chat')
.addField('Who?', `**User ${msg.author.tag}**`)
.addField('Which chat?', `**Chat: ${args[0]}**`)
.setFooter('Request\'s ID: ' + requestID)
.setColor('#fffb3a');
let chan = client.channels.get('567959560900313108');
chan.send(emb);
requestID++;
fs.writeFileSync('./requestID.txt', requestID.toString(10));
}
Now the .resolveRequest <ID>:
if (command === '.resolveRequest') {
msg.channel.fetchMessages({limit : 100}) //getting last 100 messages
.then((messages) => messages.forEach(element => { //for each message get an embed
element.embeds.forEach(element => {
msg.channel.send(element.fields.find('value', args[0].toString(10))); //send a message containing the ID mentioned in 'args[0]' that was taken form the message
})
}));
}
.join-chat <chat_name> works flawlessly, but .resolveRequest <ID> does't work at all, even no errors.
Any way to fix it?
Using .find('value', 'key') is deprecated, use .find(thing => thing.value == 'key') instead.
Also you should use a DataBase to store things, but your Code actually is not broken, its just that you check for: command === '.resolveRequest', wich means you need to run ..resolveRequest, as in the command variable the prefix gets cut away so change that to: command === 'resolveRequest'
I have never coded a Discord Bot before but am familiar with Javascript so I figured I would give it a shot. I used the beginner files from this site Digital Trends but am running into some issues.
I have the bot running in my server and the basic command swapped from "!" to "?" and the included command "?ping" does return the expected response "Pong!"
I run a server where we start a video game each month and play through while discussing it along the way, similar to a book club. So I'm trying to create a channel where people can suggest a game using a bot command since I don't trust they could handle following simple rules on their own.
What I'm trying to figure out is how to go about taking a user command of:
?gs "Video Game Title" "Platform"
And having the bot delete the command and repost as:
#user suggested Video Game Title for Platform
While also adding reaction emojis "👍" and "👎" to allow other users to vote.
I'm not asking for anyone to do this for me, but to simply help point me in the right direction of how to code this with Discord in mind using JS (if possible)
Here is my current "bot.js" code:
var Discord = require('discord.io');
var logger = require('winston');
var auth = require('./auth.json');
// Configure logger settings
logger.remove(logger.transports.Console);
logger.add(new logger.transports.Console, {
colorize: true
});
logger.level = 'debug';
// Initialize Discord Bot
var bot = new Discord.Client({
token: auth.token,
autorun: true
});
bot.on('ready', function (evt) {
logger.info('Connected');
logger.info('Logged in as: ');
logger.info(bot.username + ' - (' + bot.id + ')');
});
bot.on('message', function (user, userID, channelID, message, evt) {
// Our bot needs to know if it will execute a command
// It will listen for messages that will start with `!`
if (message.substring(0, 1) == '?') {
var args = message.substring(1).split(' ');
var cmd = args[0];
args = args.splice(1);
switch(cmd) {
// !ping
case 'ping':
bot.sendMessage({
to: channelID,
message: 'Pong!'
});
break;
// Just add any case commands if you want to..
}
}
});
args = args.splice(1);
This line is incorrect, args (being a string) has no .splice() method. (I often get .slice() and .split() confused, so this happens to me a lot too!)
Instead, use:
args = args.split(" ").slice(1);
I have recently created a bot for my discord server. Now I want him to filter bad words.
For example:
User (without bot): You are an asshole
User (with bot): You are an [I'm stupid because I swear]
Is this even possible in Discord? I have given my bot all permissions! (including removing messages, it can't edit message with the program self tho)
If that is not possible^ Can we do the following?
The ability to directly delete the message and write the following:
Bot: #username Do not swear!
Now I have the following code (I dont know if useful):
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log('Hello, the bot is online!')
});
client.on('message', message => {
if(message.content === '--Trump'){
message.reply('He is the president of the United States of
America!');
}
if(message.content === '--Putin'){
message.reply('He is the president of Russia!');
}
});
client.login('MzAwMzM5NzAyMD*1NDUxNzc4.C8rH5w.M44LW*nrfbCR_zHzd**vtMqkr6nI');
Docs. Currently in the Discord API there is no possible way to edit a message from another user. You could completely delete the message or you could resend it but edited. If you want to resend it then you could use:
let censor = "[Sorry, I Swear]"; /* Replace this with what you want */
client.on('message', message => {
let edit = message.content.replace(/asshole/gi, censor);
message.delete();
message.channel.send(`${message.author.username}: ${edit}`);
}
Input >>> Hello asshole
Output <<< AkiraMiura: Hello [Sorry, I Swear]
Take note that if the user sends a 2000 byte (Charater) long message you won't be able to send a fixed version and it would just get deleted.
Use Regex to help you detect from blacklisted words you wanted to.
For example, If you want to blacklist the word asshol*, use the regex to detect the word:
if ((/asshole/gm).test(message.content))
message.delete().then(() => {
message.reply('Do not swear!'); // Sends: "#user1234 Do not swear!"
});
}
If you wanted to blacklist/filter MULTIPLE words, like fu*k and sh*t
Use separators in Regex: /(word1|word2|word3)/gm
So... use:
if ((/(fuck|shit)/gm).test(message.content)) {
message.delete().then(() => {
message.reply('Do not swear!');
});
}
It's fully working!
Re-write in FULL code,
client.on('message', (message) => {
if ((/asshole/gm).test(message.content)) {
message.delete().then(() => {
message.reply('Do not swear!'); // Sends: "#user1234 Do not swear!"
});
}
});
Tell me if it works
Good Luck,
Jedi
try:
client.on('message', message => {
message.edit(message.content.replace(/asshole/gi, "[I'm stupid because I swear]"))
.then(msg => console.log(`Updated the content of a message from ${msg.author}`))
.catch(console.error);
});
credit to #André Dion for bringing up the right method from the API
After looking through the documentation of Botkit I don't see a way for a bot to initiate a message to a channel by itself at a certain time. What I've tried doing is providing a callback function to the .startRTM function that does what I want it to do at certain times, however the calls are asynchronous to retrieve information from another API. Is there a better way to approach this than sticking everything in a while(1) {} call? If not, how can I get the r.getHot callback to succeed because JS is running on the main thread so it'll skip over the callback function. The variable r is from the snoowrap library.
var bot = controller.spawn({
token: process.env.slacktoken,
incoming_webhook: {
url: process.env.webhookurl
}
}).startRTM(function(err, bot, payload) {
if (!err) {
while(1){
for (var i = 0; i < allowableTimes.length; i++) {
if (new Date().getTime() == allowableTimes[i].getTime()) {
r.getHot('aww', {limit: 1}).then(function(res){
var url = res[0].url;
var title = res[0].title;
console.log(url);
console.log(title);
bot.sendWebhook({
username: "bawwt",
icon_emoji: ":smile_cat:",
text: "<" + url + "|" + title + ">",
channel: "#random"
});
});
}
}
}
}
});
Ahh, I misread your question at first
I'd suggest looking into node-schedule. Be aware that if you're on a host that sleeps their processes, I don't think this will work. Otherwise, this is a better way than your while loop.
Leaving the below for others who find this
To originate a message without user input with Botkit:
Spawn a bot, var bot = controller.spawn(opts), then call bot.say() anywhere bot is in scope.
bot.say(
{
text: 'my message text',
channel: 'C0H338YH4' // a valid slack channel, FB
}
);
For more info, check out the docs