I'm currently making a discord bot that will send out messages. Unfortunately the messages are receiving errors such as bot.sendMessage is not a function. I'm fairly new to coding so this one has me stumped. Even any google searches have not been able to help me to the point where I can understand it.
I've tried bot.send as maybe .sendMessage is now outdated I had read somewhere I believe.
var exampleSocket = new WebSocket(dataUrl);
bot.send({to: flowChannel,message: 'Websocket connected'});
exampleSocket.onopen = function (event) {
logger.info('got to here');
The output should post in my channel that the websocket connected.
bot.send({to: flowChannel,message: 'Websocket connected'});
Client.sendMessage() was removed in Discord.js 9.0 back in 2016.
I've tried bot.send as maybe .sendMessage is now outdated I had read somewhere I believe.
TextBasedChannel.sendMessage(), TextBasedChannel.sendCode(), TextBasedChannel.sendEmbed(), TextBasedChannel.sendFile(), and TextBasedChannel.sendFiles() are all deprecated.
The equivalent of your code today is as follows...
flowChannel.send('Websocket connected')
.catch(console.error); // Catch the rejected promise in the event of an error.
Discord.js Docs (Stable)
#sendMessage is deprecated.
You need to pass 'message' through and use message.channel.send()
Channel can also be a DM.
TextChannel.sendMessage (and DMchannel.sendMessage) along with all type of sendXX functions, is deprecated.
The function TextBasedChannel.send take as argument a MessageOptions value (or directly an Attachment or RichEmbed) if you want to pass anything other than just text.
To access the send function, you need a TextChannel or a DMchannel which you can get:
In the message that triggered your function like this: client.on('messages', (msg) => {msg.channel.send('Hello')})
If you have a Guild instance: guild.channels.get('channel id') or guild.channels.find(d => d.name === '<channel name>)') (note: you'll have to check if the channel is a TextChannel and not a voice one)
with the Client.channels method, which list all of the Channels that the client is currently handling, mapped by their IDs - as long as sharding isn't being used, this will be every channel in every guild, and all DM channels
Related
I'm failing to achieve something very simple. I can't send a message to a specific channel. I've browsed trough the documentation and similar threads on stack overflow.
client.channels.get().send()
does NOT work.
It is not a function.
I also do not see it as a method on the Channel class on the official documentation yet every thread I've found so far has told me to use that.
I managed to have the bot reply to a message by listening for a message and then using message.reply() but I don't want that. I want my bot to say something in a specific channel in client.on('ready')
What am I missing?
You didn't provide any code that you already tested so I will give you the code for your ready event that will work!
client.on('ready', client => {
client.channels.get('CHANNEL ID').send('Hello here!');
})
Be careful that your channel id a string.
Let me know if it worked, thank you!
2020 Jun 13 Edit:
A Discord.js update requires the cache member of channels before the get method.
If your modules are legacy the above would still work. My recent solution works changing the send line as follows.
client.channels.cache.get('CHANNEL ID').send('Hello here!')
If you are using TypeScript, you will need to cast the channel in order to use the TextChannel.send(message) method without compiler errors.
import { TextChannel } from 'discord.js';
( client.channels.cache.get('CHANNEL ID') as TextChannel ).send('Hello here!')
for v12 it would be the following:
client.on('messageCreate', message => {
client.channels.cache.get('CHANNEL ID').send('Hello here!');
})
edit: I changed it to log a message.
This will work for the newest version of node.js msg.guild.channels.cache.find(i => i.name === 'announcements').send(annEmbed)
This should work
client.channels.fetch('CHANNEL_ID')
.then(channel=>channel.send('booyah!'))
Here's how I send a message to a specific channel every time a message is deleted. This is helpful if you'd like to send the message without a channel ID.
client.on("messageDelete", (messageDelete) => {
const channel = messageDelete.guild.channels.find(ch => ch.name === 'channel name here');
channel.send(`The message : "${messageDelete.content}" by ${messageDelete.author} was deleted. Their ID is ${messageDelete.author.id}`);
});
Make sure to define it if you're not using messageDelete.
I am looking to send a message that has a different profile picture than the bot. Basically, like Tupper Bot does. I can't seem to figure out how to do it anywhere, I've read the documentation and searched around.
You can use a webhook to do what you describe. If you already have a webhook link see here on how to use it. This works from external programs too.
If you don't, you can create a webhook with your bot and then send messages to it. In this example we will create a simple webhook and send a message to it.
First we should check if the channel already has a webhook. That way you don't create a new one everytime you use the command. You do that with the fetchWebhooks() function which returns a collection if there is a webhook present. If that is the case we will get the first webhook in the collection and use that. Note: if you have more then one webhook you can of course add additional checks after the initial one.
If there are no webhooks present, we create a new one with createWebhook(). You can pass additional options after the name.
let webhook;
let webhookCollection = await message.channel.fetchWebhooks();
if (webhookCollection.first()) {
webhook = webhookCollection.first();
} else {
webhook = await message.channel.createWebhook("new webhook", {
avatar: "https://i.imgur.com/tX5nlQ3.jpeg"
});
}
Note: in this example we use the channel the message came from but you can use any channel you want
Technically we can now send messages already.
webhook.send("this is a test");
What you can also do is create a webhookClient. Thats a little like the discord client you create when you start your bot. It takes the webhook ID and token as well as additional options you can set for clients.
const hookclient = new Discord.WebhookClient(webhook.id, webhook.token);
This lets you use a few additional methods like setInterval.
hookclient.setInterval(() => {
hookclient.send("This is a timer test");
}, 1000)
This lets you use the webhook without creating or fetching one first.
I am making a discord bot in discord.jsV12 that auto sets up a server. For this to happen i need the bot to delete all channels. I have tried msg.guild.channels.forEach(channel => channel.delete())
But nothing happens and I get 0 errors.
What you attempted is actually the solution.
You can use it on the message object, which means it's an action after you make a message, like so:
client.on('message', message => {
if (message.content === '.deleteChannels') {
message.guild.channels.forEach(channel => channel.delete());
}
});
triggered by making a discord message containing ".deleteChannels"
Make sure your bot has permissions to delete channels as well.
Be aware that this is a reply to a message. Otherwise, message would not be defined.
discord.js v12+ uses Managers, which means you'll have to go through an extra step and pass through the cache property.
msg.guild.channels.cache.forEach(channel => channel.delete());
Guide to switch from v11 to v12
More info about updating
I've a problem with a reaction reply System.
I want that when a user adds a reaction, that replies to a message, except that when the bot reboots it is no longer detected by the bot.
Do you know how to fix this problem?
Here is my current code :
bot.on("messageReactionAdd", function(messageReaction, user){
if(messageReaction.message.content === "Message"){
if(user.bot){return}
messageReaction.message.reply("It works.")
}
})
bot.on("message", function(message){
if(message.content.startsWith(prefix + "test")){
message.delete()
message.member.createDM().then(m => m.send("Message").then(m => m.react("✅")))
}
}
on the latest version of discord.js, you can use the Partial Events to accomplish this.
According to the doc (https://discord.js.org/#/docs/main/master/topics/partials):
Partials allow you to receive events that contain uncached instances, providing structures that contain very minimal data. For example, if you were to receive a messageDelete event with an uncached message, normally Discord.js would discard the event. With partials, you're able to receive the event, with a Message object that contains just an ID.
What you need to do is
const Discord = require('discord.js');
// add "partials" in the bot options to enable partial events
const client = new Discord.Client({"partials": ['CHANNEL', 'MESSAGE']});
[...]
client.on("messageReactionAdd", async function(messageReaction, user){
// fetch message data if we got a partial event
if (messageReaction.message.partial) await messageReaction.message.fetch();
if(messageReaction.message.content === "Message"){
if(user.bot){return}
messageReaction.message.reply("It works.")
}
})
Doing this, you must be careful on your client.on("message", ...) calls, to avoid accessing data or method that are not available.
there is a boolean message.partial that you can use to discard partial message when you don't need them.
I'm making a discord bot, and I'm trying to make use of the createChannel function shown here in the documentation. For some reason, I am getting the following error:
TypeError: bot.createChannel is not a function.
My code is within a function which I pass a message to, and I have been able to create roles and add users to roles within the same function. It's just the createChannel function that's not working. Below is the relevant portions of the code.
const bot = new Discord.Client();
function makeChannel(message){
var server = message.guild;
var name = message.author.username;
server.createRole(data);
var newrole = server.roles.find("name", name);
message.author.addrole(newrole);
/* The above 3 lines all work perfectly */
bot.createChannel(server,name);
}
I have also tried bot.addChannel, and bot.ChannelCreate, since ChannelCreate.js is the name of the file which contains the code for this command. Also, I have attempted specifying channel type and assigning a callback function as well, but the main issue is the TypeError saying that this isn't a function at all. Any idea what I'm doing wrong?
Additionally, I plan to use ServerChannel.update() at some point in the future, so any advice on getting that to work once the previous problem is resolved would be greatly appreciated.
Alright, after a few days of trying things and going through the docs, I have discovered the solution. I am using a more recent version of Discord than the docs I was reading were written for. In the newer version, channels are created with a method in the server, not a client method. so, the code should be:
const bot = new Discord.Client();
function makeChannel(message){
var server = message.guild;
var name = message.author.username;
server.createChannel(name, "text");
}
The "text" value is the type of channel you are making. Can be text or voice.
I'll post a link to the most recent documentation for anyone else who encounters this problem here.
The answer should update documentation link to the GuildChannelManager which is now responsible for creating new channel.
(Example from docs)
// Create a new text channel
guild.channels.create('new-general', { reason: 'Needed a cool new channel' })
.then(console.log)
.catch(console.error);
https://discord.js.org/#/docs/main/stable/class/GuildChannelManager
#Jim Knee's I think your answer is v11, I'm new in discord.js, using Visual Studio Code's auto-code thingy. You can do all the same things except your thing must be this. If you are poor people, getting errors on doing #Jim Knee's answer, this is the place for "YOU!"
Get rid of server.createChannel(name, "text/voice");
And get it to THIS server.channels.create(name, "text/voice");
Hope I can help at least ;)
I'm just a new guy here too
I think you have not logged in with your bot.
From the docs:
const Discord = require('discord.js');
var client = new Discord.Client();
client.login('mybot#example.com', 'password', output); // you seem to be missing this
function output(error, token) {
if (error) {
console.log(`There was an error logging in: ${error}`);
return;
} else
console.log(`Logged in. Token: ${token}`);
}
Alternatively, you can also login with a token instead. See the docs for the example.