Random response to message discord.js - discord.js

I’m developing a basic discord.js moderation bot. As one of the functions I need the bot to respond to a message with one of many pre programmed responses.
Eg.
Message = ‘Hello’
Response = ‘Hey’ or ‘Hi’ or ‘Goodday’

This code should work for you, It selects a random value from an array with your messages in it.
// your messages should go into this array
const messages = ["message one", "message two", "message three", "message four"]
const randomMessage = messages[Math.floor(Math.random() * messages.length)];
console.log(randomMessage)

Related

I need a code that sends a message every time a channel is created

I want my bot to send the message "first" every time a channel is created
the closest I could get was at Discord JS : How can ı send message when create channel by bot but I don't want to that he sends the message only on channels he created himself, but on channels created by anyone
You can use the channelCreate event.
Here's a simple example for you:
client.on("channelCreate", async (channel) => {
const channelName = channel.name;
console.log(`New channel created: ${channelName}`);
});

(Discord selfbot) Is there anyway to response if 'hi' in someone message

Is there anyway to make the selfbot response 'hello' if 'hi' is in someone message?
Like
A: hi? Anyone here?
The bot: hello
The bot response because 'hi' is in A's message.
I think it's not possible because i tried many Discord selfbot library and none of library work (Python)
Which library are you using?
I made a discord bot with discord.js (Javascript), and with that you can receive an event every time someone talks in your discord server and then respond depending on the contents of the message.
First you start your discord client (the Intents may vary depending on what you want to do):
const discordClient = new Client({ intents: [Intents.FLAGS.DIRECT_MESSAGES, Intents.FLAGS.GUILD_MESSAGES] })
Then the idea is to get the content of every new message and answer properly, once you have created your discord client, you will need to set up an event listener like this one:
discordClient.on('messageCreate', message => {
const content = messageReceived.content.toLocaleLowerCase()
if (content === 'hi') {
messageReceived.channel.send("hello, I'm a bot!")
}
})
And don't forget to login with your discord bot key
const discordKey = "YOUR DISCORD BOT KEY"
discordClient.login(discordKey)
You can also see the repository for my bot here.
And for your use case you would want to mainly focus on some parts insid discord.ts.
Hopefully this helps.
Here are some basic examples using discord.js within node.js.
Simple Response
To send a response, simply check if the user's message contains the desired input you want your bot to respond to.
if(message.content.toLowerCase().includes("ping") {
message.reply("Pong!")
}
Multiple Responses
This is a much more efficient method of responding to multiple inputs. This includes using an array.
const array = [
"hello",
"hola",
"bonjour"
]
if(array.some(word => message.content.toLowerCase().includes(`${word}`)) {
message.reply("Hello!")
}
Here's the code
---Starts From Here:---
// type `await lib.` to display API autocomplete
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});
// Only respond to messages containing "hi", "hey", "hello", or "sup"
if (context.params.event.content.match(/hi|hey|hello|sup/i)) {
let messageContent = context.params.event.content.match(/hi|hey|hello|sup/i);
await lib.discord.channels['#0.3.0'].messages.create({
channel_id: context.params.event.channel_id,
content: `${messageContent[0]} to you too 👋`,
message_reference: {
message_id: context.params.event.id
}
});
}
--Ends--
Image of code
I suggest using autocode.com it will really help you in coding life. I use it myself.
Here's a small guide https://autocode.com/guides/how-to-build-a-discord-bot/
If your banned using discord selfbot, that's not my fault
from discord.ext import commands
client = commands.Bot(
command_prefix='-',
self_bot=True,
help_command=None
)
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content == 'Hello!':
await message.channel.send("Hi how your day!")
client.run('user token', bot=False)

I'm trying to make a discord bot that DM's a random user and It either DM's me only or I get an error

This is my code and It seems the random user selection is broken although it works completely fine in another command I have that pings a random user
client.on('message', message => {
if (message.content.toLowerCase() === `${prefix}command`) {
const userList = message.guild.members.cache.array();
var randomNumber = Math.floor(Math.random() * userList.length)
var dm = userList[randomNumber]
console.log(dm.user.id)
dm.send("123");
}
ok, so the code you have written works just fine. The problem is that your bot cannot send a message to its self. There is a very easy solution to this. Just check if the selected member is a bot and return if that's the case. Note: I put your random number inside the array field of the userList.
const userList = message.guild.members.cache.array();
var dm = userList[Math.floor(Math.random() * userList.length)];
if (dm.user.bot) return;
console.log(dm.user.username);
dm.send("123");
Note: If you only have yourself and the bot on your test server then this will only ever send a DM to you. In that case I would recommend getting a secondary account and inviting some friends to the test server.
Have you enabled the members intent? The members list only shows you and the bot if you don't have that intent enabled. Read the docs for intents for more information.

Get previous message before trigger DiscordJS

I'm trying to get the message sent RIGHT BEFORE each time I call the bot.
Right now I'm using:
client.on('message', message => {
if (message.content === '$test')) {
message.channel.messages.fetch({ limit: 2 }).then(messages => {
lastMessage = messages.last().content
message.channel.send(lastMessage)
})
}
The bot correctly sends the message sent before the trigger phrase if I send:
hello
$test
hello
However, if I send four messages quickly:
Welcome!
$test
hello
$test
it sends:
hello
hello
when it should reply with Welcome and then hello.
How do I get the content of the message sent right before each time the bot is triggered, rather than of the second-to-last message in the channel?
You should not try and grab the previous message, rather store the messages in order.
var messages = [];
client.on('message', message => {
if (message.content === '$test') {
message.channel.send(messages[messages.length - 1]);
}
messages.push(message.content);
})
You are grabbing the most recent message from the channel, and that can provide unpredictable results when multiple messages are sent.
This instead logs every message in order. This will make sure that all messages will be added along with the processing to prevent discord messages loading faster than your discord bot application processing them.
There is a similar answered question to this one
DiscordJS Bot - How to get the message immediately before another message in a channel?

How to react to a specific message (discord.py)

I'm coding a suggestion bot that's supposed to send a player's suggestion to a suggestions channel in my server and react in the suggestions channel with some emojis.
The problem is that using 'message' as the Message parameter would react to the message sent to trigger the code, but I want it to react to the message the bot sent to the suggestions channel. I'm fairly new to coding. How can I get the bot to react to a message in a different channel?
text_channel = client.get_channel('527127778982625291')
msg = 'Your suggestion has been sent to '+str(text_channel.mention)+' to be voted on!'
await client.send_message(message.channel, msg)
msg = str(message.author.mention)+' suggested "'+str(repAdder)+'"'
await client.send_message(discord.Object(id='527127778982625291'), msg)
print(message)
await client.add_reaction(bot_message, ":yes:527184699098136577")
await client.add_reaction(bot_message, ":no:527184806929235999")
await client.add_reaction(bot_message, '🤷')
You needed to add the reaction to the message that the bot sent, not the user-sent message.
Passing the bot-sent-message as a Message object to client.add_reaction() instead of the original message should fix the problem.

Resources