#development
1 messages · Page 1813 of 1
just use a good old for loop
then you can swap out the increment for a column search
flipping it would be a mutation
take a sip of immutable architecture
// rows
for(let row = 0; row < board.length; row++) {
for(let col = 0; col < row.length; col++) {
if(col > 0 && board[row][col] !== board[row][col-1]) return false;
}
}
// cols
for(let col = 0; col < board[0].length; col++) {
for(let row = 0; row < board.length; row++) {
if(row > 0 && board[row][col] !== board[row-1][col]) return false;
}
}
damn so I was almost there
I also wrote 2 for loops but was like no this is not it lol
well imma head to bed, gl on the diagonal one
i want to get rid of the for loop somehow
const checkIsColumnWinner = board => board[0].reduce((acc, cell, columnIndex) => {
if (acc) return acc;
for (let rowIndex = 0; rowIndex < board.length; rowIndex++) {
if (board[rowIndex][columnIndex] !== cell) {
return false;
}
}
return true;
}, false);```
Anyone here have experience with the twitter API?
Client.stream('statuses/filter', { track: "@BotPunny" }, function (stream) {
stream.on('data', tweet => {
console.log(`${tweet.user.name} (@${tweet.user.screen_name}) - ${tweet.text}`);
if(tweet.text.toLowerCase() === `@botpunny test`) {
console.log("responding")
Client.post("statuses/update", { in_reply_to_status_id: tweet.id, status: "Test Success" }, (err, data, response) => {
if(err) console.log(err);
console.log(1)
});
}
});
});
It sends the Test success, but not as a reply, instead as a regular tweet
.entity-header__button-text, .entity-header__button-icon {
background: rgba(180, 255, 198, 0.504);
}
.entity-header__button:hover,.entity-header__button-text:hover, .entity-header__button-icon:hover {
background: rgba(180, 255, 198, 0.704);
}
when im hovering it changes the color back to that color and not the color specified in my css, am i using the wrong element??
Try background: rgba(180, 255, 198, 0.704) !important;
Feels like I've seen you somewhere
Hey, is anyone here goodie at javascript?
A lot of people here
cool. I am having an issue with a little piece of code.
https://pastebin.com/6BtFJkY9
When the clickMenu event gets triggered (from another package that isnt d.js) only the client id gets printed, but menu.id results as null. when I switch client and menu in the execute area, then only menu.id prints correctly and client.id returns null. Anyone have any idea to why this is happening? I might be a little tired as it is almost 2am 😅
How can I make args[0] have the first letter in uppercase?
For example: person uses !command hello, and it replaces the hello for Hello
args[0].charAt(0).toUpperCase() + args[0].slice(1)
Ah callum beat me to it
seym
Try js execute(...args) { console.log(args); },
charAt(0) means the first character?
See what you get
yes
You don't need it; just use args[0][0]
ok, thank you so much
...args as in being client, menu? Or just ...args
wdym?
It can be anything, it's a parameter name
Ok, give me a second
const args = ["aaa", "bbb"];
args[0]; // "aaa"
args[0][0]; // "a"```
args[0][0] is the first letter?
args[0].charAt(0).toUpperCase() + args[0].slice(1)
and
args[0][0].toUpperCase() + args[0].slice(1)
both work
const args = ["abc", "efg"];
args[0]; // "abc"
args[0][0]; // "a"
args[0][0].toUpperCase() + args[0].slice(1); // "Abc"
and thanks to 
Anyone have the reasoning to open and close db connections upon each request rather than opening a connection upon startup and keeping it open? I was told always close when done with the function. But I have someone asking why.
yeah, I get it now thanks 🙂
I console logged ...args as you said, and I got a huge output https://pastebin.com/hZNYpwKn
So it does return the MessageComponent properly
There's only 1 parameter
If you want the client, use menu.client
And if I want to use the menu?
Just menu
wtf?
Ok, im really sorry, a million thanks to you for the js support, but do I leave in the execute part the menu and client?
There is only 1 parameter
That would be menu
IDK
Check your code
Or send it here, people can help
What's the problem? It's not unmuting the member?
He said its unmuting them, but it remutes them a short time after
🩴
poggers
What about your mute command?
i have a unmute code do you want
unless you have a timer that periodically checks if the user is muted or if it expired
flazepe, again thank you for helping me, you are a genius
execute(menu) {
console.log(component.client.id);
console.log(menu.id);
}
Am I doing it wrong?
Does it work?
Just in case
I was skimming through the pastebin you sent earlier
There's actually 2 parameters it seems like

So you got it right menu, client
client.on('message', msg => {
const error = "❌";
const timeing = "⏱";
const success = "✅";
const lodeing = "🤔";
let args = msg.content.split(" ");
if (args[0] === prefix + 'unmute') {
if (msg.author.bot) return;
if (msg.channel.type == "dm") return msg.channel.send(new Discord.MessageEmbed().setColor("RED").setDescription(error + ` **You Can't Use This Command In DM's!**`).setFooter(`Request By ${msg.author.tag}`).setTimestamp())
if (!msg.member.hasPermission('MANAGE_ROLES')) return msg.channel.send(new Discord.MessageEmbed().setDescription(error + " **You Need `MANAGE_ROLES` Permission To Use This Command!**").setFooter(`Request By ${msg.author.tag}`).setTimestamp())
if (!msg.guild.me.hasPermission('MANAGE_ROLES')) return msg.channel.send(new Discord.MessageEmbed().setDescription(error + " **I Can't Kick Any Member In This Server Becuse I Don't Have `MANAGE_ROLES` Permission!**").setFooter(`Request By ${msg.author.tag}`).setTimestamp())
let user = msg.mentions.members.first()
if (!user) return msg.channel.send(new Discord.MessageEmbed().setDescription(error + " **Please Mention Same One!**").setFooter(`Request By ${msg.author.tag}`).setTimestamp())
if (user.id === msg.author.id) return msg.reply(new Discord.MessageEmbed().setDescription(lodeing + " **WTF Are You Doing ??**").setFooter(`Request By ${msg.author.tag}`).setTimestamp())
if (!msg.guild.member(user).bannable) return msg.reply(new Discord.MessageEmbed().setDescription(error + " **I Can't Unmute one high than me >_<**").setFooter(`Request By ${msg.author.tag}`).setTimestamp())
var muteRole = msg.guild.roles.cache.find(n => n.name === 'Muted')
if (!muteRole) return msg.channel.send(new Discord.MessageEmbed().setDescription(lodeing + ` **WTF Is That ?? [ Super Error ]**`).setFooter(`Request By ${msg.author.tag}`).setTimestamp())
user.roles.remove(muteRole)
msg.channel.send(lodeing + " **Processing The Unmute Function**").then((m) => {
m.edit(success + " **Processing is complete**")
})
msg.channel.send(new Discord.MessageEmbed().setDescription(success + ` **${user} Has Ben Unmuted By <@!${msg.author.id}>**`).setFooter(`Request By ${msg.author.tag}`).setTimestamp())
}
})```
سخققغ
sweet jesus
sorry
Allah

That is...
Wait, try again js execute(menu, client) { console.log(menu.id, client.id); }
shit why
Well yeah you don't expect it to work just by pasting the code
host@host-MS-7A38:/mnt/HDD/panel-bot$ node .
No buttons.
The bot has awakened
Logged in as: something, idk lol#6326
customid undefined
Looks like a no
If its bc im dumb I agree
As in, how did you run that execute method
he say client is not defined
Show your event handler code
I run the execute thing through my handler in my index.js
Let me pastebin it
^event handler code
ok ammm
O
oh no
Try js execute(...args) { console.log(args.length); }
If it's not 2 then something is off
Ok one second
What package do you use for components by the way?
Its 2
Can you elaborate?
Its kinda really late so my brain might be a little dead
When the clickMenu event gets triggered (from another package that isnt d.js)
Im using discord-buttons for the menu system
Ah
I couldnt find anything better than that
Detritus
could it be an issue with the package itself?
Ok coolio, as there isnt much of an alternative other than making my own discord api thing
Time to debugjs execute(menu, client) { console.log(menu.id, menu.client.id, client, client.id); }
yay my fave process
Yeah
I need menus
P sure it doesnt have menus
But I'd say it's better to wait for the official release
A lot of stuff can break while it's in development
when I tried using the charAt I had this error:
at Object.exports.run (/home/runner/Bulba-Bot-Recover/commands/info.js:13:52)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:312) 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: 2)```
what the fuck??
[]
hi @crimson vapor
hi @pale vessel
The log is so long that it exceeds my terminal limit
wdym log args?
console.log(args)
console.log(args[0])?
Never mind
you use replit or vs
I legit just scrolled past to the previous attempts
Is everything defined?
Clear ur terminals bois
nope
@earnest phoenix https://discordjs.guide if you’re struggling with the basics
good send me an invite an my dm
Thing is I have no fucking clue what undefined
(node:447) [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.

@long badger don’t spoon feed him if you’re gonna help him on replit though
more than 3 things undefined
🩴
OK then make it short js execute(menu, client) { console.log(menu.id, menu.client.id, client.id); }
See which one is undefined
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
sorry my en language is not so good
So it was never broken @hexed sedge

We're wayyyy of the track
What was your issue in the first place? @hexed sedge
are you the one with an unexpected token error?
probably me 
no
I'm not asking help about it, it's cause flazepe asked me to try a console.log and I recieved this unexpected token 
@pale vessel perhaps my NodeJS being older charAt won't work somehow?
Err, no
mine is v12.16.1
breh
and what's client.id supposed to be?
yes

it just clicked
It confused me since you said null
It can never be null if it's not a property
It would have been undefined
Naw
omfg thanks for the patience man <3 super sorry, just tired as it is 2:47am atm
It's all good, you should get some sleep exdee
lmfao yeah, just wanted to figure this out
its only 8am tho
Yeah I woke up at 6:50am or something
oh
I realized I was being dumb and I forgot to fix one thing on the code, the charAt is actually working 
thanks flazepe 🙂
this one didn't work
so I used the charAt
You sure?
because why not
const args = [
['277183033344524288']
]```
Try again, could have been because of your code earlier
It would be weird if it doesn't work
Actually, doesn't really matter if charAt() works
If it works it works
yeah
only one more thing
if I want to use with args[1], I might replace charAt(0) for charAt(1) and slice(1) for slice(2)?
if message.channel.id in gloabal_chat:
TypeError: argument of type 'int' is not iterable
not sure what to do here
cause this is the only one not working for me
only args[1]
Provide your code along with this so we have more information to work with
@commands.Cog.listener() async def on_message(self, message): if message.channel.id in talk_channels:
yeah, I did but I'm recieving error
Keep everything else as is (slice, etc.)
You sure args[1] is defined?
@pale vessel if you ever need anything lmk
but basically when it's the one that fetch the args[1] it works perfectly, but when it's the one that fetch the args[0] it gives me this error:
at Object.exports.run (/home/runner/Bulba-Bot-Recover/commands/info.js:13:52)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:724) 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: 5)```
I'm not sure why I'm getting an error, could anyone help?```js
//Things above the code defining variables...
//async function STARTS
async function connect(){
mongo.connect((err) => {
console.log("MongoDB connected for Beyblade.js");
});
let ids = mongo.db("main").collection("ids");
const id = ids.find({});
Promise.all([id]).then(data => {
let beys = data[0];
beys.forEach(bey => {
datas[bey._id] = {
latest: bey.latest,
name: bey._id
}
});
console.log("Updated data!");
});
setInterval(() => {
mongo.db("main").collection("ids").updateOne({_id: bname}, {$set: {latest: datas[bname].latest}});
}, 600000);
}
//async function ENDED
//connect and continue
connect();
//rest of the code
}
async init(){
return true;
}
}
module.exports = Beyblade;```
np, just want a way to thank you
Error: xl MongoClient must be connected before calling MongoClient.prototype.db
anyways, Ill take your advice and go to sleep. Goodnight #development
Can you log your args again? console.log(args)
goodnight lol
Also, can you show me your charAt() code again
ok
ok
the section of code
@commands.Cog.listener() async def on_message(self, message): if message.channel.id in talk_channels:
the error
if message.channel.id in gloabal_chat:
TypeError: argument of type 'int' is not iterable
(node:862) [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.
I'm confused with my code getting the error, seeing that it does connect to the database before calling mongoclient
args[1].charAt(0).toUpperCase() + args[1].slice(1)```
that's what I recieved I think
I think you copied a part of your error
let me check again
Should be above the error, depending on where you put that line of code
If you put it after the charAt() part, then it wouldn't show since it errored
this is all:
(node:862) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'charAt' of undefined
at Object.exports.run (/home/runner/Bulba-Bot-Recover/commands/info.js:13:52)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:862) 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: 2)```
Check this
ph
this is it
lol
[ 'a' ]
this was the log
and what I sent in command
So you did !command a?
yeah
Then args[1] wouldn't have existed 🩴
I'm not sure why you want args[1] though
[ 'a', 'b' ]
But you need to add a check first if you need that
ok, so basically this:
this is a simple "pokédex" command, and you can simply do pb!pokedex pikachu to see a pikachu, or pb!pokedex shiny pikachu to see a shiny pikachu (so it fetches args[1] here)
wdym?
when it fetches args[1] I only need the args[1]
args[0] is only to check if args[0] === 'shiny'
So js const toReplace = args[1] ?? aargs[0]; toReplace[0].toUpperCase() + toReplace.slice(1);?
A
Typo but yeah
what does this do exactly?
It tries to get the second arg (args[1]) if exists
If not args[0]
And then the usual first letter capitalization
?? can be substituted for ||
yeah, I'm getting kinda lost
can I send in your DM a pastebin link with my current code?
?? is cooler than ||
im not clear about the ?? operator but isnt it the same as ||?
No
You know sometimes empty is something not empty 
Say you have to things
wot does the ?? do?
if you want an empty string then you would use ??
If the left side is null it will use the right side
It checks if your val is defined and not null
i realised a few days ago that ![] returns false
yeah
ye same as ||
arrays are truthy
I mean, yes and no
Anything defined not 0 is true is JS
so + is the same as .length?
JS = false
nope
It really doesn't like me doing this in typescript. (UserName = message.author.id, UserData = {})
Anyone know how to get rid of that? Cause it's really starting to piss me off
0.1 + 0.2 === 0.3 this returns false 
yes
floating point numbers are weird
it does that in most languages tho
Anyone know how to solve my issue or if I can do it in a way that does not cause an error like that
what error does that say?
You should use a record
Which is?
It is another way of making an object
Since the Object type is a bit weird
Say you wanted to make an object where the key is a string and the value of the that key will also be a string
Well, the value of that string key is also an object xD
const settings: Record<string, string> = {}
With another few objects inside
Errrr
Honestly no idea rn
As you can see, it works just fine. But it just comes out as an error
Use an interface?
You could also use an interface as well ig
You have to
And how would I do that?
Or well, any 
I don't know interfaces. I use my previous programming knowledge to try to build bots
Make an interface for it and use Record<string, Interface>
Also Mistyy, I wasn't asking how to make an interface. I meant "How do I make a multi layered interface that covers my extensive structure"
Multi-layered interface?
Idk man. As I said, dunno interfaces
Guys what are your opinions on vim
But you said you know how to make interfaces 🩴
Multi-layered as ints interface SomeInterface { buildings: { house: number; }; otherProp: string; ... }?
Not sure what you mean
I mean I have an object
Gimme a sec
{
"User1ID": {},
"User2ID": {}
...
}
That is what it cant figure out
That's exactly what Record does
Okay, I'll go see how to use record then, and if it does what I want it to, cause it's both writing and reading data that I'm having trouble with
No idea what it is
That’s because JS interprets 0.1+0.2 to something like 0.300000….1
It will be true if you use math.round
console.log(Math.floor(0.1 + 0.2) == Math.floor(0.3));
Don’t think about it as it doesn’t make any sense 
Record<string, Interface> is equivalent to ts interface Obj { [key: string]: Interface; }
It's a nifty utility type
again object isn't a type you really wanna use
object should be an interface
Why Mistyy? What errors will I encounter?
Otherwise it will be treated as Record<any, any>
Wdym
Oh, okay
Message.member is undefined if I'm not wrong
It's powerful if you'd like to invest some time to learn trillions of shortcuts 
You won't really get an error
I mean, it's not inherently a JS-specific problem. It's just the way floating point numbers are represented in most languages
message.author is a user
No, you need the message.member for that
I'm pretty sure it's because the user is just the discord user, but the member is the user in the guild memory
Shouldn't it be message.author.member?
Or am I wayyyyy off?
No, message.member
The member object is associated with a guild, whereas the user object is not.
Yup
That's weird
It's not weird
You can get the user off the member but not the member off the user
User has no ties with a guild
so it makes no sense for you to be able to get a member object
^^
flazepe, would the interface be constructed like this?
Sure
You should, err, replace those nasty any with a typed object 
Nope, an interface
typed
Use records
If you put object it won't be any different than any
Oh, so put an interface within the interface
Yes
Uhhhh, okay xD
Only use records if you need the key to be any, or a simple structure, like Record<"firstName" | "lastName", string>
So I'm just defining my entire structure rn xD
Why? I need it to be a string anyways
No, you use Record when you wanna make a typed object.
Depends on what "message" is
Try to console.log(message) before calling that line
Check if it has the .member
@commands.Cog.listener() async def on_message(self, message): if message.channel.id in talk_channels: stats = levelling.find_one({"id" : message.author.id}) if not message.author.bot: if stats is None: newuser = {"id" : message.author.id, "xp" : 100} levelling.insert_one(newuser) else: xp = stats["xp"] + 5 levelling.update_one({"id":message.author.id}, {"$set":{"xp":xp}}) lvl = 0 while True: if xp < ((50*(lvl**2))+(50*(lvl))): break lvl + 1 xp -= ((50*((lvl-1)**2))+(50*(lvl-1))) if xp == 0: await message.channel.send(f'well done {message.author.mention}! You leveled up to **level:{lvl}**')
error-
if message.channel.id in talk_channels:
TypeError: argument of type 'int' is not iterable
Could be that the message is from a DM
Make sure message.member exists
I suppose the member isn't cached
Yes, but can you send a screenshot further up. Instead of only sending one line?
That would also be a reason
if (!message.member) return; EZ
if (message.guild) {} else return; EZ
client.on("message", async (message) => null); EZ
const players = [
{player: "player1", rating: 1200},
{player: "player2", rating: 1200},
{player: "player3", rating: 1219},
{player: "player4", rating: 1219},
{player: "player5", rating: 1210},
{player: "player6", rating: 1090}
];
const balanceTeams = ({players, teams}) => {
}
const [team1, team2] = balanceTeams({players, teams: 2});
// team1 = [{player: "player1", rating: 1200},{player: "player2", rating: 1200},{player: "player3", rating: 1219}];
// team2 = [{player: "player4", rating: 1219},{player: "player5", rating: 1210},{player: "player6", rating: 1090}];
how should i write the balanceTeams function without it exploding with large teams?
i basically want the sum of the ratings for each team to be as close as possible
but i dont want to try every combination
there must be a fancy math thing to solve this faster
If there aren't peaks, just order by rating and match first with last
Keep doing it until there are no players left
that might work well enough
Tbf, it'll be the only way to get as balanced as possible teams
Any other way would only increase difference
well trying every combination and would find the rare cases where there are peaks, but it would be exponential
I mean, the peak player will always end up matched with someone
If matched with the worst player it'll result in smaller final value
how would this get split into two team? [1,100,101,200,201,202]
1 and 202 are on a team
100 and 201 on the other
what about 101,200
101 on first team
200 on the lower one
We synced
idk if im correct but yeah
so there would be a running total for each team
and which ever team is higher at the time picks the lowest player
The team with the highest player stays with the lesser option
why does icycast/shoutcast exist
so the first pass the highest and lowest seed the teams, then the next pass it looks at the total for each team first and then chooses the lowest rank for the highest team
Ye
that's going to be fun to write
wdym?
I was trying to get some radio stations beyond listen.moe to work with my lavalink rewrite when I tried to add support for one my bot supports called frisky radio
but trying to get the mp3 doesn't return an HTTP/ response
so, http requests error
Matchmaking is fun, the worst part is composing the MMR
what do you use for metrics?
what kind of metrics? i just put data in Dyanmodb
for example, my tcg players win/lose mmr based on how much damage they cause, with how many cards, sustaining how much damage, etc
like, what defines them as "experient players"
i haven't built that in yet, but my plan is to save those stats in the DB
i have the history command started here
wouldn't that allow abuse?
like, create an alt and keep losing/winning against yourself to manipulate your mmr
each server is sandboxed
the server managers can look out for that
and only people with a certain role can record
ic
JavaScript!
So, I created a new field to the main data model, how can I make it add the new field to all existing data? (MongoDB).
Model? Mongoose?
iterate over the entire collection and update every item
There's no models in MongoDB
models are a bad idea
How does one do that?
that oop thinking
whut
they sent that in #memes-and-media too
Probably had their bot offline during review and got mad that the bot reviewers don't have the time to wait for his bot to become online
that's not what the decline reason says
I see
client.guilds.cache.forEach(guild => {
guild.channels.cache.forEach(channel => {
channel.messages.fetch()
})
})```
fetch is not a defined
Yup
I'm making ticket system and its not working bcz msg is not fetched 😅
const Schema = require('../../models/guild');
module.exports = async (client, reaction, user) => {
let data = await Schema.findOne({ id: reaction.message.guild.id });
if (reaction.message.id === data.ticketMsg && reaction.emoji.name === '🎟') {
reaction.users.remove(user);
}
};
Not working if I reacted to message
how does it not work?
Idk
Its working before
But when I restarted its not working
Its not Removing my reaction
console.log data, reaction.message.id, or use a debugger to see what's going on.
debug your code
Ok
You have to enable partials
?
2021-07-16T06:46:47.693723+00:00 app[worker.1]: Error: Cannot find module '/app/.srcindex.ts' 2021-07-16T06:46:47.693746+00:00 app[worker.1]: at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15) 2021-07-16T06:46:47.693747+00:00 app[worker.1]: at Function.Module._load (internal/modules/cjs/loader.js:746:27) 2021-07-16T06:46:47.693748+00:00 app[worker.1]: at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12) 2021-07-16T06:46:47.693748+00:00 app[worker.1]: at internal/main/run_main_module.js:17:47
I am currently getting this error when I try to start my bot using Heroku as a host (don't judge me, I'm getting a VPS soon). My Procfile is as follows: worker: node -r ts-node/register/transpile-only .\src\index.ts, and this works when I start my bot in my integrated terminal in VSC. Anyone have any idea why this isn't working?
Is it required whether my bot is in only 65 guilds?
You must do it in order to listen for reactions to messages which aren't cached
Ok
The page I sent you even gives you an example
client.on('messageReactionAdd', async (reaction, user) => {
// If a message gains a reaction and it is uncached, fetch and cache the message
// You should account for any errors while fetching, it could return API errors if the resource is missing
if (reaction.message.partial) await reaction.message.fetch();
// Now the message has been cached and is fully available:
console.log(`${reaction.message.author}'s message "${reaction.message.content}" gained a reaction!`);
// Fetches and caches the reaction itself, updating resources that were possibly defunct.
if (reaction.partial) await reaction.fetch();
// Now the reaction is fully available and the properties will be reflected accurately:
console.log(`${reaction.count} user(s) have given the same reaction to this message!`);
Though you don't really need to fetch the reaction if you only need the message ID
but maybe disocrd.js requires you to because it's trash
Fixed it, nevermind, I am far too sleep deprived to realize that I'm stupid and the backslashes were the wrong way ^
let ch = client.channels.cache.find(c => {
c.name == user.username && c.type == 'text';
});
if (ch)
return reaction.message.Reply({
embed: {
title: 'You have opened ticket already!',
color: 'RANDOM'
}
});
Why its not working
Nothing error
I have 4 channel name ᵈʳᵉᵃᵐ乡𝓟𝓻𝓲𝓷𝓬𝓮★᭄ꦿ᭄☆#1111
Several things wrong with this
-
In you're
channels.cache.findthe test function doesn't return anything: Change to:return c.name == user.name... -
To reply to a message use
Message.reply(no capital 'R")
Issue 1 can also be solved by removing the curly braces (in which case lambda returns automatically)
@flat copper
let ch = reaction.message.guild.channels.cache.find(c => {
c.name == user.username && c.type == 'text';
});
if (ch)
return reaction.user.send({
embed: {
title: 'You have opened ticket already!',
color: 'RANDOM'
}
});
Latest code
But still not working
Thats not a function
func(() => value);
func(() => { return value; });
func(() => (value, undefined));
func(() => { value; });```
async func (num) => { return await func(num > 5 ? num > 1000 ? num - 1000 : num ** 1.5 : num + 1 ) }
ez
Whats the intent for cheching if a user is in a vc?
GUILD_VOICE_STATES??
it was
nvm
func (() => { void value })
a text editor that you use inside a terminal
hello hello! I have a question regarding current time for discord bots.
you know how new Date() will show the current time? But it's in UTC. is there any way for it to be such that if I want the bot to generate the current time based on the author's timezone?
you can, but it may also be possible to do something else
hey how do i migrate a channel from one category to another? (in djs)
what are you doing this for?
discord offer timestamps https://discord.com/developers/docs/reference#message-formatting-timestamp-styles so you can just provide the utc time and discord will automatically handle and convert it to the user's local time
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
i'm currently doing timezone conversion. and i wanted to do it such that if the user keys in
26 Jan 15:00
It would show all the converted timezones. but the default one is UTC. I wanted it such that, for instance if I'm GMT+8, the time 26 Jan 15:00 will show all the converted times from GMT+8. if that makes sense....?
OH I WIL CHECK THIS OUT O:
<t:1626431160689>
o
<t:92488294:d>
I'm guessing it's using the Discord epoch cause this definitely aint 53509
<t::d>
are you providing the time in seconds or milliseconds?
milliseconds
ah, unix is seconds
ah
wdym
i am fiding the category by this: js const unclaimedcategory = guild.channels.cache.find(c => c.name == "UNCLAIMED" && c.type == "category")can i instad of an id in the setParent pass the unclaimedcategory variable?
yeah, i think passing either the channel or the id should work
okay, but is it maybe possible to migrate directly from one category to antoher?
No right?
you'd use the .setParent() method to move a channel from one category to another
oowh so it just overwrites
id assume so
Hi, where can i put post a bug on the website?
a top.gg issue?
yep
Report bugs and give feedback regarding the Discord Bot List and Discord Server List - top-gg/issues
thanks
thanks starman! I guess it worked!
oof, hopefully it'll get fixed at some point
yep, well its only to let them know if its a new bug
but due its been reported its ok
if its not fixed they think its not priority now 😄
setTimeout(() => {
channel1.setParent(`${claimedcategory}`, { lockPermissions: false })``` I currently had set 5 roles who where able to see channnel1 by giving it viewing allow perms. However, after this little category change, I want to overwrite it to make sure only 2 of those selected roles are able to see them (Marked by role1.id and role2.id). How would i make such overwrite?
wasn't it like channel1.overwritePermissions?
Yeah ping me with the answer, thanks in advance guys!
Hello! Anyone online.
hello
Since you change categories, wouldn't it be easier to (outside of your discord bot) reset the channels permission overrides
in the first category let all 5 roles see the channel
in the second category let only two roles see the channel and then when you run the command
simply run a simple method which will make the channel inherit the permissions of the category
easiest with less code
unless you insist on adjusting the permissions manually which then you can use https://discord.js.org/#/docs/main/stable/class/TextChannel?scrollTo=overwritePermissions and pass an object of resolvables
@eternal osprey forgot if I pinged you now (I probably did)
what?
it actually already pinged me as you replied to my message. thank you!
I ahve just used channel1.overwritePermissions
would work too. Thanks for the help!
so i have this code in my reload command to set the aliases
if (pull.aliases && Array.isArray(pull.aliases)) {
pull.aliases.forEach((alias) =>
client.aliases.set(alias, pull.name));
}``` but it says `TypeError: Cannot read property 'set' of undefined` why does it?
cmd works at other bot
does it really matter since its a mostly one off operation
what should it be then
idk, you didn't show barely any code
what code do you want
errr...the rest of it?
if you get too used to foreach on the beginning you end up using it wrongly later on
const fetch = require('node-fetch');
module.exports = {
name: 'what-anime',
aliases: ['w-anime'],
category: 'Fun',
description: 'get anime by image',
execute: async (client, message, args) => {
let attachment = message.attachments.first();
fetch('https://trace.moe/api/search', {
method: 'POST',
body: { image: attachment.url },
headers: { 'Content-Type': 'application/json' }
})
.then(res => res.json())
.then(result => {
console.log(result);
});
}
};
Can anyone help me with linux
how i add the -r flag?
It is recommended to run it as a normal user as it doesn't need further permissions.
If you want to run it as root, add the -r flag.
do you know whats wrong?
initialize client.aliases
if (!client.aliases) client.aliases = {}
Body needs to be stringified JSON and set your content-type header to application/json
and then put all command aliases in those {}?
O, you already have the correct headers
{} means you're initializing client.aliases as an object
Skimmed through that
plz help 
command -r
what to put in?
put in what?
nothuing?
Its application/json already?
the {}
nothing I guess, it's up to you what you want as starting data
set() only works for sets and maps/other equivalent constructors
Won't work for an object
oh, forgot about js maps
did you grab the code somewhere?
Looks like it came from the library itself
is d.js updated?
what to do
yes
i installed it yesterday on bot and i just reinstalled it
what version is it?
discord.js@12.5.3
weird then
what to do
it occurs like right here cuz the embed doesnt send but the commands reload
idk, you'll need help from someone more experient in d.js for that
It's using form-data's browser lib for some reason
@timber fractal so what's inside ../structures/embeds.js
you might be doing something weird
No not reqlly its a default embed i will show
const Discord = require('discord.js');
module.exports = {
default: function (msg) {
return new Discord.MessageEmbed()
.setAuthor(msg.author.tag, msg.author.displayAvatarURL())
.setColor(#00fbff)
.setFooter(Ishana's Utilities | ${msg.guild.name})
.setTimestamp()
}
}
They helped me in djs server i defined the wring thing
@stray seal u can only redirect them to a channel if they are in that server
I think thats it
How i do it then?
If then in the server.
tell me what's the use case
???
@timber fractal probably not but somewhere inside your code can you console.log(typeof global.window)
just in case
Give me a second ill be right back on pc
In djs they say it might be from glob
I'll be on my pc as well to investigate glob
undefined
i fixed it it was this little piece i defined wrong
nice
that glob package has so many unnecessary dependencies
contributing to the node_modules clusterfuck
When you realize npm itself depends on almost 300 dependencies 
now my 15 doesnt seem as bad
yep
npm went full npm
how can i get the number of emojis in all guilds
message.guild.emojis.cache.size but for all guilds
just loop every guild the bot is in
Are emojis even cached by default?
then add those numbers then u get ur result 
dunno
Client.guilds.cache.forEach()
client.guilds.cache.forEach(server => {
server.emojis.cache.size
})```?
or you could just use reduce and add up the sum
let pp = 0;
Client.guilds.cache.forEach(g => {
pp += g.emojis.cache.size;
})
console.log(pp)
max pp
Or just
const pp = <Client>.guilds.cache
.reduce((all, g) => all + g.emojis.cache.size, 0);
console.log(pp);

Or even better:
client.guilds.cache.reduce((count, guild) => count + guild.emojis.cache.size, 0);
sight 100
Is it possible to put emoji instead of getting "??"?
I put "😗" but it returned "??"
You have to use a font which renders emojis, or just use an image
I'm using jimp
Simp
Jimp isn't that great with text since it uses bitmap fonts which have limited characters support
You're better off using canvas for text manipulation
Trivia sure does look neat with the select interaction
Wew, indeed
if only element widths were consistent too 😔
Wouldn't buttons be better in this case
for randomized true/false and multiselect imo select fit better
maybe I made it button if I specifically made multiple answer
/**
*@type {Array<string>}
*/
const answers = question.incorrect;
answers.push(question.correct);
answers.sort(() => Math.random() - 0.5);
for (let n = 0; n < answers.length; n++) {
selectAnswer.addOptions([
{
label: `Options : ${n + 1}`,
description: `${decode(answers[n])}`.slice(0, 48),
value: `${decode(answers[n])}`,
},
]);
}``` For simple randomizing the answer, this is good enough?
why -0.5? iirc it rounds it to the next matching index
sort requires a return value of a number bigger or smaller than 0
That's basically the shortest way to shuffle an array
But its not really recommended
the longest length is 4, forgot to mention
Ya, I saw it quite easy to guess, but I think it work for short length?
Its pretty decent for small arrays
i guess the way i do it is a bit overkill then, i have a array of Answers where i push in the correctanswer and then shuffle the array. so i get a question with 4 possible answers but always in a random order
Do bot integration roles count towards the max server roles?
I'm pretty sure they don't, right?
iirc
another array randomization method is to clone the array of possibilities then splice a random item onto a new array
export function shuffleArray(array: any) {
let currentIndex = array.length,
randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
}
return array;
}
``` i have this, works quite nice, but idk if its the fastest way
that should be very fast, but not sure about the quality of the randomness
nah its just an array of 4 items, should be good enough
so people just wont press the same button to get the correct answer
yolo spams same button
cogs
hmmm
tbf, that's as far as I can point you to since I'm not a python dev
how to do those
dot dot dot
just research how cogs work, I can't guide you but I know that's the way for multi-file bots in python
bot.load_extension('cogs.test') # this is good but you can make it better
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
else:
print(f'Unable to load {filename[:-3]}')?
@earnest phoenix
this?
ye probably
what type of error do you get in the console
This is development related, right? What am I meant to do here?
no no i just want to make my 200 lines file to like other files
not development related, you need to write about your bot there
what does it do? why use it? be creative
oh ._.
Yes, but am I supposed to use HTML?
yeah
optional
you're supposed to write about your bot
no
use npm
idk
npm isnt used on top.gg
html is just for fancyfying
lol
Ah. Makes sense
then why my bot got accepted
im so confused
you cannot use npm in your bots description
waffle/woo/me are talking about the longdesc not the bot itself
My knowledge of HTML is basically throwing things together until it eventually comes out with a scuffed looking website, so I'm glad it's not forced.
which is what waffle is asking about
oh that
LOL same
tbf, html is by far the most optional thing in longdesc since you can just use markdown
some fullstack dev would look at some of the html I've written and laugh for a few minutes, then slap me in the face.
my bot desc is kinda weird
you can also use markdown
^
Yeah, using md rn
So Im Trying To Get This To Work The Only Error I Have Had I DOnt Get: DiscordAPIError: 404: Not Found whats not found?
const Discord = require("discord.js");
const fs = require('fs');
const path = require('path');
const config = fs.readFileSync(path.resolve(__dirname, '../config.json'));
exports.run = async (client, message, args) => {
const webhookClient = new Discord.WebhookClient(config.webhookID, config.webhookToken);
if (!message.member.permissions.has("ADMINISTRATOR"))
return message.channel.send("You Have Been Denied Use Of This Command ~ Have A Nice Day!");
if (!message.member.roles.cache.has("831638881376010250") || message.author.bot) return;
let announcement = args.slice(1).join(" ");
webhookClient.send(announcement)
};
maybe a webhook with that ID / token doesn't exist
idk, i just made the webhook, copied it, ID is the Numbers, then Tokens The Characters Right?
is there an api that gives a phrase in different languages?
Like... google translate?
Pretty sure a lot of people use this: https://github.com/matheuss/google-translate-api
can someone explain why this wont write to the file... this sent the "Added To the File" section but it never added to the file 
const fs = require('fs');
const path = require('path');
exports.run = async (client, message, args) => {
let guild = message.guild
let test = args.slice(1).join(" ");
fs.writeFileSync(path.resolve(__dirname, './test.html'), JSON.stringify(test))
message.channel.send(test + "Added To The File").catch((e) => guild.channels.cache.find(i => i.name === 'crystal-crash-logs').send('Error: ' + e));
};
it as in the test message i usede
Hi there. whenever i put my bot id into https://top.gg/bot/:your-bot-id/webhooks to start using webhooks i always get a 404 error. do i need to add my bot to top.gg to access this page? If not, why am i getting a 404 Page Not Found error
is your bot on top.gg? as itll return as nulled if not
If you see the 404 Page go refresh it once
That should do the trick
No it isnt. Is it necessary for the bot to be on top.gg to access its webhooks?
yeah
Tried refreshing it for the past 5 min or so. doesnt work
Oh oka. no workaround for that?
Nope
why would you need its webhooks without it on the site?
Well I need to get info about the people who have voted for a server that Im in and give them a role.
you'd want to be on the server api then
i assume thats a thing i dont use the server list
I dont think so. a few hours ago I talked to someone in #topgg-api and they suggested me to use webhooks
yes but bot webhooks are for when people vote for a bot
In the docs there is something called on_dsl_vote tho.
I wasnt sure how to use it so came here for help
but guess i need to get accepted on top.gg first
on_dsl_vote would be exactly what webhooks do probably
webhooks are basically reverse apis - the service sends a request to you and you handle it
Yeh but i dont understand how to implement them. plus can't find any examples to try to understand the code cuz i couldnt understand the docs at all
what language?
Python
Yeh i did. but what i don't get is that if i dont enter the server id anywhere. how will top.gg know it has to send the data to me
you enter the id in the other side
other side?
and for that i need to be registered on topgg ig?
like my bot
webhooks are reverse apis, so if you normally supply the api url in your own code, for a webhook you supply your server's url to the site
yes, you need to be approved first
sure
ngl, next.js sucks ass
Is there a way to make ur bot private on top.gg so like people other cant see it except the owner?
no
non-existent TS support and proper docs
why would you publish a bot if you want it to be private in first place?
published means open for public usage
Well its actually built especially for one server
then don't publish it
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: reaper-2.0@v6.3.0-stable
npm ERR! Found: discord.js@13.0.0-dev.f200f14.1626436969
npm ERR! node_modules/discord.js
npm ERR! discord.js@"^13.0.0-dev.1dcad05.1626178061" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer discord.js@"^12.0.0" from discord-paginationembed@2.1.0
npm ERR! node_modules/discord-paginationembed
npm ERR! discord-paginationembed@"^2.1.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /home/ubuntu/.npm/eresolve-report.txt for a full report.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/ubuntu/.npm/_logs/2021-07-16T18_40_13_212Z-debug.log
while doing npm i in aws
using discord v13
so i cant use the webhooks?
chances are you'll be denied if it's hardcoded to one server
again, why would you?
like, votes have 0 benefit outside of putting your bot higher on the list
if you want some kind of "daily" reward just make a command to simulate it
i see
how to install discordjs v13?
although I'd not advise doing so
since nightly versions might drastically change before stable release, requiring you to constantly rewrite your code
How do i get/make a Bot Dashboard?
You'll need to know HTML, CSS, JS, preferably a framework like React or Vue, how to create REST APIs, and how to use discord's oauth2. It's not an easy task, and there isn't a single answer to this. Research the technologies I listed, and start learning.
Kinda Works... Doesn't Send announcement In The Description
const Discord = require("discord.js");
exports.run = async (client, message, args) => {
const webhookid = "REDACTED"
const webhooktoken = "REDACTED"
const webhookClient = new Discord.WebhookClient(webhookid, webhooktoken);
if (!message.member.permissions.has("ADMINISTRATOR"))
return message.channel.send("You Have Been Denied Use Of This Command ~ Have A Nice Day!");
if (!message.member.roles.cache.has("831638881376010250") || message.author.bot) return;
let announcement = args.slice(1).join(" ");
let embed = new Discord.MessageEmbed()
.setColor("GREEN")
.setTitle("Testing")
.setDescription(announcement)
.setTimestamp()
webhookClient.send(embed)
};
i had "test" as the test message for the announce
there was at one stage, during the initial beta it showed up on bot profiles
omg isn't it client.user.id?
yup! Thanks
how do i check if a specific user has one of these roles: js const roling = [role1, role2, role3, role4, role5]?
Depends on what rolex is
If it was a snowflake as a string, you could use .includes(...)
If it was a role instance, you could pass a function with .some and see if the .id matches.
yup used the some function and it worked!
channel1.overwritePermissions([
{
id: role1.id,
deny: ['VIEW_CHANNEL']
},
{
id: role2.id,
deny: ['VIEW_CHANNEL']
}, {
id: role3.id,
deny: ['VIEW_CHANNEL']
},
{
id: role4.id,
allow: ['VIEW_CHANNEL']
},
{
id: role5.id,
allow: ['VIEW_CHANNEL']
},
{
id: message.guild.id,
deny: ['VIEW_CHANNEL']
},{
id: vip.id,
allow: ['VIEW_CHANNEL']
}
], 'This will send the channel to the claimed category')
}, 10000);```
why is it missing permissions now? Pretty sure my whole bot has all the selected scopes available.
and the roles don't have admin rights
I want to explore the possibilities with buttons but I don’t have a cows clue on how to make em work I just wanna make a verification system that says “press here to verify”
Okey, Why we are not able to use emojis (not unicode) on embed title? I can do it in v12 but not v13 anymore
Then you will need to learn how they work first :)
Discord.js is a mystery. Maybe a bug? Raise an issue on their GitHub or go ask in their Discord server.
Same code, only difference is v12-v13
does the element users start with index 0 or 1? js {"h38c70":{"name":["367251020914491392"],"users":[],"category":["Unclaimed"]},
Indexes in JS start from 0
unimportant question: Are there other languages for coding bots
as far as I know, I only know python and javascript
just a random question, but itd be cool to learn something new
Any language that supports websockets and HTTP requests
like php and c++?
yeah I think I understand
you might want to ease into lower level languages like getting into java/c# and then work into c and/or rust from there
If you don't understand types already, give TypeScript a try
going from high level to lower level is rough
I know thanks
It's less about the level of the language and more about the paradigms.
Lower level languages usually follow similar ones
Came out the crib learning C++ before Python
I need to finish coding, ive been procrastinating for the past week 😔
Pascal ftw
Sometimes, but lower-level languages are just closer to the hardware of the computer. Paradigms affect a large aspect into how one writes and thinks about programs. Imperative vs. declarative programming, for example. Learning Java vs. Clojure, for example. I'd rather say that low/high-level programming is just another paradigm.
Rust for Discord bots cough cough
Golang
if I had to choose between going to hell and rust I'd choose hell because that's better
You're just scared of crabs
Go is better confirmed
does anyone know about ipc and cluster evaling?
my whole bot relies on them so I think so haha
@pale vessel should I drop using built in http lib and just go for net.Socket and write raw requests
Why 
Is the difference that significant? If not, then don't bother, IMO.
ohh
socket.connect({ port: 10204, host: "localhost" });
socket.write("HTTP/1.1 GET /loadtracks\r\n\r\n");
Doesn't sound half bad honestly
uses streams as well
Only downside is parsing headers
I was trying to support icecast web servers since their responses start with ICE/ instead of HTTP/
and nodejs http doesn't like responses that don't start with HTTP/ and emits an error
ice ice baby
How did other libraries handle those then?
Apparently, they replace http's parser
I found a lib that uses http(s) and allows for ICE/
ditch all http wrappers, return to http

You really like it low level huh
Sure haha
ferpormance
masochist
idk. It's a protocol specifically for radio broadcasts
speaking of performance, anyone ever tried ultralight?
link?
Is this the "better electron"?
hm. Front end
ye
Cry mentioned it before IIRC
this sounds like that other electron alternative
there are many "better electron"s out there
this one isnt exactly a replacement
doesnt run node.js
so 
and doesnt support native libs
if you're looking into electron alternatives
blazor desktop is something to look into
really promising
you know what
just don't use electron at all or make a fucking website instead
boom
isnt that for C# tho



