#development
1 messages Β· Page 1844 of 1
Much less spam in a channel the bot is used
Hopefully nested commands will or sub-command groups will not show up in the future before entering it's main group command
which one is better bind or arrow function
=> is more commonly used nowadays, I prefer it more
its for controller class in an api
hmm alright
i'll just use arrow function then
Yeah but you can't delete them. Also you can't let a command fail silently without the user getting an interaction error which kinda sucks for command cooldowns.
aye thanks
That's true but I'm speaking about running slash commands in non-whitelisted channels, if the user is missing the permissions or any command argument isn't valid.
These messages will not spam the channel anymore the user executed the slash command.
Yeah that's definitely pog
I am sending a message: js message.reply()Then I am catching an error js .catch(error=>{})But now what I want is, if there is no error in sending the reply, I want to send another message. How do I do that?
I like keeping channels clean
Yeah I have to say I really like that shit... even if I always refuse to get in touch with the latest "technology"
I somehow always have to... (at the end)
in the end, everything evolves to crab anyway
Well comparing 10-15 y ago to now, yes, you're right.
That's already written down the Discord dev docs
Just need to wait until it arrives
There we go:
Currently, subcommands and subcommand groups all appear at the top level in the command explorer. This may change in the future to include them as nested autocomplete options.
I am sending a message: js message.reply()Then I am catching an error js .catch(error=>{})But now what I want is, if there is no error in sending the reply, I want to send another message. How do I do that?
Use .then(...go on...) or await the reply and check it's result
Does anybody has the Discord permissions list (in the accurate order)?
(as flags)
fs.readFile('codes.txt', {encoding: 'utf-8'}, function(err, data) {
if (err) throw error;
let dataArray = data.split('\n');
console.log(args1[0][2])
const searchKeyword = `${args1[0][2]}`;
let lastIndex = -1;
for (let index=0; index<dataArray.length; index++) {
if (dataArray[index].includes(searchKeyword)) {
lastIndex = index;
console.log("Yup it's in there!")
break;
}
}
dataArray.splice(lastIndex, 1);
const updatedData = dataArray.join('\n');
fs.writeFile('codes.txt', updatedData, (err) => {
if (err) throw err;
console.log ('Successfully updated the file data');
});``` Hey, why is it console.logging eventhough args1[0][2] is not in the txt file?
for example: !test again heyhey
heyhey is nott in tthe txt file but it is still removing the last line from tthe txt file?
er, im a bit confused. I am making an api request to https://discord.com/api/v9/webhooks/875789465308770346/aW50ZXJhY3Rpb246ODc1Nzg5NDY1MzA4NzcwMzQ2OmE2UjE3QURhVE5xYkowbkQ2R3d4QVpqd2ticWdCdFZXOVBJWThwTVBCeWpNN1g3alByaTNpbTN0am5oTWVGclZUMG1nMk43cUVBcnQ0ejlqR0RsUHM2M1ZxU2d0M3RybHdmSG9WV3BKeWY5dVNuUlc1T2NXNlRBQjZmemhBYjg5/messages/@original
with the body { content: 'hi' } and my bots message is not editing for some reason
im getting this error btw
Error: connect ECONNREFUSED 127.0.0.1:80 with axios
@original? what is that
didn't the api says /messages/message_id
and this message must be sent by same webhook
It refers to the original response
is it accepted by the api?
didn't see it, it will be helpful
is there a link docs for it?
are u trying to make http request to localhost or somethin?
https://discord.com/developers/docs/interactions/receiving-and-responding#get-original-interaction-response
https://discord.com/developers/docs/interactions/receiving-and-responding#edit-original-interaction-response
https://discord.com/developers/docs/interactions/receiving-and-responding#delete-original-interaction-response
? no, its by axios
how does the axios setup look like?
i sent the url im sending the request to
return await this.RequestManager.request(
'PATCH',
`${this.RequestManager.constants.BASEURL}${this.endpoints.EDIT_SLASH_COMMAND_RESPONSE(
applicationID,
interactionToken
)}`,
{ content: params.content }
);```
and thats
const options = {
method,
url,
headers: {
Authorization: `Bot ${this.client.token}`,
'Content-Type': 'application/json'
},
data
};
return await axios(options);```
that's interaction xD lol i was talking about webhook, my mistake π
Thx tho π
They were talking about interactions
π
it almost look same syntax as webhook
id/token/messages..
And interactions are webhooks
yea it's under same path
The way you PATCH an interaction response is the same way as you would do on a webhook for example
try logging url
yeah, i have
This I guess?
How do I check the result whether it gave an error or not, if I await the message.reply?
]
that's url?
that's relative url.. probably he thinks u meant localhost
have you set up the baseURL for axios?
Axios makes stuff confusing
i found the issue, im dumb :/
which is?
Hey..
I'd like to ask what do we mostly do with interactionCreate.
I'm confused honestly, I don't find it a purpose. (Talking about normal commands, not slash.)
nothing
it's emitted when a user clicks a button... or uses a select menu... or a context menu
it doesnt do anything for normal commands
definitely not nothing
he said normal commands, not slash
normal messages can have interactions too
I mean I can use it to do something if someone clicked a button.
.. but a real purpose.. I don't find any examples.
normal messages can have buttons, select menus and context menus
That's a real purpose, lol
oh yeah, true i forgot there are other components
Yes.. but I can do the buttons, etc, without the event.
But you can't interact with them
technically you can
the event is the only way to tell if a button has been clicked
Oh.. damn.
I can't seem to find any documentation how to setup the interactionCreate event. π
you really don't need to use that event if you're using discord.js
the methods and properties of interaction that was provided in that event
Alright.. I have this command.
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('random')
.setLabel('primary')
.setStyle('PRIMARY')
);
message.channel.send({ content: 'Hello World.', components: [row] });
How can I make it whereas (only for this command).. if someone clicked the button.. it would, for example, reply to the user with a message.
I know for a fact that interactionCreate does this but they do it for all buttons in general.
ex:
client.on("interactionCreate",interaction=>{
if(!interaction.isButton()) return;
console.log(`button with id ${interaction.id} was clicked by ${interaction.user.username}`)
})
I got so confused.
Documentation is even more confusing.
I created the button.. and I created the event.
Does anyone know how to make a command in python that shows the number of servers the bot is in?
The response will be: I am in {guilds} servers.
len(client.guilds) I guess
Hmm ok
Do something once done?
Yes.. I clicked the button, the interaction create event was fired, but I want it to do something in the command when clicked.
What do you want to do? Respond to the interaction?
Basically if the button was clicked, reply with a message.
easier way than the client.on("interactionCreate"
djs has support for slash commands now?
eee. quick question - is searching for things (like users, messages, channels) api abooz? in programming, not using ofc
why will it be
I'm confused, how do I put that in the command?
you're searching through your own cache
Command?
Should I make a new parameter named as interaction?
Yes.. the button is for one command.
If you're using commands then use
no, iterating through discord data =p
I don't want the reply to be for all the buttons.. only for one specific command. Like a command when its button is clicked, it does this, another button does something different.
yes thats what customID is for
and you can also check the message id of the interaction
How..
One moment.
const { MessageEmbed, MessageActionRow, MessageButton } = require("discord.js");
const { black } = require("../../other/texts/colors.json");
module.exports = {
config: { ... },
run: async (bot, message, args) => {
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('test')
.setLabel('primary')
.setStyle('PRIMARY')
);
message.channel.send({ content: 'Hello World.', components: [row] });
},
};
That's done.
ehhh, ill ask my questions someone another
So ```js
if (interaction) {
// handle
return;
}
... // command code```
Or create a folder with interaction handles
This is legit my question.. how can I make it respond to the interaction, like an example code that checks if the button above is clicked, then doing something.
Are you using v12?
No.. V13.
just replace console.log with whatever u want lol
Then use this
interaction is the interaction
It has the reply method?
interaction.reply("MESSAGE")
You don't have to use client.api anymore, they have a class and event for interactions now
What part is confusing? 
TypeError: interaction.reply is not a function
at Object.run (C:\Users\Mohammad Hajjiri\Desktop\Rewrite\src\commands\owner\customcommand.js:30:21)
at module.exports (C:\Users\Mohammad Hajjiri\Desktop\Rewrite\src\events\guild\messageCreate.js:45:27)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
What I'm trying to do is make two buttons in a message in a command, if button a is clicked, it does something else if button b is clicked, it does something else.
Also, not sure why the error above showed...
Does anybody has the Discord permissions list (in the accurate order, regarding the hierarchy)?
Accurate order? What do you mean?
go to /events/guild
create a file: interactionCreate.js
I did.
module.exports = async (bot, interaction) => {
if (!interaction.isButton()) return;
console.log(`A button with an ID of ${interaction.id} was clicked by ${interaction.user.username}.`);
};
...
and that should be fine
Ordered by their hierarchy. For example MANAGE_GUILD does include MANAGE_CHANNELS, doesn't it?
Never had anything to do with permissions before other than just checking them.
in ur command , remove interaction.reply
and put it inside this
You shouldn't invite a shitty bot that runs 2 instances in the first place
It's a private bot
No, it doesn't
Only ADMINISTRATOR is special
Why though? It will make all buttons when pressed reply with the same message.
Ohh
How are you passing the interaction to a command?
yea, use if or just redirect it back to the message command

if (interaction.isButton() && interaction.customId === "random") require(...).run(..., interaction);```
Aha, alright that means I have to check multiple commands...
So a permission "above" doesn't exist then...
Something like that
Nah, those are only for roles
alright, ty
again...
;-;
Heyy..
hi?
Fetching for messages and channels are not abusable..
.. but what are the reasons behind this?
iterating through also?
What do you mean?
reasons? im doing bot based on linux and thought that grep could be cool to do =p
Ah.. not sure what that is. :( (no reactions π )
just iterating throught all members/channels/messages and printing output in pages
Not sure..
like if you say
$grep -c test
will print all the channels containing "test" in name or smth..
I don't think it is..
The channels are like cached.. so it's like finding channels.
.. or like looping through all the channels in a guild that has a channel named as "test".
second more =p
What?
or no... generally as i said to find dofferent types of data in discord and show output in embed or smth....
abooz or noot?
I don't think so.
y know. i wanna be sure. i dont wanna be banned as a dev =p
especially that bot is public on topgg =p
β’~β’
I say wait for confirmation from other developers. (Since I haven't done this before, and I'm not too sure about it.)
k
thk. grep goes byebye
if (!message.channel.permissionsFor(message.guild.me).has([Permissions.FLAGS.VIEW_CHANNEL, Permissions.FLAGS.SEND_MESSAGES, Permissions.FLAGS.EMBED_LINKS])) return;
How is Permissions not defined?
idk. maybe ur cAPSlOCK?
Nope?
Discord.Permissions unless you destructure Discord to cast it's exported member Permissions to a variable
I have to use destructuring assignment, oh you're joking.
You don't
const Discord = require("discord.js")
const { Permissions } = Discord
// is the same as
const Permissions = Discord.Permissions
unless you're dealing with low level memory references in which case they aren't the same
Ah..
This is.. oh god.
Thank you. π
Tf
Oh god.
I should click the link.. π
Yoo Luca.
@solemn latch
New user to ban. π
hey
how do you get the owner tostringed?
the guild owner
i cant seem to get the owner
if you don't have the owner in the cache, you need to access the guild.owner_id or guild.ownerID or guild.ownerId and fetch the user from the API
how
Discord sends the owner ID for each guild. Look at your library's docs and look for guild owner ID or something similar
π
Hey.. I've never been so confused.
I have this code.
if (!message.channel.permissionsFor(message.guild.me).has([Permissions.FLAGS.VIEW_CHANNEL, Permissions.FLAGS.SEND_MESSAGES, Permissions.FLAGS.EMBED_LINKS])) return;
In some commands, it checks, and in some commands, it errors TypeError: Cannot read property 'has' of undefined
What? π
@last tapir you can also use await guild.fetchOwner();
bot.users.fetch(message.guild.ownerId()).toString()
I mean.. a command like !a works if I have a code that sends a message including the code check above, and another command !b that doesn't work since the code above errors.
Update, for some reason, this is only happening in one category.
Update.. I don't know what the fk I did.. for some reason.. the bot is checking another code that has .has and if that .has has an error.. it errors the first .has word in the first sentence, if that makes sense.
Its solved.. but not sure how. π€·ββοΈ
adding someone to bot team later on wont show them on creator list on the website?
It will eventually on the new site.
I have now a login button with the identify scope for a bot.
<button><a href="https://discord.com/api/oauth2/authorize?client_id=872968216169812009&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Findex.html&response_type=code&scope=identify"></a>Log in</button>
Now I want to get data from the user. The redirect url is the main page.
How do I get data from the user?
wdym get data from the user?
When I autorise the bot with my account I want to get data from the user
when I try to vote for a bot I click log in, and then I click authorize, and then what happens next is I go back to the log in page
brehh
Discord sends data in the post request it makes to your server. You store the data then redirect the user to the content you want to display and use that stored data
I followed this docs exactly:
https://discordjs.guide/oauth2/#implicit-grant-flow
But this isnt working. When authorizing the user with the bot I get back to the page, it still shows just "Hoi" without the username and discriminator as it should. The config.json is also empty:
"clientId": "",
"clientSecret": "",
All I get is a weird code in the url bar:
http://localhost:53134/?code=ZfaVki5XQl2h9M3B5GmQm3qoddFGTV
Can someone help me?
I used this exaclty this code:
https://github.com/discordjs/guide/tree/main/code-samples/oauth/simple-oauth-webserver
Well the code on the url is what is typically used in the authorization code grant
I can't remember if implicit grant flow gives you a code as well since i've never really used that flow before
nope, it directly return access token without refresh token
Thought so
check what is printed in ur node console
Nothing
clientId and clientSecret should be provided if u forget them
I have them but that doesnt change something
can u console log query?
Bruh why is that a discord embed
Because it leads to the OAuth page
mm..
did u confirmed the redirect_uri in ur application is exactly same as in ur node script?
localhost:xxx is not same as localhost:xxx/
tested it and working fine
oh i forget in ur authentication URL make sure response_type is token
if u want info appear in that hoi page
or set it to code if u want it be console logged in node at backend
a
b
https://ayeven.github.io/hanyuu/ front end is hard
I dont how many commits I try to make the posts appear. lmao
well, yeah quite some time seeking the template
I thought it was raw instead of a template :(
it feels like i'm reading a blog
you might wanna look into something else
look for inspirations on https://www.behance.net/ and https://dribbble.com/
nah too much fluff, sore to the eyes
The easier the better, aye
if (typeof data !== 'string') throw new error(errorMessage);
^
RangeError [EMBED_DESCRIPTION]: MessageEmbed description must be a string.```
It works in v12 though
i changed it to v13 but idk if there is more
You know map just makes a new array right?
You will have to join it
it works in v12
Yes
i am learning v13
Actually no
so i need help
i know i use hthis
What you need is to read the guide
how?
...
pls?
and understanding error messages
They are pretty self explanatory if it says it must be a string then don't give it an array
So this is really a beginner question but I have developed some basic bots but I don't know how do devs make bots public. Like what I did was for my guild , how can I make it customizable for each guild ?
I tried googling but couldn't find answer , can someone tell me how it's done ?
PS : Also which database framework is good among MongoDB, SQL and SQLlite for discord bots ?
Those are fine, just pick your favorite/something that you find interesting
ok thanks
how hard is making a sharded bot 
as easy as adding an extra parameter
how does sharding works anyways 
creating new process for each shard
that doesn't make things clearer
do you know what a process is
no.. 
why do you have cringe emojis in your messages
anyways
when you do node . or anything similar, it creates a new process of node
sharding is similar
it spawns multiple processes based on the number of shards you provide
each shard handles different guilds
so basically a shard is like clones of a bot?
yes
yes
when shard is offline, bot will be offline in that shard's guilds
so that means guild a can have an "online bot" and guild b can have an "offline bot"?
did you wonder that why big bots has status pages?
if both are on different shards, yyes
not rlly tbh
What would happen if i return in a setInterval
nothing
would it stop it or..?
it won't stop the interval
Hey may I have the invite to discord developer server?
Thx
how do i augment process declaration in typescript
declare global {
namespace NodeJS {
interface Process {
property: type
}
}
}
ohh thanks it works
So you do shards on same hosting provider or different one ?
Same one
can i have a question not related to bot developing? (just other dev things)
yes
why do you want to do this
if you know both languages you can just rewrite it yourself
why i cant create .env file
If the python code uses external libs, even if you find a converter it won't work as expected cause JS doesn't have the exact same libraries and APIs
did you read the error?
hey, why does this little snippet work when i input: !redeem test code123, eventhough there is not even a code123 in the codes.txt:
if(args1[0][1] == 'spotify'){
message.delete()
fs.readFile('codes.txt', {encoding: 'utf-8'}, function(err, data) {
if (err) throw error;
let dataArray = data.split('\n');
console.log(args1[0][2])
const searchKeyword = `${args1[0][2]}`;
console.log(dataArray)
const index = dataArray.indexOf(`${searchKeyword}`);
if (index > -1) {
dataArray.splice(index, 1);
let newLinks = dataArray.join('\n')
fs.writeFileSync('./codes.txt', newLinks);
}else{return message.channel.send("Not a valid key!")}```
it is not sendingg the not a valid key error
console log searchKeyword to see what it is
sure
basically everything i put after !redeem spotify.
thisisthevariable
!redeem spotify code1
etc etc
And dataArray?
a long array of generic codes
Console log dataArray[index] right after you declare index
yes
sure!
it shows me the variable i used after !redeem spotify
and it deleted it from the original file, which is good
but if i would use a key that is not in tthe file:
aha!
UREKA!
now i can check if it's undefined and return it
idk JS, so smh... but if noone here will help - i'll dm a someone on twitter =p
if(args1[0][1] == 'spotify'){
message.delete()
fs.readFile('codes.txt', {encoding: 'utf-8'}, function(err, data) {
if (err) throw error;
let dataArray = data.split('\n');
const searchKeyword = `${args1[0][2]}`;
console.log(dataArray)
const index = dataArray.indexOf(`${searchKeyword}`);
if(dataArray[index] == undefined){
return message.channel.send("Not a valid key!")
}
if (index > -1) {
dataArray.splice(index, 1);
let newLinks = dataArray.join('\n')
fs.writeFileSync('./codes.txt', newLinks);
}
```strange!
It first says that the key has been claimed
and then sends: the key is not valid?
async def help(self, ctx: commands.context,command : str):```
if i give command arg it doesn't sending anything even i have provided if statements
...response_type=token"...?
I have this inside a div to create a greyish background but I don't understand why it doesn't take the full window size
<div v-if="createPopup || editPopup || deletePopup" class="fixed z-10 w-screen h-screen bg-black opacity-70"></div>
what the heck are those css classes
tailwind

anyways to make it cover the whole screen you should use 100vh for height and 100vw for width
also what's the point of a grey background if it covers the whole screen
just added inset-0 works now
not letting the user interact with other things outside the popup
They wont be able to see anything else if the popup takes the whole screen
it doesn't? 
what element is supposed to take the whole screen
as i said
cause it had some insets
is the guild_ids required?
@slash.slash(
name="ping",
description="Pong!",
guild_ids=[]
)
async def _ping(ctx:SlashContext):
await ctx.send("Pong!")
if you want to make it guild-only, yes
Anyone know the rate limits for this discord API endpoint?
https://discord.com/api/channels/:channel_id/messages
Make the guild ids to [ Your dev guild id ], for development otherwise leave blank to make it global (it takes up to an hour to register global commands)
hi, i need to deploy an express application to a specific domain name, i'm new to express and online i didnt find anything helpful, can anyone help me?
Sure.
What's your host?
Repl/heroku/glitch/vps etc
welp, looks like slash commands are not the only option anymore
how
Wdym
what happened
@mentions?
Yes, bots will continue to receive message content (and embeds, attachments, and components) for DMs and messages in which they are mentioned.
Yeah
Yup
But how do message collectors work then?
;-;
I hate it when bots send stuff in DMs
Bad UX
also now we get to keep our eval commands
which is good
although having to maintain a websocket connection for them would suck
i'd still prefer private slash commands
put something like this
server {listen 80;
listen [::]:80;
root /var/www/<your domain.com>/html;
index index.html index.htm index.nginx-debian.html
server_name yourdomain.com www.yourdomain.com;
location / {
proxy_pass http://localhost:8083;#whatever port your app run
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
at /etc/nginx/sites-available/domain.com
Then run
Then run ```bash
sudo ln -s /etc/nginx/sites-available/domain.fuck /etc/nginx/sites-enabled/domain.fuck
Then restart nginx with
```bash
sudo service nginx restart
I hope they'll add this in the future
yeah
wait what language is this lol
if possible, i want to move my bot out of the websocket entirely
Same
idk
nginx config language probably
(might be yml dk)
Hi Tim
just waiting for them to support attachments
my interaction server lib is pretty much ready
i need to do this is js lol
where is your express hosted? vps?
do you know what nginx is ?
it an alien language
no, just a hosting service
what hosting service?
amogus language
no sorry, i'm new to express and stuff like this
it is called hostsapling, idk if anyone here knows it, but i'm trying to find a better one
you don't need express to know nginx
Oh you're doing a lib?
Not even motivated to even start
if its one of those limited pterodactly panel hosts, you need to ask them if they even support custom domains
ye, a very barebones lib with 0 dependencies. already have an interaction server and a websocket, just missing a rest manager now
yes it is lol, thanks
I'm very interested. I'll keep an eye out for it.
will put it on github soon

Ihv a ts object, i want to extract all the optional fields and make a new type. How do I do that?
type it out like a normal person
There is alot. I want to make a utility type For that
Are all the properties optional or just some?
Just some
And in the new type they would be required? Or still optional?
2021-08-14T13:07:18.410153+00:00 app[Worker.1]: (node:4) UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions
2021-08-14T13:07:18.410165+00:00 app[Worker.1]: at RequestHandler.execute (/app/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
2021-08-14T13:07:18.410166+00:00 app[Worker.1]: at runMicrotasks (<anonymous>)
2021-08-14T13:07:18.410166+00:00 app[Worker.1]: at processTicksAndRejections (internal/process/task_queues.js:95:5)
2021-08-14T13:07:18.410185+00:00 app[Worker.1]: at async RequestHandler.push (/app/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
2021-08-14T13:07:18.410186+00:00 app[Worker.1]: at async Object.module.exports.run (/app/commands/embeds/help.js:131:17)
2021-08-14T13:07:18.410186+00:00 app[Worker.1]: (Use `node --trace-warnings ...` to show where the warning was created)
2021-08-14T13:07:18.410243+00:00 app[Worker.1]: (node:4) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
2021-08-14T13:07:18.410328+00:00 app[Worker.1]: (node:4) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Client.on("message", async (message) => {
if(!message.member.guild.me.hasPermission(["SEND_MESSAGES", "EMBED_LINKS", "USE_EXTERNAL_EMOJIS"])) return;
})
Then use Optional. It makes all fields optional. AFAIK there is no way to extract all the optional fields from a interface and create a new type with them
Optional does what you want it to, but It'll make the required fields optional too instead of removing them
but there's no other way
Your bot is missing permission in that channel
Its called Partial though!
just make 2 interfaces and intersect them?
I want to fix that it's not my server
Oh yeh Partial not Optional
do you have multiple client.on("message")?
also you have to take channel permissions into account
wdym with that
I guess you could also use Omit
if the required properties are only a few
but using intersections is also an option
you showed your code for client.on("message"), and in your code, you have the permission check and nothing else in it
where is the rest?
Shouldn't it be fore all commands ?
yes, but you didnt show the commands code, and its important to know where it is. is it inside the same client.on("message") or is it inside another client.on("message")?
Ok π
I am using cmd handler
They are not in the index.js
let me explain
commands/folder/cmd
do you have this? js client.on("message", () => { // permissions here // commands here }) or this? ```js
client.on("message", () => {
// permissions here
})
client.on("message", () => {
// commands here
})
No
im asking because you showed this
This in the index.js
No i don't have this in my commands file
you are not understanding the question, show your index.js file
// connecting to discord
const Discord = require('discord.js')
// connect us to the config.json file
const config = require('./config.json');
// create a new Discord Client
const Client = new Discord.Client({disableEveryone: true, partials: ['MESSAGE', 'REACTION']});
require('discord-buttons')(Client);
// we make a new system for the cmds
Client.commands = new Discord.Collection();
// require the fs module
const fs = require('fs');
const fetch = require('node-fetch')
const prefix = ('w!');
// it creates a new function for our aliases
Client.aliases = new Discord.Collection();
const map = new Map();
const snipes = new Discord.Collection()
const mongodb = require('./mongo')()
// it creates a new function for our aliases
Client.aliases = new Discord.Collection();
// it creates a new function for our cooldowns
const cooldown = new Set();
const userSchema = require("./schema/user-schema")
const Levels = require("discord-xp");
const canvacord = require("canvacord");
const { MessageEmbed } = require("discord.js");
var moment = require('moment')
Client.on("message", async (message) => {
if(!message.member.guild.me.hasPermission(["SEND_MESSAGES", "EMBED_LINKS", "USE_EXTERNAL_EMOJIS"])) return;
})
With handler ?
yes
fs.readdirSync('./commands/').forEach(dir => {
//in the cmds folder, we gonna check for the category
fs.readdir(`./commands/${dir}`, (err, files) => {
// console log err (catch err)
if (err) throw err;
// checking if the files ends with .js if its a javascript file
var jsFiles = files.filter(f => f.split(".").pop() === "js");
// if there is no cmds in the file it will return
if (jsFiles.length <= 0) {
console.log("Can't find any commands!");
return;
}
jsFiles.forEach(file => {
// console the loaded cmds
var fileGet = require(`./commands/${dir}/${file}`);
console.log(`File ${file} was loaded`)
// gonna let the cmds run
try {
Client.commands.set(fileGet.help.name, fileGet);
// it search in the cmds folder if there is any aliases
fileGet.help.aliases.forEach(alias => {
Client.aliases.set(alias, fileGet.help.name);
})
} catch (err) {
// catch err in console
return console.log(err);
}
});
});
});
do you have an event handler?
No
i need to see all your Client.on()
Client.on("ready", async () => {
console.log(`π€ ${Client.user.username} is Online!`)
function randomStatus() {
let status = ["π€ Wolfy Bot", "π€ w!help", "π€ Poob Beep"]
let rstatus = Math.floor(Math.random() * status.length);
Client.user.setActivity(status[rstatus], {type: "PLAYING"});
}; setInterval(randomStatus, 5000)
})
Other logs codes
I can't send them
how many Client.on("message") do you have?
9
show them
literally just remove the private part before sending
Check your dm @quartz kindle
;\
the general rule of thumb: You're asking for help in this server, your code doesnt work, no one is gonna steal it 
It's the index.js it's all working
Because it is too bad to steal
you also have 9 message event listeners
so let me explain
when discord sends you a message
it has no content
it sends it to ALL your client.on("message") at the same time
it does not send it to one, then another
they do not affect each other
so your permission checking from one client.on("message") does not affect the code in another client.on("message")
unless you create a function* to call the next message event handler when needed
Β―\_(γ)_/Β―
add permission checking to all your client.on("message")
& how to make it affect the commands file
or put all your code in 1 client.on("message")
ok
do the second one plz
I can't it's on handler
yes you can
.info
let button = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId(`Hasnoid`)
.setLabel('Share:')
.setStyle('PRIMARY')
.setDisabled(true))
.addComponents(
new MessageButton()
.setCustomId(`pool_${user}`)
.setLabel('1')
.setStyle('SUCCESS'))
.addComponents(
new MessageButton()
.setCustomId(`pool_${user}`)
.setLabel('3')
.setStyle('SECONDARY'))
.addComponents(
new MessageButton()
.setCustomId(`pool_${user}`)
.setLabel('9')
.setStyle('DANGER'));
message.channel.send({embeds:[exampleEmbed],components:[button]});
is something wrong here
DiscordAPIError: Invalid Form Body
components[0].components[2].custom_id: Component custom id was already specified
components[0].components[3].custom_id: Component custom id was already specified
okay makes sense 
π
Nonetype has no attribute 'request'
import requests
import discord
from discord.ext import commands
import time
import random
import asyncio
client = commands.Bot(command_prefix = "$$")
client.remove_command('help')
@client.event
async def on_ready():
print(f"Successfully logged into {client.user.name}")
async def generate_meme():
#Fetching the given api and sorting out stuff
api_url = "http://meme-api.herokuapp.com/gimme"
fetch = requests.request("GET", api_url)
res = fetch.json()
title = res['title']
subreddit = res['subreddit']
image = res['url']
upvotes = res['ups']
author = res['author']
link = res['postLink']
prev = res['preview']
preview = random.choice(prev)
#Setting up the embed
embed = discord.Embed(color = discord.Colour.blue())
embed.set_author(name = title, url = f"{link}")
embed.add_field(name = "**β’Subreddit:**", value = f"_r/{subreddit}_", inline = False)
embed.add_field(name = "**β’Upvotes:**", value = f"_{upvotes}_", inline = False)
embed.add_field(name = "**β’Author:**", value = f"_{author}_", inline = False)
embed.add_field(name = "**β’Preview:**", value = f"[Click me](prev)", inline = False)
embed.set_image(url = image)
#Sending the embed to the given channel
channel = await client.fetch_channel("873035924936753192")
await channel.send(embed=embed)
asyncio.sleep(5.0)
client.loop.create_task(generate_meme())
client.run()
Here's the code
I've been curious what happens if you register two handlers for the same event like message create
Does it run both at the same time or just the last one
both at the same time

Wonder how that would affect global variables
Or anything that gets modified by both functions
in a single threaded language like js, the first callback will run first
at least while the code is synchronous
do you have any file or folder called "requests"?
I have an asynchronous function. I am using settimeout. There is a request inside the function. When there is an error, I cannot catch it with try catch, how should I fix it?
async function f() {
request({url:url,json:true},function(err,response,body){
if(response.statusCode===200){
//somethings doing
}else{
var msgE = new Discord.MessageEmbed();
return msg.channel.send(msgE.setFooter("Error"));
}
});
}
setTimeout(f, 1500');
Ight
if your request function does not work with promises, you need to wrap it in one
function f() { // does not need to be async if it returns a promise
return new Promise((resolve, reject) => {
request(..., (err, res, body) => {
...
resolve(body) // or reject(err)
})
});
}
if any error how catch ?
f().catch()
ooh thx
or try { await f() } catch() {}
but with settimeout possible ?
setTimeout(() => f().catch(e => ...))
thx so much
also, if you want to return from inside the promise, use resolve instead of return
for example resolve(msg.channel.send())
thx
<!DOCTYPE html>
<script>
var DinoNuggyCount = 0;
</script>
<html>
<head>
<title>Dino Nuggys</title>
</head>
<body>
<a href=# onclick="add()">
<img scr="img/dinonuggy.jpeg" alt="Dino Nuggy">
</a>
<br><br>
you got:
<input type="text" id="text" disabled style= text-align:center>
<script>
function add() {
DinoNuggyCount = DinoNuggyCount + 1
document.getElementById('text').value = DinoNuggyCount;
document.title = DinoNuggyCount + "DinoNuggyCount";
}
</script>
</body>
</html>
the image wont show on the page and i have no idea why
Are you using a webserver like express
repl atm
i use repl to test stuff
also yea
see i said it my self
tim notices the little things smh
i have a feeling tim actually reads the code people give. everyone else skims it.
π
True
I need to learn to actually read code instead of skimming for a problem
you earn credits, not money
you can only spend them on ads, you cannot convert it to actual money
unless you are tim and cheat the system
Cant you sell the ads to others?
doubt
no idea
Hey.. in slash commands, I heard there are two types, global and local? What's the difference?
local = guild only
Not sure how I can make my slash commands global.
Every tutorial in YouTube is showing local commands... π
show code
you just dont give a guild id
You simply don't give a guild id
Ah.
If you are using d.js that is
if you're using client.application.commands, just dont give it an id
idk how any other lang does it
otherwise if you're using guild.commands, use client.application.commands instead
I'm still trying to setup slash commands in my current folder.
I have normal commands right now that uses prefixes and the message create event, I'm trying to figure out how to transition them.
discord should eventually create a command manager dashboard
.. so I'm currently following up a tutorial since I'm legit, LOST.
while there isnt one, someone already made one on github, you can try using that
const { readdirSync } = require("fs");
module.exports = async bot => {
const load = dirs => {
const commands = readdirSync(`./src/commands/${dirs}/`).filter(d => d.endsWith('.js'));
const commandArray = []; //
for (let file of commands) {
const pull = require(`../commands/${dirs}/${file}`);
bot.commands.set(pull.config.name, pull);
if (pull.config.aliases) pull.config.aliases.forEach(a => bot.aliases.set(a, pull.config.name));
commandsArray.push(pull); //
bot.on("ready", () => { //
bot.guilds.cache.get("...").commands.set(commandArray); //
}) //
};
};
["bughunting", "economy", "fun", "image", "information", "management", "music", "owner", "partnership", "settings", "social", "utility"].forEach(x => load(x));
};
This is the code in my command handler.
The codes that has a // after it are the codes the tutorial told me to add for the slash commands.
Ah..
Yes.. no I know.. it takes some time for it to actually update.. alright.. I'll use locally for some time then.
local commands are instant
global commands take to a maximum of an hour to propagate (ive gotten them within 5-10 minutes though)
God.. that name.
Thanks!! .. but if I don't want to transfer all the commands I have in my folder to slash commands.. should I make a new collection?
I have here a web server from the official djs guide:
const fetch = require('node-fetch');
const express = require('express');
const { clientId, clientSecret, port } = require('./config.json');
const fs = require('fs');
const app = express();
app.get('/', async ({ query }, response) => {
const { code } = query;
if (code) {
try {
const oauthResult = await fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
body: new URLSearchParams({
client_id: clientId,
client_secret: clientSecret,
code,
grant_type: 'authorization_code',
redirect_uri: `http://localhost:${port}`,
scope: 'identify',
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
const oauthData = await oauthResult.json();
const userResult = await fetch('https://discord.com/api/users/@me', {
headers: {
authorization: `${oauthData.token_type} ${oauthData.access_token}`,
},
});
console.log(await userResult.json());
} catch (error) {
// NOTE: An unauthorized token will not throw an error;
// it will return a 401 Unauthorized response in the try block above
console.error(error);
}
}
return response.sendFile('index.html', { root: '.' });
});
app.listen(port, () => console.log(`App listening at http://localhost:${port}`));
But the server doesnt load any script files or css files linked in the html file. How can I made him to load them?
like local script/css files?
youll need to host those too, probably will want to use a public folder with express(or a webserver).
https://expressjs.com/en/starter/static-files.html
hello
can anyone help?
@bot.event async def on_guild_add(ctx): adrian = bot.get_user(811965393781653595) await ctx.send_adrian(f"Added to {ctx.guild.name}")
it wont work
on_guild_add is not a valid event
and what to do?
era what happen to your pfp
era HACKED?1!!?!?
I believe you are looking for the on_guild_join event. Furthermore, the event takes in the guild parameter representing a discord.Guild object
ctx is already a guild
ctx is the variable representing the guild. As a result the guild object has no attrubute to guild. you would want to do ctx.name
Because ctx is the guild
remove ctx
put guild
like
@bot.event
async def on_guild_join(guild):
and change ctx.guild.name to guild.name
Not needed, they're free to allow ctx to represent the guild.
ok
ye it works aswell 
May cause confusion though
tell me if that works @crimson kindle
like this?
no
ok wait
ok
"ctx its not defined"
remove ctx
ok
cuz u changed ctx to guild
because you're passing in guild now.
Not ctx
yep
Furthermore as future reference, it is fairly unique for an event to take ctx as a parameter, there are but a handful which do.
lemme test
@bot.event
async def on_guild_join(guild):
adrian = bot.get_user(811965393781653595)
await adrian.send(f"Added to {guild.guild.name}")
there is 2 guilds :l
no, just guild.name
in 2nd line?
discord.Guild has no attribute to guild.
guild.guild.name should be guild.name for the reason above
ok
@bot.event
async def on_guild_join(guild):
adrian = bot.get_user(811965393781653595)
await adrian.send(f"Added to {.guild.name}")
now the not didnt send the message
I didn't get that yet
@earnest phoenix just the guy send scam link
I am sending a message: js message.reply()Then I am catching an error js .catch(error=>{})But now what I want is, if there is no error in sending the reply, I want to send another message. How do I do that?
add the bot to a server
and make sure that the bot already has a mutuals with u
Why is there a period prior to the guild object? That will most definitely encur an error.
Ok
thats great
Yea
Is it normal for v13 d.js to have a error bypass a catch function?
message.reply().then(() => success()).catch(error=>{});
// or
try {
await message.reply();
success();
} catch {}```
It's giving me the error instead of sending a embed I have for errors
I'm working on eval
If you're dealing with promises you must use await for it to be able to catch
There are fails here?
'@bot.command()
async def sl(ctx):
user = await bot.get_user(811965393781653595)
await user.send("Servers connected to:")
for guild in bot.guilds:
await user.send("guild.name")'
try {
//success embed
} catch (e) {
//error embed
}
how my code is setup for refrence
try catch only works on promises if they are awaited
ReferenceError: success is not defined
Do whatever on success()
.then(() => success(message.reply(`Sent!`)))
Without the success() part
Sorry lol
I thought it is a function
I'm bad at explaining
alguien me puede ayudar con un problema del js
Got it working
Basically the code that's doing the actual evaluation had to be in the try function
Nothing await related
ΒΏCuΓ‘l es el problema?
my discord bot won't connect
No te preocupes, soy de MΓ©xico
No creo que haga falta el inglΓ©s
pero bueno
yo colombia
que bueno que hablas espaΓ±ol
medio se
Bueno, el problema es quΓ© el bot no se conecta, ΒΏCierto?
si
ΒΏAlgΓΊn error? ΒΏQuΓ© acciΓ³n hicistΓ© antes de que sucediera este error?
English only here please! You can speak other languages in #general-int π
dm?
Yea
oki
Gracias ! 
this is unrelated to bot developing, but still coding so ill ask here
i am familiar with node.js, but i never used js in html docs
i have a button:
<button type="button" class="hidemusicbtn" onclick="hideMusic()" name="hide-music">Hide music</button> <br>
and in the script tag i have this:
function hideMusic(){
document.getElementsById('actual-music').style.display = "none"
}```
but on click it does absolutely nothing, what have i done wrong?
Does anybody know how to do reactions on replit? (using python btw)
ok, i'm now getting this error
getElementById not Elements
An ID should always be unique, that's why
yes i just realised it while you were pinging me, i am really really dumb
.then(msg => {
msg.edit(embed)
})```
Doesn't work anymore?
.edit takes an object now. You can't just pass a string or embed instance.
You can send embeds with { embeds: [...] }
Hey..
I'd like to ask why this code isn't sending the embed.
https://sourceb.in/EBfieD6RcZ
OH
You see.. I'm smart..
I found the issue.. oh god.
lol
msg.edit({ embeds: [embed] })
})``` v13 π
const collector = new Discord.ReactionCollector(
msg,
(reaction, user) => Object.values(reactionControls).includes(reaction.emoji.name) && user.id === message.author.id,
{ time: 5*60000, dispose: true }
);```
anything to change here, after v13?
because the bot is not reacting to the message author but itself
I love how I just switched 2 simple commands out of 113 (111 advanced) to slash commands.. now 111 left to go.. π
yea, Klay helped me with that already... Thnks
goodluck
β€οΈ
Hey i.got type error in
let vote =client.topgg.hasvoted(message.aurthor.id)
if(!voted){
message.reply('first vote me on top.gg') ```
Showing has voted undefined
is that even a thing?
hasvoted() is not a function
Umn
I want a vote require commamd
So i maded with help of my friend
hasVoted() not hasvoted
Ok
^
Is there a way to check if the bot has the applications.commands scope in a guild?
not that I know of
Without trying to fetch the commands and handle the error.
actually I don't know anything
Still showing same error
your client is undefined
Mhmm
or .topgg is not how you should type it
show the declaration of client.topgg
You're also passing in message.aurthor.id, which doesn't exist
That i corrected at morning only u only told me
oh yeah i remember
So what to correct π€
message.author.id
That i know lmao what to write instead of this
what you wrote and what I wrote are the two different things
I written the same in replπ no difference
Umnn
show me the code
oop sorry i thought that was py
idk d.js
whats the problem?
Showing type error hasVoted not defined
let vote =client.topgg.hasVoted(message.aurthor.id)
if(!voted){
message.reply('first vote me on top.gg') ```
Ye
wheres hasVoted
2nd line
?
Clinet.topgg.hasVoted
send the actual error
Client.topgg does not exist
pog
client.topgg
Is ok?
This only i putted butπ€
i dont know
Umn
have u got client.topgg = or anything similar
client.topgg
He is still passing message.aurthor.id
Do i remove it?
i dont get what that has to do with his problem though π€
you spelled AUTHOR wrong
Umn lel leme check
just focus on one thing at a time, you're going to confuse yourself
It is ok
Yee
?
I want to make a vote require commamd actually
Getting this result
.. yes client is going to log something
where are u defining client.topgg u still havent answered my question
I said log
no error
console.log(client.topgg)
Umnn in main file index.js u can say
you're not defining client.topgg anywhere
Mhm
so, define it and ur code won't error
do not put any api token in any files
use .env
since you are using replit, anyone can go and see your tokens
^^
Ok
As it is showing same error
But
just a note, u kinda need to learn the fundamentals of javascript / any language before making a discord bot
discords api is a beast
^^
Umnn
but u done client.Topgg, u've still not defined client.topgg or client.Topgg
watch yt tutorials and copy as much code as u want only if u understand whats going on
And try to make it as myself in a way as possible
That's the thing some of yt tourtial has different thing and we are making different
Since
I try to make it as my way as possible
yes, if u understand whats going on you'll understand what to change and keep
@digital ibex his index.js:
const Topgg = require("@top-gg/sdk")
client.Topgg = new Topgg.Api(sEcret token)```
Why do even include the topgg/sdk in your index file and try to pass it? Include it in your 247.js
i see now
Useless to bind the class to your client if you need it in your module only.
Just said watched yt tutorial
console.log(client.Topgg) right beneath where u define it
prob for vote only command
And i have to make other commands too vote only so its just useless to right it everywhere
Checking if the member has voted in your module is okay. Then save it's for example in your database if you need to keep that.
His 247.js
module.exports = {
name: "24/7",
botPermission: ["EMBED_LINKS", "READ_MESSAGE_HISTORY","USE_EXTERNAL_EMOJIS","ADD_REACTIONS","CONNECT","SPEAK","DEAFEN_MEMBERS","MOVE_MEMBERS","USE_VAD"],
aliases: ["247"],
run: async (client, message, args) => {
let vote = client.Topgg.hasVoted(message.aurthor.id)
if(!voted){
message.reply('first vote me on Top.gg')
// here we done you can do this in any command and make it vote only
} else{
const player = message.client.manager.players.get(message.guild.id);
if (!player) return message.channel.send({
embed: {
color: "RED",
description:' there is nothing playing'}}).then(m => m.delete({ timeout: 5000 }));
// Check that user is in the same voice channel
const { channel } = message.member.voice
// toggle 24/7 mode off and on
if (player.twentyFourSeven) {
player.twentyFourSeven = false;
return message.channel.send({
embed: {
color: "GREEN",
description:' 24/7 mode is **disabled**'}});
} else {
player.twentyFourSeven = true;
return message.channel.send({
embed: {
color: "GREEN",
description:' 24/7 mode is **enabled**'}});
}
}
}
}```
@compact sluice ?
told you replit is not private
anyone can see everything you did
Pardon me, But what even is guildMembersChunk
π πΏ yee
Hmmm
an event which is fired when discord sends chunks of members (thats what most libraries do)
Not gonna talk about your code and typos in it but do you really send a request to the topgg API any time someone runs the command to check if he has voted?
Checking if the member has voted in your module is okay. Then save it's for example in your database if you need to keep that.
One of a few typos to mention...
let vote = ...
if(!voted) ...
After doing this now also error showing but error is changed
Now it is showing
Cannot read property id of undefined
How do I get the server of the user he is in and sharing with the bot?
I have these scopes selected and followed these guide:
https://discordjs.guide/oauth2/#a-quick-example
You can filter over the guilds the user is in (easier to filter over since users can only be in at max 200 guilds while bots can be in Infinite) and check for if the client is in that guild.
Is there a way to check if the bot has the
applications.commandsscope in a guild?
Without trying to fetch the commands and handle the error.
Nope :)
errr. damn
how tf do i add a \ as a string?
what?
As it only picks up the regex function of it
""
realfinal = 'Spotify-'+finalstring+`\`
it only sees that
\ as a regex function
You're probably looking for \\
\ is an escape character. You escape the escape
eee why do people concat looks so ugly
Why do people use string concat instead of template literals
Concentration spanning multiple lines looks much better than templates spanning
also syntax highlighting...


