Sending private messages Discord-api - javascript

help me with discord-api. Sending private messages to the user who just logged on to the server. I have the following code:
const robot = new Discord.Client();
robot.on("guildMemberAdd", (gMembAdd) =>
{
gMembAdd.guild.channels.find("name", "test").sendMessage(gMembAdd.toString() + "hello guys");
});
Added the following code:
robot.on("guildMemberAdd", (gMembAdd) =>
{
gMembAdd.guild.channels.find("name", "test").sendMessage(gMembAdd.toString() + "hello guys");
gMembAdd.mentions.users.first().sendMessage("Test");
});
I received an error message. Help me please.

First thing you shouldn't use .sendMessage() as it was deprecated in newer versions. You need to use .send().
When you subscribing to guildMemberAdd you will recieve a GuildMember, from there you can directly send a message:
robot.on("guildMemberAdd", (gMembAdd) => {
gMembAdd.guild.channels.find("name", "test").send(gMembAdd.toString() + "hello guys");
gMembAdd.send("Test");
});
This should send a message directly to the member that joined.

Related

How to get message link through Discord.js v12?

I'm creating a logging system for my Discord server of over 12k members. What I would like to achieve is that whenever a moderator uses the .lock command, the bot sends a message to the logs channel and DM's me. Both work, but I can't figure out how to attach the message url so that I can click on that and immediately jump to the .lock command itself so I can review what happened.
This is the code that I have thus far:
// Message url to be used in logging later.
const msgURL = 'empty';
// Send lock message
const embed = new Discord.MessageEmbed()
.setTitle("LOCKDOWN")
.setColor('#ff0000')
.setDescription("There have been a large number of infringements in this channel. Please be patient as we review the sent messages and take appropriate action.")
.setFooter("Please do not DM staff asking when the lockdown will be over. ");
message.channel.send({embed}).then(msgURL => {
msgURL = embed.url;
})
// Send unlock notification to #staff-logs.
// async method to get the channel id (in case of delay.)
function getStaffLogChannel(){
return message.guild.channels.cache.get('ID');
}
// Staff logs channel
let staffLogs = await getStaffLogChannel();
// User who issued the command
let commandIssuer = message.member.user.tag;
// message published in staff-logs
staffLogs.send(commandIssuer + " has used the **.lock** command in: " + message.channel.name)
// send notification in DM
client.users.cache.get('ID').send(commandIssuer + " has used the **.lock** command in: " + message.channel.name + " ( " + msgURL + " )");
I have also tried to change the
message.channel.send({embed}).then(msgURL => {
msgURL = embed.url;
})
to:
message.channel.send({embed}).then(msgURL => {
msgURL = embed.url.get;
})
But that unfortunately doesn't work either. Here you get this error:
TypeError: Cannot read property 'get' of null`
You can just use Message#url. There is no need for the .get().
You are trying to get the URL of the embed, not the message.

defaultChannel.send is not a function

I have some code to greet the server when the bot is added.
client.on("guildCreate", guild => {
const defaultChannel = guild.channels.find(c => c.permissionsFor(guild.me).has("SEND_MESSAGES"));
defaultChannel.send(`Hi! Thanks for adding me to your server!`).catch(console.error);
});
It finds a channel where it can send messages to and sends a thanking message.
When I run the above code I get the follwing error: TypeError: defaultChannel.send is not a function

Send a message with Discord.js

I am trying to make a discord bot, but I can't quite understand Discord.js.
My code looks like this:
client.on('message', function(message) {
if (message.content === 'ping') {
client.message.send(author, 'pong');
}
});
And the problem is that I can't quite understand how to send a message.
Can anybody help me ?
The send code has been changed again. Both the items in the question as well as in the answers are all outdated. For version 12, below will be the right code. The details about this code are available in this link.
To send a message to specific channel
const channel = <client>.channels.cache.get('<id>');
channel.send('<content>');
To send a message to a specific user in DM
const user = <client>.users.cache.get('<id>');
user.send('<content>');
If you want to DM a user, please note that the bot and the user should have at least one server in common.
Hope this answer helps people who come here after version 12.
You have an error in your .send() line. The current code that you have was used in an earlier version of the discord.js library, and the method to achieve this has been changed.
If you have a message object, such as in a message event handler, you can send a message to the channel of the message object like so:
message.channel.send("My Message");
An example of that from a message event handler:
client.on("message", function(message) {
message.channel.send("My Message");
});
You can also send a message to a specific channel, which you can do by first getting the channel using its ID, then sending a message to it:
(using async/await)
const channel = await client.channels.fetch(channelID);
channel.send("My Message");
(using Promise callbacks)
client.channels.fetch(channelID).then(channel => {
channel.send("My Message");
});
Works as of Discord.js version 12
The top answer is outdated
New way is:
const channel = await client.channels.fetch(<id>);
await channel.send('hi')
To add a little context on getting the channel Id;
The list of all the channels is stored in the client.channels property.
A simple console.log(client.channels) will reveal an array of all the channels on that server.
There are four ways you could approach what you are trying to achieve, you can use message.reply("Pong") which mentions the user or use message.channel.send("Pong") which will not mention the user, additionally in discord.js you have the option to send embeds which you do through:
client.on("message", () => {
var message = new Discord.MessageEmbed()
.setDescription("Pong") // sets the body of it
.setColor("somecolor")
.setThumbnail("./image");
.setAuthor("Random Person")
.setTitle("This is an embed")
msg.channel.send(message) // without mention
msg.reply(message) // with mention
})
There is also the option to dm the user which can be achieved by:
client.on("message", (msg) => {
msg.author.send("This is a dm")
})
See the official documentation.
Below is the code to dm the user:
(In this case our message is not a response but a new message sent directly to the selected user.)
require('dotenv').config({ path: __dirname + '/.env.local' });
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("ready", () => {
console.log(client.users.get('ID_OF_USER').send("hello"));
});
client.login(process.env.DISCORD_BOT_TOKEN);
Further documentation:
https://github.com/AnIdiotsGuide/discordjs-bot-guide/blob/master/frequently-asked-questions.md#users-and-members
You can only send a message to a channel
client.on('message', function(message) {
if (message.content === 'ping') {
message.channel.send('pong');
}
});
If you want to DM the user, then you can use the User.send() function
client.on('message', function(message) {
if (message.content === 'ping') {
message.author.send('pong');
}
});
Types of ways to send a message:
DM'ing whoever ran the command:
client.on('message', function(message) {
if (message.content === 'ping') {
message.author.send('pong');
}
});
Sends the message in the channel that the command was used in:
client.on('message', function(message) {
if (message.content === 'ping') {
message.channel.send('pong');
}
});
Sends the message in a specific channel:
client.on('message', function(message) {
const channel = client.channels.get("<channel id>")
if (message.content === 'ping') {
channel.send("pong")
}
});
It's message.channel.send("content"); since you're sending a message to the current channel.

Reply to direct messages of twitter using node.js API in Twitter

I am using twit npm package to read direct messages
var stream = T.stream('user', { stringify_friend_ids: true })
stream.on('direct_message', function (directMsg) {
console.log(directMsg)
}
I want to reply the directMsg received , is there any method call of twit which can be used to achieve or any other nodejs package recommended to achieve the same.
Can't provide the exact code solution, but the way is to implement the following steps
Get USER_ID property from directMsg object
Use Twit Rest API method T.post(path, [params], callback) to send direct message to the user with USER_ID
Use Twitter API documentation to understand what you need to send direct messages, you need to properly provide parameters like in documentation
So the code will look like this
T.post("direct_messages/new", {
user_id: USER_ID, // USER_ID is parameter from directMsg object
text: 'YOUR_REPLY'
});
Hope it will help you.
Even i ran into it, here is what you have to do.
Listen to the user stream for direct_message and retrieve the sender.screen_name and recipient.screen_name and verify it's not equal + you need the sender.id as stated by #RashadIbrahimov above.
// Reply to Twitter messages
function replyToDirectMessage(){
//get the user stream
var stream = T.stream('user');
stream.on('direct_message', function (eventMsg) {
var msg = eventMsg.direct_message.text;
var screenName = eventMsg.direct_message.sender.screen_name;
var userId = eventMsg.direct_message.sender.id;
// reply object
var replyTo = { user_id: userId,
text: "Thanks for your message :)",
screen_name: screenName };
console.log(screenName + " says: " + msg );
// avoid replying to yourself when the recipient is you
if(screenName != eventMsg.direct_message.recipient_screen_name){
//post reply
T.post("direct_messages/new",replyTo, function(err,data,response){
console.info(data);
});
}
});
}
and call it
replyToDirectMessage();

How to reply message to Javascript at some address from Java server in vertx using event bus?

I get the message from client but in case of replying message, i tried many ways but no result .
My JavaScript Code is
var eb = new EventBus("http://localhost:8080/loginUrl");
eb.onopen = function () {
console.log("Connection Open")
};
eb.onclose = function () {
console.log("Connection Close")
};
eb.registerHandler("server-to-client", function (message) {
console.log('received a message: ' + message.body());
});
// publish a message
function sendMes(message){
console.log("Sending Message "+message);
eb.send("client-to-server",message,function(callback){
console.log("Received Message "+callback)
});
}
My Java Server Code is
Router router = Router.router(vertx);
vertx.createHttpServer().requestHandler(router::accept).listen(8080);
SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
BridgeOptions options = new BridgeOptions();
options.addInboundPermitted(new PermittedOptions().setAddress("client-to-server"));
options.addOutboundPermitted(new PermittedOptions().setAddress("server-to-client"));
sockJSHandler.bridge(options);
router.route("/loginUrl/*").handler(sockJSHandler);
EventBus eb = vertx.eventBus();
eb.consumer("client-to-server").handler(sockJSHand->{
System.out.println("Sending Message "+sockJSHand.body());//It prints the message from client
eb.send("server-to-client","Message");
});
How to reply back some message from server ?
Your code sample seems to be fine and almost looks like the chat server-client example application except that your should be using the EventBus#publish API instead of the EventBus#send API to allow the message to be dispatched among all registred handlers (all clients web browsers).
As per the Java docs:
EventBus publish(String address,
Object message)
Publish a message.
The message will be delivered to all handlers registered to the address.
An update of your server side code would be as follows:
Router router = Router.router(vertx);
vertx.createHttpServer().requestHandler(router::accept).listen(8080);
BridgeOptions options = new BridgeOptions();
options.addInboundPermitted(new PermittedOptions().setAddress("client-to-server"));
options.addOutboundPermitted(new PermittedOptions().setAddress("server-to-client"));
SockJSHandler sockJSHandler = SockJSHandler.create(vertx).bridge(options);
router.route("/loginUrl/*").handler(sockJSHandler);
EventBus eb = vertx.eventBus();
eb.consumer("client-to-server").handler(
sockJSHand -> {
System.out.println("Sending Message "+ sockJSHand.body());//It prints the message from client
eb.publish("server-to-client", "Message");
}
);

Categories