#development
1 messages · Page 1504 of 1
if you mention the channel you can get the channel id from the mentioned channel
Like they mentioned, GuildChannelManager.delete isn't a function. get the instance from cache and call instance.delete
now I get thic
(node:15968) Warning: Accessing non-existent property 'func' of module exports inside circular dependency
(Use node --trace-warnings ... to show where the warning was created)
precisely
you'd probably do message.guild.channels.cache.get(msgArgs[0])
itll return a promise of a channel
hey hello can you put the shard in discord.py and you can explain me how to put them
get the channel from cache and call channel.delete
then once the promise is resolved, itll return a channel
cache get does not return a Promise
but there is no need to fetch
Collection<string, GuildChannel>.fetch is not a function
youll have to iterate through the cache
Looks good
i mean you probably could wrap the get into a Promise function and then call the function, but its stupid
HELP ME PLS
Making a Map based cache op async is stupid
well thats just .get with extra steps
lol
ik thats what you were saying
THIS IS SHARDS?
hey hello can you put the shard in discord.py and you can explain me how to put them
there are 2 ways to shard your client @earnest phoenix
ok
this will spawn a new Process with the shard running on it
so its not my node
why
the other method will use a worker to spawn more shards
URL = match ? `https://cdn.discordapp.com/emojis/${match[2]}.png` : emojiMap.emojiDefinitions.find(x => x.surrogates === mB[1]).assetUrl || message.attachments.first().url || mB[1];
the last or of the thing should be running
you could probably do a message.guild.channels.cache.resolve(msgArgs[0])
not the emojimap
@pale vessel
where did you placed this code?
?
The ShardManager by default uses worker_threads. The image they showed uses worker_threads and all shards share the same memory space on different threads if there is more than one logical processor
is this shard okay?
you removed the ? i added
depends if you use the Manager or Internal sharding
i dont think I did
code looks fine
show me where it was
index.js as the tutorial said and bot.js whole script of my bot
did you placed the shard manager in a different file from your bots main file?
yes
ok and inside the new ShardingManager set the path to your bots main file
I suggest looking at the source. iirc, there is no distinction from internal sharding and ShardingManager. ShardingManager uses internal sharding. The easiest way to test this is if both shards can log to the same console
ok
dont understand
iirc there is a difference between Internal Sharding and the Sharding Manager
internal and via IPC is only distinct in Eris
why
replace ./bot.js with the path to your bot main file
They were talking to me about that statement
if your bot main file is called index.js change bot.js to index.js
ah ok
this?
Internal sharding is on the Same process and Sharding manager uses Worker threads.
?
client.shard
how is your main file called?
bot.js
how is your sharding manager file called?
worker_threads is within the same process. There is no "cluster" based sharding where events from all shards are forwarded to a single client to manage the cache and worker tasks.
index.js
Also, is that Eris docs?
How can I make an image transparent on canvas
yes
the same basic idea of internal and external sharding is true for all libs
ok if you want to start the bot with shards start index.js without sharding use bot.js
I don't believe that's up to date with how discord.js manages sharding unless I missed something when I read through the ShardManager code
if you want to set a certain amount of shards pass the totalShards: "auto or number of shards" in your Sharding Manager constructor
discord suggest to start sharding at 1k guilds
created script pls?
// for ShardingManager options see:
// https://discord.js.org/#/docs/main/v12/class/ShardingManager
totalShards: 'auto',
token: 'YOUR_TOKEN_GOES_HERE'
});```
I just wanted to test I deactivate it now and activate it soon
it requires some other modification on certain stuff tho
bcs not all things are shared between the shards
https://anidiots.guide/understanding/sharding read this page for more informations
Oh. I guess the default is still using worker_threads but shards having separate caches. I didn't realized there was a mode specification
So I guess we were both correct in our own regards
probably
if i would hit the region of the need to shard i would probably Modify the lib i use to have a shared cache for all shards
pass me the script with .env since I work with repl.it
sorry
That's what I do currently. Sort of. I just have one logical processor for all gateway events for all shards within a cluster
Discord object caching is still handled in Redis though
How can I make the background be transparent
Redis caching is stronk
ctx.fillStyle = "white";
sure will be a bit slower than directly in memory but still less headache then using Brodcast eval
okay i'm only left with one shards
creating a new Canvas(width, height) will have a transparent background by default. If you want to remove pixels from an image you're compositing onto the base layer, you'll have to use masking
You should check to make sure you're sending the file to Discord or wherever as a png since discord.js defaults to jpg
What are you drawing onto the canvas?
let invertCanvas = canvas.createCanvas(image.width, image.height);
let ctx = invertCanvas.getContext("2d");
ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.globalCompositeOperation = "difference";
ctx.fillStyle = "white";
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
its invert
Does the input image you're drawing onto the ctx have transparency
yes
loop through the image data, invert the color and put the new image data
Ah. The svg should have transparency then
Try flaze's suggestion. Perhaps it's a lower level issue when it comes to decoding SVGs
@pale vessel ?
I was gonna do buffer
For context, I don't use node-canvas
so I can only help so much
i'm not sure if it works for inverting, i only used it for recoloring the entire image
what did you do>?
If they shut you down for being too much of a noisey neighbor, you should probably not use image manipulation.
Oh. I thought volt was some provider or something
voltron

voltrex
Ah. Now that name rings a bell
master mobile developer
well
imma work on decompiling gifs
imma do switch
@pale vessel
can I do this
URL = match ? `https://cdn.discordapp.com/emojis/${match[2]}.png` || `https://cdn.discordapp.com/emojis/${match[2]}.gif` : ...
Nope
how can you exclude 0 from the loop when there are two 0 and 1 in the array
module.exports.fetchAPI = async function (url) {
const response = await axios.get(url)
let image = response.data
const count = Object.keys(image).length
for (let i = 0; i < count; i++) {
return Object.values(image)[i]
}
}```
you need :
decoding gifs is a cheap task, but if you wanna encode, good luck lol
i misread
@lament rock I found a good npm
aaa never mind
I can just loop it
it works, but not the way you intend it to
how do I make it work the way I intend it to
Check if the regex matched a before the first :
if so, change png to gif
you can't use ||
that makes no sense and it will never fallback to that since the first string will always be truthy
I mean if the custom emoji was a gif
yes
If whatever is 1 or 0 is in the for loop and you want to exclude 0, you can do something similar to
if (thing === 0) continue
obviously replace thing with whatever can be 0 or 1
goes a mean soemthing?
animated
ok
ok thx
you can wrap the a with ()
the same concept applies for user avatars btw, avatars which have gif formats start with a_
doesnt the format for the avatar webm
discord.js defaults to webp
so I cant really do much to check if it is a gif or png
webm is not a supported file extension for avatars
ok
message.author.displayAvatarURL({
dynamic: true,
size: 1024,
format: 'png'
});
if the user has an animed pfp
if (message.author.avatar.startsWith("a_")) // user has animated avatar
so something like ```js
URL = match ? https://cdn.discordapp.com/emojis/${match[2]}.${match[1] ? "gif" : "png"} : a || b || c;
? and : is a ternary expression.
boolean value ? code to do if boolean is true : code to do if boolean is false
o
okay well that helps
how do I check if its a gif
Imma use a switch to switch between gif and png
match[1] is the result of the first capture group if the a is in the emoji. If a was not present in the string between the < and : then it will be undefined
Ok so I've been testing some code recently for a test bot I'm messing around with, and I can't seem to properly make a json file. I can get my code to read from it and write to it, but every time I want to add something to the json file it just rewrites the old json file with the new content. Here's my code: ```js
if(command == 'new') { // w!new
commandArg = message.content.indexOf(' ', 7)
commandStr = message.content.substring(6, commandArg)
commandSay = message.content.slice(commandArg+1)
var dataobj = {}
dataobj.CustomName = commandStr
dataobj.CustomPhrase = commandSay
const JSONString = JSON.stringify(dataobj, null, 2)
fs.writeFile('CustomCommands.json', JSONString, (err) => {
if (err) {
throw err
}
console.log('JSON successfully saved')
}
)
}
fs.readFile('CustomCommands.json', (err, jsonStringlocal) => {
if(err) {
throw err
}
const CustomNameCommand = JSON.parse(jsonStringlocal)
if(command == CustomNameCommand.CustomName) {
message.channel.send(\``${CustomNameCommand.CustomPhrase}````)
}
}
)
the ternary expression is for if the result of that capture group is not undefined, then its a gif
You need to assign new data to the Object you parse, then stringify the Object and write the string back to the JSON
So parse the JSON and add what I need in the variables and then stringify it back into a json?
Also, I think your code might be susceptible to race conditions if you're writing and it does properly write but the read doesn't show that new data. You might wanna use the sync methods which don't take callbacks or you put subsequent code within the callbacks
So use readFileSync and writeFileSync instead
so
Yeah. That'll pause the thread until those IO ops finish
if (message.author.avatar.startsWith("a_") || URL.endsWith(".gif)) {.}
I'm not sure if this is practical, but you might want to consider using a database if you want to regularly read and write to and from something
Again, that's up to you
Talking to Waffle, FYI
That would return true if the author's avatar is a gif OR if the emoji url ends with gif
if (message.author.avatar.startsWith("a_") || URL.endsWith(".gif)) { type = "gif" }
fun fact, you don't need curly braces after if statements unless you're doing multiple lines if a condition a met
yeah
if you just want to do one line it can literally be
if (condition) doMyStuff()
doesnt have to be a method
@lament rock would you mind if i dm'ed you
Why would that be necessary
its about your bot i wanted to ask a question about it
Oh, this is just a bot for my friends and I to mess around with, nothing that's going to be used by more than 5 or 6 people
alrighty
Okay
still an option, up to you
guys, this is good? py memberCount = 0 for g in self.client.guilds: for user in g.users: memberCount += 1
it wont break anything?
https://www.npmjs.com/package/gif-frames Can I use this to encode gifs
self.client.guilds returns a guildmanager
you could do self.client.guilds.forEach((g) => { //do stuff })
Pretty sure it returns a list of guilds the clientis in
That's Python isn't it
it is
YEEE
why not g.member_count?
ig i dont have member intent
you don't need it
How do I loop throu an array
js?
yes
member_count is always sent over GUILD_CREATE. It's an approximate
for g in self.client.guilds:
memberCount + g.member_count```
+=
for (let i = 0; i < array.length; i++) {}
so i have this little image problem ^^" my long discription is approximately
<div>
<div class = "image"> </div>
</div>
sum exists
either works @solemn leaf
wait why not just +?
you're not doing anything to memberCount
- doesn't mutate the state of a variable
let x of array gives you an x which is the item at any particular index
this is good then?
for (var i = 0; i < frameData.length; i++) { }
ok
that should be fine
i'd recommend let instead of var in a for loop initializer
like cry said, you can use sum() and [g.memberCount for g in client.guilds]
i think that's the syntax
THIS IS GOOD??!?!
otherwise if you uses a var called i earlier on it can mess with it
and its generally good practice
No, what you're doing is evaluating memberCount, which is zero plus the guild member count
you're not modifying the variable
a one liner would be better though
yeah you have to do += to actually update the value of the variable
idk
i did it as +=
use const over let if you don't reassign the value of the variable. That's practically the only way to get "statically typed js". With that comes it's own performance benefits. let implies type reassertion
let images = []
gifFrames({ url: URL, frames: 0 }).then(function (frameData) {
//frameData[0].getImage().pipe(fs.createWriteStream('firstframe.jpg'));
for (var i = 0; i < frameData.length; i++) {
let image = await canvas.loadImage(frameData[i]);
let invertCanvas = canvas.createCanvas(image.width, image.height);
let ctx = invertCanvas.getContext("2d");
ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.globalCompositeOperation = "difference";
ctx.fillStyle = "white";
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
images.push(ctx.canvas.toBuffer())
}
});
const can tbe cahnged
what you mean
I know. If you don't reassign the value of a const, use it over let
yeah, when iterating with of, you should do const xyz not let xyz, my bad
obv with i = 0; i++; you're modifying i so that will be let
getting as close as possible to statically typed is good
wait
do I just remove the await
let image = await canvas.loadImage(frameData[i]);
^^^^^
SyntaxError: await is only valid in async function
make the function you're calling that in async
function thingy(params) {
const thing = await code(params); // not valid
}
async function thingy(params) {
const thing = await code(params); // valid
}
gifFrames({ url: URL, frames: 0 }).then(async function (frameData) {
sure
is it wrong?
No
That is valid syntax
I would have use arrow functions, personally, but we all have our own styles
thats fine
arrow functions are es6. If a lib supports node versions earlier than when arrow functions were added, they would have to use that
are you going to loop through the frames and use gifencoder
Passing it an Array of all the frames can cause the heap to run out of free space depending on the size of the gif
basically all that's different is that instead of it being function (abc) {} it would be (abc) => {}
regarding arrow functions
you can't access this in anonymous functions
?
and no arguments
sure
doesn't matter in this case
not like that]
@pale vessel
If I regularly evaluated this, that would be the return value as well
Well. Amanda handles Promises, so I shouldn't have added the async, but whatever
So I've been trying to fix this code, but I just can't get it to work
I started using fs.appendFile and it's getting close, but it's still improper
,\n
right
How would I do that?
commas are important in JSON
how should I encode the gif
that's the error causing the parsing to fail
it seems to depend on how you call it
PLEASE JSON.stringify the Object before you write. JSON.stringify handles the commas for you. Improperly managing commas can be catastrophic
could someone pls help me with html/css for long bot description? qwq
speaking of which, I used bootstrap for my bot description but I want to force dark theme, what do I do?
it's not recognizing it as "advanced css" or whatever it said
this in that context is the global object and not an instance of CanvasRenderingContext2D
assigning to the prototype implies it's a static method. this would not be defined in context to the class
;-; how could i make this image in the description field? qwq
https://cdn.discordapp.com/emojis/sungl.png
(node:19000) UnhandledPromiseRejectionWarning: Error: Server responded with 404
while this works
which image?
the one you sent?
i'd assume its a simple <img src="url_to_image"> like any other image
the one which is at bottom of the site for no reason qwq
I'm confused... which one? Sorry if this is annoying I just don't know what image you mean
regardless, it should be as simple as an img tag
ah
try a test of the length
use JSON.stringify like I mentioned
ah right
not adding content after a comma is improper management
JSON.stringify handles commas for you
Then don't add the ,\n
why didnt it work
it didnt do the gif
when this is a gif
@pale vessel this no workie
URL = match ? `https://cdn.discordapp.com/emojis/${match[2]}.${match[1] ? "gif" : "png"}` : emojiMap.emojiDefinitions.find(x => x.surrogates === mB[1])?.assetUrl || message.attachments.first()?.url || mB[1];
log the url
you cant append to json
it doesnt change anything if i take the image tag or put it as div background image qwq everytime its down there qwq
log URL
Whenever I try to use writeFile, it just overwrites the previous data, and I'm having a hard time figuring out how to just add data
that was url
message.attachment.first().attachment seems to give a url
json has to be overwritten, thats why its so innefficient
I was mentioning earlier that you need to assign data to the old object then stringify the old object with the new data and write that
they both give one
not seeing that property https://discord.js.org/#/docs/main/stable/class/MessageAttachment
you need to read the json file, convert it to object, add the data to the object, stringify it again, and save the full file again
I used .url bcs doc
ugh
whoops i meant url
flaze
thats why json is heavily not recommended for usage as a database
ENOMEM waiting to happen
🗿 Memory leak
voltrex leak
JSON is memory leak confirmed
Is there a better file type or since this is a small thing should I still use json
Since it's so small, JSON is fine
Alright
@pale vessel can you fix the attachments one
I think regardless of size you should still maybe use a db, but again up to you
if its something small, you can use json, but keep it also loaded in memory
only write when you need to change it
and only read once at startup
any specifics on what i need to do?
You need to put CSS in your long description
I would like to force a theme but I'm using bootstrap
use css if you want a forced theme
adds the word CSS in description
pretty sure it checks for style tag
wonder if itll work
probably
flaze
i asked xetera and he said he checked for that
attachments broke
yeah it just checks for style tags
how do i get it. where a command will have reactions, and if the user his one of them, it will change the message
LMAO it worked
message.awaitReactions
be sure to react to the message before awaiting reactions via message.React(emoji)
thanks
anyone know how to get the current position a track is in using the spotify presence?
as in viewing a user's status and seeing what pos they're at?
yes
probably just regex it
yeah
i didnt realize they gave a timestamp, thought it was a string 
does the start time start where they are in the song or is it the beginning of the song tho?
eyo! I would like know how to do modif for doing a bot to a public bot
Can someone help me ?
You know, I did an bot but it's like if their is the mute command.... The client will can't have the command. So ,I'm trying to know how to put my bot with the modif ...
Nah
@fervent goblet looks like the start time
so what would i need to use to calculate the current pos?
...for the welcome message...
you would get the current timestamp and convert it to a number
do the same for the starttimestamp
then subtract
to convert to a number, use the date library
i think you can say const start = new Date(usrActivity.timestamps.start);
otherwise just look up the format
im fairly certain tho
i been messing around with the add reaction code. but i cant get it to react to the bot message, it only reacts to the users
you're reacting to your input message, not the message you sent
save the sent message in a variable(with the promise awaited) then react to that message
you would say const botMessage = await message.channel.send("xyz");
then to react you'd do botMessage.react('👍');
mood
What happened?
package stopped importing right
Or:
message.channel.send("xyz").then(m => {
m.react("😁")
});
Ok
- I'll do it tomorrow

-1. I'm too tired rn
-2. I'm not being paid enough
-3. OH MY GOD I AM AN IDIOT I FORGOT TO PUT COMMAS
-4. welp, stack overflow here i come
this is not the channel for memes....
Tis not a meme my good sir
feelsbadman
yeah starman's right
npmjs.com/package/to-date be like:
return new Date(value)
wrong one
Do y'all know when discord is actually going to properly implement slash commands for bots?
never
Gives no sense for bots to have that
What
probably in a few months
but for anyone to actually use it
eh maybe a year
unless they fix it fast
Wtf will slash commands help with
Properly? You can already implement it
i know, my mate has implemented it on his bot, but he says it's still buggy
You mean like a UI for it?
he's using it for a translate command
I see
Not just becaue it can be used means it's good
Set Channel Command: https://srcb.in/TdywOoeXjn
Suggest Somehing: https://sourceb.in/tu09nvR2Yd
Schema: https://sourceb.in/l1Qu2YUMpX
help. no work. i will set the channel then it will be undefined
although discord hasn't made a way to fetch members
so it's just best that you use id
What
you can't get members like you could with a regular command handler
Compare the bits
how
hi hi
using a bit comparison machine
member.hasPermission()
oh lol
i'm making my own lib
my bad
I need help with this https://www.npmjs.com/package/gifencoder
You could see Discord.js' implementation.
Not you.
oh
here is my code
gifFrames({ url: URL, frames: 0 }).then(async function (frameData) {
console.log(frameData[0].frameInfo)
const encoder = new GIFEncoder(frameData[0].frameInfo.width, frameData[0].frameInfo.height);
encoder.start();
encoder.setRepeat(0); // 0 for repeat, -1 for no-repeat
encoder.setDelay(frameData[0].frameInfo.delay); // frame delay in ms
//frameData[0].getImage().pipe(fs.createWriteStream('firstframe.jpg'));
frameData.forEach(async function (frame) {
let image = await canvas.loadImage(frame.getImage());
let invertCanvas = canvas.createCanvas(image.width, image.height);
let ctx = invertCanvas.getContext("2d");
ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.globalCompositeOperation = "difference";
ctx.globalAlpha = 1.0;
ctx.fillStyle = "white";
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
encoder.addFrame(ctx);
});
encoder.finish()
const buf = encoder.out.getData();
the buffer is right
but when I send it
supposed to be a gif there
the package compiles images into a gif
how do you dashboard a discord bot?

you just make a dashboard and code it into your bot
is there a way to see when a bot was uploaded to topgg
I think someone stole my bot's identity
F
I want to see when they posted their bot
nice pfp lol
just search the pings in #logs
im looking rn
How did you find out about this identity thief
I was getting the link to my bot for a url shortener
and I just searched for it on topgg
and there were two...
just one was a white avatar instead of an orange one
mmhmm
give me a hand to make my dashboard for my bot there any videos on yt?
give me a hand to make my dashboard for my bot there any videos on yt?@misty sigil
bRo?
not how it works
Ma ce qualcuno italiano o devo usare google XD
how do you dashboard a discord bot?
Bruh google it if no body answers
@neon condor https://www.youtube.com/watch?v=qujpBixCjIk
#webdev #javascript #discordbot
In this series, we are going to build a Discord Bot Dashboard. We will be using React, Express, MongoDB, and Node.js, aka MERN stack.
Part 2: https://www.youtube.com/watch?v=DomtnrQ4f3Q&feature=youtu.be
Want to support me and the channel? Donations are not required but greatly appreciated!
Become a Patreon: h...
Gz
^^^^^^^^^^^
it requires extensive knowledge of
- http requests
- web frameworks
- frontend development
- db interactions
and a shit ton more
you don't have to use a framework
tldr most of things listen on this roadmap https://github.com/kamranahmedse/developer-roadmap
eh you'd be best to
true
o
using gif encoder 1 🤔
?
gifencoder 2 is so much better
what
gifencoder is slow
gifencoder 2 can be several times faster
also, looks like your foreach is async, which means its not running until after you do encoder.finish
make foreach sync
what im confused
for best performance you can also avoid forEach and do a normal for loop
still a bad idea
does the gif encoder know which frame is supposed to go where? do frames have indexes or something?
or does it just push frames like you would push items into an array?
1 sec
you push frames
frameData[x].frameIndex
because if you push frames, you have to do it sequentially
doing it concurrently will not guarantee frame order
async forEach is concurrent, not sequential
Promise.all() is also concurrent
I needed async for the await
how should I do the loop
I was doing this
but I didnt think it worked
for (var i = 0; i < frameData[i].getImage().data_length; i++) {
isnt that for getting frames? not for adding them?
Pure JavaScript tool for extracting GIF frames and saving to file
thats only for reading gifs, not creating them
yeah hes using gif-encoder
that is why I have the encoder
why does promise.all not work for loading the images?
so you're reading from one gif and enconding it in another? like a gif transformer
there is a way to do it concurrently
yes
but you need to change your code a bit
you can use an async map
with Promise.all()
but you cant use encoder.add() inside it
you have to use encoder.add() in the end, after all frames are done
ok
yeah, all editing and adding of frames after loading them with promise all.
what
promises = frames.map(async frame => {
// do async transformation here
});
transformed = await Promise.all(promises);
transformed.forEach(frame => {
encoder.addFrame(frame)
});
frames is whatever you get your frames from
frameData
frameData
so I could put the canvas stuff in there?
let me look at your code again
promises = frameData.map(async frame => {
// do async transformation here
let image = await canvas.loadImage(frame.getImage());
let invertCanvas = canvas.createCanvas(image.width, image.height);
let ctx = invertCanvas.getContext("2d");
ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.globalCompositeOperation = "difference";
ctx.globalAlpha = 1.0;
ctx.fillStyle = "white";
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
});
transformed = await Promise.all(promises);
transformed.forEach(frame => {
encoder.addFrame(frame)
});
tim died
hes a busy man
ik
dont forget the consts and lets
i didnt write them because they are fairly obvious
wdym
return ctx;
so the variable promises is an array of promises that return ctx
[Promise<ctx>,Promise<ctx>,Promise<ctx>] etc
then encoder.finished() before I buffer it
then you can await all of them at once with await Promise.all()
that will give you an array of results, like this [ctx,ctx,ctx]
so then you can forEach them and addFrame(ctx)
you called it frame
for simplicity
should I change it to ctx
ikay
gifFrames({ url: URL, frames: "all", outputType: "png" }).then(async function (frameData) {
console.log(frameData[0].frameInfo)
const encoder = new GIFEncoder(frameData[0].frameInfo.width, frameData[0].frameInfo.height);
encoder.start();
encoder.setRepeat(0); // 0 for repeat -1 no-repeat
encoder.setDelay(frameData[0].frameInfo.delay); // frame delay ms
const promises = frameData.map(async frame => {
// do async transformation here
let image = await canvas.loadImage(frame.getImage());
let invertCanvas = canvas.createCanvas(image.width, image.height);
let ctx = invertCanvas.getContext("2d");
ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.globalCompositeOperation = "difference";
ctx.globalAlpha = 1.0;
ctx.fillStyle = "white";
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
return ctx;
});
const transformed = await Promise.all(promises);
transformed.forEach(ctx => {
encoder.addFrame(ctx)
});
const buf = encoder.out.getData();
const buf = encoder.out.getData();
then I can send the buffer in an attachment
how long you think it would take to load
should be pretty fast
how can it so the bot picks up what a user says in discord and makes it a variable in python?
@quartz kindle It could be getting stopped on the await
ok its stopped on the await
the image type is unsupported
Assuming you're using d.py, either use the event or listen(er) decorator, or even wait_for. Depending on what you want to do.
a fun
i have no idea what i was just told, my iq is not that high
gifFrames({ url: URL, frames: "all", outputType: "png" }).then(async function (frameData) {
This does have nothing to do with iq doe kekw, can you explain what you want to do more then?
what im trying to do is number = input("please input number")
except make it so people can do it through discord
Aha, wait_for suits more then
thanks
ContentStream {
_readableState: ReadableState {
highWaterMark: 16384,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: false,
ended: false,
endEmitted: false,
reading: false,
calledRead: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
objectMode: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null
},
readable: true,
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
_obj: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff db 00 84 00 10 0b 0c 0e 0c 0a 10 0e 0d 0e 12 11 10 13 18 28 1a 18 16 16 18 31 23 25 1d ... 2764 more bytes>,
[Symbol(kCapture)]: false
}
@quartz kindle epic
not loading, epic
yep exactly
its 1 frame
wait
nvm
its the full thing
discord is having troubles rendering it
ok i still have no idea what to do, this is what i get for trying to do this while knowing little about python
open it in browser
send your code ig
this is gonna be cheesy code kekw
import discord
import time
from discord.ext import commands
client = commands.Bot(command_prefix="!")
@client.event
async def on_ready():
print("Bot is ready")
@client.command()
async def sos(ctx):
await ctx.send("The bot needs the following permissions to work in special channels")
await ctx.send("https://cdn.discordapp.com/attachments/786890463834538006/795771449432473670/unknown.png")
await ctx.send("https://cdn.discordapp.com/attachments/786890463834538006/795771603534741594/unknown.png")
await ctx.send("https://cdn.discordapp.com/attachments/786890463834538006/795771705234686002/unknown.png")
@client.command()
async def start(ctx):
repeat = 0
number = 0
while repeat == 0:
number = number + 1
time.sleep(1)
await ctx.send(number)
i forgot that i did not fix the counting on this
```py
code
```
its probably not a good idea to make a py bot without knowing py
yeah this tbh
you set number to be 0 in every loop
woo
i know
you should probably not change the frame delay
i also forgot to add the wait
encoder.setDelay(frameData[0].frameInfo.delay); // frame delay ms
didnt you say the format isnt supported @solemn leaf ?
I changed to jpg
DABOSS, don't use time.sleep, it's blocking. Use asyncio.sleep instead, it's a coroutine btw, needs to be awaited
but now Im having troubles with delay
ok
also, you're doing nothing with the repeat value, so it's gonna be an infinite loop
yeah, i just made it so the bot keeps counting non stop
then the repeat var isn't needed, just do while True
ok
though, why would you want to do that
How to make a dashboard for my bot?
so i have message.client.guilds.cache.filter(g => g.member('id')) to get all the guilds which the user and client share but how to i put all of the guilds' id into an array
Well I'd just set the number as the client attribute, so there's another whole command that send the number attribute. That way you don't send it in every loop
# start command
client.number = 0
while True:
client.number += 1
# sleep
# some another command
await ctx.send(client.number)
Also to add to what norizon is saying
Do a for loop and add the ids to an array.
probably better to just map them rather than looping
i just wanna know how i can make it so the user can choose what the variable number is so they can start off on a number other than 0, because if the bot goes down its just gonna start from 0 again
Have you looked at the link I sent? There's example there
how would i map it?
that.map(i => i.id)?
the gif is a lie
when you view it on your pc, does it also go transparent on the second frame?
honestly, potential discord bug then 🤷♂️
just not on the client
or your encoding settings are not discord compatible, discord does have a list of supported formats somewhere.
console.log([...message.client.guilds.cache.filter(g => g.member(message.author.id))]); its makes an array length 2, even though im in like 5 mutual servers, someone told me that g.member uses cache but i dont know what that means or how to do it now
You might need intents?
i have guild member intent but not presence
oof
i actually have no idea how to do this, i tried but it just killed my whole bot somehow
so is there like a way to fetch them?
dont think fetch can do that in one api call 🤔
i tried and i failed miserably, i still cannot really understand user input
uhh so is it possible?
send what you've got
@client.event
async def on_message(message):
if message.content.startswith('number'):
channel = message.channel
await channel.send('Please input number you would like to start on')
def check(m):
return m.content == 'hello' and m.channel == channel
number = await client.wait_for('message', check=check)
await channel.send('Hello {.author}!'.format(msg))
oh god
this is my pathetic attempt
why do you copy the whole thing
god appears* "yes?"
you just need the check and the wait_for
oh
for instance, if you only want it to wait for your message, you can do something like
def check(m):
return m.content.isdigit() and m.author.id == your_id # could be m.author == ctx.author if you want it to wait for the message from whoever invoked the command
msg = await client.wait_for('message', check=check)
number = int(msg.content) # cast it to int since it returns Message object and the content attribute is str
thanks
well, if you use fetch, youd have to fetch from each guild, which if you have 100 guilds with your bot, thats 100 api requests. https://discord.js.org/#/docs/main/stable/class/GuildMemberManager?scrollTo=fetch which easily becomes api abuse.
your best bet is using oauth iirc.
whats oauth
its a way for your bot to make user specific api requests, such as all their guilds.
Is it this? https://discordjs.guide/oauth2/#a-quick-example
my brain hurts from this
its generally a bad idea making a bot in a language you dont know
discord bots are not really the best first or first few projects.
True, my bot is my first project and it was awful
That's like writing a book in a language you don't understand. It's better to start with the basics or you're gonna mess a lot of things up.
It might work, but you're probably not gonna understand why lol
devs be like: as long as it works™️
i can make it work without any user input but i want the user to choose what number they start on
and i have no idea why its not working, its probably really dumb
your using dpy right?
I've literally spoon-fed you though
they have a whole thing already for it afaik.
in the docs
the new py docs are so clean
canvas is really simple, read the npm page for canvas
to like detort
i cant find anything un the new docs lol
distort
i cba to figure this out, im just gonna make a bot that obnoxiously keeps counting
kekw, just learn python and you'll understand the d.py docs
one day
the doc changes seem to mostly be css changes though
but for now i'm happy with an obnoxious discord bot that repeatedly counts
my useless little curb stomped baby
imo it's easier to look for class attributes on the new docs
what would be the most 'non messy' way to format a Date object as DD/MM/YYYY at HH:MM TT but inline
doing it in vue so it has to go inline in {{ }}
can someone help me rq?
what's the issue
so
I'm trying to mention a role
and I don't think message.guild.roles exist
you could just do message.guild.get_role(id) btw
OH
thanks ❤️
it does
Oh wait
can I mention the role with that?
i think you want to use mentions
<Guild>.roles returns list of role
message.guild.roles.get
stfu js
oh snap its py
yep its ez

py bad bcs based off everything else
so by doing get(message.guild.roles, id=id) you're getting an element from the list which has given attribute
but that's redundant as you can just do, message.guild.get_role(id). This is faster as getting a value from a dict is faster than iterating and finding an element in a list
what are you having trouble with?
your not using gif encoder in this example are you?
whats the code look like
this is what draws on ther image
ctx.drawImage(image, wide, y, ctx.canvas.width / 2 - wide * 2, yh, 0, i * cH, canvas.width, step * cH);
unless if you want the whole thing
with canvas you kinda need the whole thing.
let image = await canvas.loadImage(URL);
let invertCanvas = canvas.createCanvas(image.width, image.height);
let ctx = invertCanvas.getContext("2d");
var easeInOut = function (x, pow) {
x = x < 0 ? 0 : x > 1 ? 1 : x; // clamp x
var xx = Math.pow(x, pow);
return xx / (xx + Math.pow(1 - x, pow));
}
ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
ctx.globalAlpha = 1; // reset alpha
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
var step = 1 / canvas.height;;
var y = 0, yh = 0, cH = canvas.height / 2;
var curve = Math.sin(Date.now() / 1020) + 1.2, curve2 = Math.sin(Date.now() / 2217) + 1.4, curve3 = Math.sin(Date.now() / 533) * Math.PI, curve4 = (Math.sin(Date.now() / 731) + 1.1) * Math.PI;
var wave = 4 / (Math.PI * 1), wave1 = curve4 / (Math.PI * 1);
for (var i = 0; i < 1; i += step) {
var wob = Math.sin(i * wave);
var wide = (Math.sin(i * wave1 * 3 + curve3) + 1.0) * 100;
y = easeInOut(easeInOut(wob, curve), curve2);
yh = easeInOut(easeInOut(wob + step, curve), curve2) - y;
y *= ctx.canvas.height;
yh *= ctx.canvas.height;
ctx.drawImage(image, wide, y, ctx.canvas.width / 2 - wide * 2, yh, 0, i * cH, canvas.width, step * cH);
}
woo?
sorry in the middle of a game :p
what game
its kinda hard to tell whats going on, but it could be placing the images at a height outside the height of the canvas
y *= ctx.canvas.height;
if y > 1 it will just place it off the canvas, right?
this is why copy pasting code is considered a real bad idea 😛
op, x is being clamped
x = x < 0 ? 0 : x > 1 ? 1 : x; // clamp x
lol didnt see that
I didnt know the math for it
I know how to do the bytes
but not in canvas
yeah, ive moved off canvas awhile back
ok
might be easier if you tried writing it yourself.
reading this is kindof a pain not really writing it myself
and since its not commented its even harder to tell.
what the fuck is this
DM me if you know how to make a music bot with discord.py
im pretty sure they are asking for someone to code them something
profiling illegal
can someone help me?
whats your language, lib, and issue
i don't understand the .env file type
sorry idk env yet
What part do you not understand?
how do i put the token in
TOKEN="token"
ok thanks!
This explains a lot about the .env file
Environment variables are a fundamental part of Node development, but for some reason I never bothered with learning how to properly use them. Maybe because they are called “Environment Variables.” Just the words “Environment Variable” trigger a PTSD-laced flashback in which I am trying to add the correct path to
ok
Hio! Someone can help me with discord Oauth2?
@crimson vapor its someone clamping
not sure why math.clamp wasnt used, but it works so 🤷♂️
its scary
Can someone help me rq 👁️ e
async def leaderboard(self, ctx):
rankings = levelling.find().sort("xp", -1)
i = 1
embed = discord.Embed(title="Leaderboards")
for x in rankings:
temp = ctx.guild.get_member(x["id"])
tempxp = x["xp"]
embed.add_field(name="{}:".format(temp), value="{} xp".format(tempxp), inline=False)
if i == 6:
break
i+=1
await bot_channel.send(embed=embed)```
NameError: name 'leaderboard' is not defined```
