Bot mention as a prefix in Discord.js - discord.js

My prefix only works if I do not add spaces to the entire command, example:
{
"token": "",
"prefix": "<#453463055741747200>"
}
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
let something = args.join(" ");
message.delete().catch();
message.channel.send(something);
}
module.exports.help = {
name: "say"
}
Let's say my bot name is MyBot, the above code would only work with #MyBot say this, how can I make it work when the command is #MyBot say this?

Maybe this won't work, because I don't use a command handler so I have a different code style, but you can try what I use to allow my bot to be used with multiple global prefixes:
var prefixes = require('./prefixes.json')
//in your case can only be var prefixes = ["<#453463055741747200>", "<#!453463055741747200>"]
let prefix = false;
for (const thisPrefix of prefixes) {
if (message.content.toLowerCase().startsWith(thisPrefix)) prefix = thisPrefix;
}
So the message just needs to start with the desired prefix. Also, I added two mention prefixes because discord is dumb and has two types of user mentions: nickname mentions and normal mentions. So in your code the bot will not work if it has a nick. That's why I added <#!453463055741747200> as well. Hope this helps you

Related

(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)

How would I create a string option in my slash command that reads the string that the user sent in, and uses that as an argument?

So I have a verified Discord.JS bot, and I've been trying to create a slash command with music (Distube). I want to register the play command, and then, allow the user to input a string (the song title) and use that and play the song. How would I do this?
This is my command file:
const Discord = require('discord.js');
module.exports = {
name: "play",
description: "Play music!",
async execute (interaction, client) {
const music = args.join(" ");
client.distube.play(message, music)
}
}
Like I said, how would I change this to match the slash command? I'm using the Discord.JS v13 Guide for this.
Thanks!
You should use const music = interaction.options.get("query").value instead of const music = args.join(' ') because d.js v13 slash commands using interactions, not arguments.
For getting bot joining your voice, you should use client.distube.playVoiceChannel, for searching user voice, we need get this also from interaction, const voice = interaction.member.voice.channel
After this, your code should look like this:
const music = interaction.options.get("query").value
const voice = interaction.member.voice.channel
client.distube.play(voice, music)

Redirect to a channel as well as ping a role then post a message using args

I'm making an announcement command for my bot and want it to go to the announcements channel automatically, then ping the first role mentioned and finally display the message.
For now I have it going to staff commands as a placeholder to get it working, this does not work or throw an error. It properly pings the role, but nothing after that shows up, even the "Debug". What am I missing. I've seen the channel part work but it doesn't for me, and I can't find a similar situation online for the message itself.
module.exports.run = async (client, message, args) => {
if (message.author.bot) return;
let prefix = config.prefix;
if(!message.content.startsWith(prefix)) return;
const channel = message.guild.channels.cache.find(c => c.name === 'πŸš”ο½œstaff-cmds');
let pingRole = message.mentions.roles.first();
let messageContent = args.slice(1).join(' ');
channel.send(pingRole, messageContent, "Debug");
This is what happens when the command is run
Try this channel.send(`${pingRole} ${messageContent}`)
The channel.send() function takes only two parameter "content" and "options" you can read more about it here

How to "globally" blacklist a user from using my discord bot?

[EDIT] This has been fixed!
I just needed to use client.users.cache.get(args[0])
In itself, it works, except the part where I can just send a user ID, which then blacklists the user.
As long as the member is in the server where the command is ran, it works. Coded in DJS and Mongoose
const mongoose = require("mongoose")
module.exports = {
name: "blacklist",
aliases: ["b", "block"],
cooldown: 5000,
description: "Blocks a user from using Hexagon!",
devOnly: true,
category: "Developer",
usage: "blacklist <user> [reason]",
async run(client, message, args) {
if(!args[0]) return message.reply('`[❌]` Incorrect Syntax: Missing Argument')
const mentionedUser = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || client.users.cache.fetch(args[0]);
if(!mentionedUser) return message.reply('`[❌]` Incorrect Syntax: Provided User does not exist!')
let reason = args.slice(1).join(" ")
if(!reason) reason = "Reason not specified."
let profile = blacklistedUsers.findOne({userID: mentionedUser.user.id})
if(profile) return message.reply('`[❌]` Error: Mentioned User is already blacklisted!')
profile = await new blacklistedUsers({
userID: mentionedUser.user.id,
reason
}).save();
message.channel.send(`\`βŒπŸ‘€\` ${mentionedUser.user.tag} was blacklisted!`)
}
}```
I just want to be able to run "blacklist <userID> [reason]" with the userID being an ID that is not a server member, but rather a user in the bot's cache.
The way I would do this, is in your handler, use a string.includes to check blacklisted ids (hopefully separated by commas or such) and check if any match.
//for example:
let tableExample; //mongoose table I use for the object, change to your needs
if (tableExample.blacklistedIDs.includes(message.author.id)) return;
//obviously I use blacklistedIDs, change this to your needs also
This method would check the database for any id and if it matches a user's id when running the command it will cancel.

How to make a command with 2 words in it Discordjs

I am trying to code a discord.js bot for my community server and I was having some issues with making my help command. I have a command for >help that shows and embed with all the different categories of commands. It also shows how to view those other commands, but for me to be able to do this I need to be able to have commands like >help fun or >help staff. I tried to make the >help fun command but when I type it, it only takes the first argument and just shows me the >help embed. If someone could show me the code for a >help fun command that will just send a new Discord.MessageEmbed that would be great. This is the code I tried using:
module.exports = {
name: 'help fun',
description: "get some `fun` help!",
execute(message, args, Discord){
const helpfunEmbed = new Discord.MessageEmbed()
.setColor('#9947d6')
.setAuthor('Vero Commands List', 'https://cdn.discordapp.com/attachments/746321327727706226/819556499088605214/Hypers.png')
.setDescription("The Vero Bot prefix for `Ak's Basement` is `>`")
.setThumbnail('https://images-ext-2.discordapp.net/external/hn8Iyc--j2npBvCjnAsXUt78zMovfsTj_DyRaBb1YdU/https/media.giphy.com/media/eEx0qRFYM1dyGQPAID/giphy.gif')
.addFields(
{ name: '`>ping`', value: 'shows bot latency'},
{ name: '**Work In Progress**', value: 'More commands coming soon!'},
)
message.channel.send(helpfunEmbed);
}
}
Make the help command, and let the user pass "fun" as an argument, then base the bot's reply off that, that way you can have one command for all the help sections.
here's a code example,
btw discord.js guide has a whole explanation on this, so you might want to read it
Here a link if you want to that exact page;
https://discordjs.guide/creating-your-bot/commands-with-user-input.html
and here is a code sample,
I am assuming execute(message, >>>> args <<<<< , Discord) (args) passes a array ( this code is according to the guide i said above)
module.exports = {
name: 'help'
description: "get some `fun` help!",
execute(message, args){
if(!args[0]) { // if no args were give : ex: ">help"
const helpEmbed = new Discord.MessageEmbed()
.setColor('#9947d6')
.setAuthor('something here')
.setDescription("A description")
// do whatever you want with the code and send it,
// assume prefix is >
// this is if there were no args: ">help" will be the command
return message.channel.send(helpEmbed);
} else if(args[0].toLowerCase() == 'fun') { // lowercase it so it will not be case sensitive ex: this would allow ">help FUn" and ">help fun"
const helpFunEmbed = new Discord.MessageEmbed()
.setColor('#9947d6')
.setAuthor('something here')
.setDescription("")
return message.channel.send(helpFunEmbed)
} else if(args[0] == 'info'){ // without ".toLowerCase()" will only allow : ">help info" and will give the below error we set if we use something like ">help Fun"
// do something here (send your embed with help menu for info)
} else { // optional, if some one do a invalid category, it will send a error : ex: ">help dfsg"
return message.channel.send('Invalid category')
}
with this you will not have to create individual command for each catergory*
we can just check the args to see if they provided any args or not (detailed explanation below)
ps: you would have noticed I have removed Discord from execute(message, args)
this is as you don't need to export Discord like this as you can just do
const Discord = require('discord.js') at the top. there will be no difference changing this, but I like to just require it at the top, if you want just add discord in there like execute(message, args, Discord)
Simple explanation on what we do here
first, we check if args[0] is undefined (if a user do ">help" without something in front of it, this would detect it and send
then it will send the embed with the categories if this returns undefined
if a arg is given it will go to the if-else chain
checking if the args = to the category we set.
if it is send the embed with the relevant command info to the user
if its not equal to the category it checked it will go through all the if else chains looking if it matches
if It does not match it will send the error " Invalid category" meaning the user sent a category that we were not looking for

Resources