#development
1 messages · Page 1251 of 1
@earnest phoenix idk how safe using a while loop for what you want to do is. I honestly would think using a foreach loop would be better, and safer. while loops are conditional, meaning it is checking if something is true or false. foreach loops, doesn't, it goes through each item in a object/array, making the item into an object to be use.
yh i need it to check if its true or false
you can do that inside a foreach loop. you can use if-else if-else statements
you can use break, and continue in a while loop
yeah i was gonna use that, but it will still emit the variable = true which will put a user together even if their id is in the db tho right?
heres my code
why do you need that bool in the first place
bool ?
bool = boolean
hey how do i make my command automated, so it will send this info every 1 minute? ```@client.event
async def on_message(message):
'''Bot replies back with sneaker info when it sees a command.'''
if message.author == client.user:
return
if message.content.startswith('!nike'):
if r.ok:
shoes = get_nike_shoes()
links = get_links()
bot_message = ''
for shoe, link in zip(shoes, links):
bot_message += shoe + '\n' + link + '\n\n'
bot_message += 'For more Nike Sneakers releases and info: ' + NIKE_SNKRS_URL
await message.channel.send(bot_message)
else:
await message.channel.send('We could not make contact with the Nike site. Our conclusion is that the Nike site is down. Please try again later!')```
i don't work with py
i made an embed page but the page goes forward even if it's not worth it? how do i solve
code: https://throwbin.io/FSnlpc0
How do I keep it on the existing page if there are no more pages?
use if statments
even if it's not worth it
what
How do I keep it on the existing page if there are no more pages?
don't allow it if the current page is equal to max pages
what
don't allow it if the current page is equal to max pages
@earnest phoenix how
magic
where did you copy the paginator from
are you storing the pages into a array?
are you storing the pages into a array?
@vernal rivet yeah
do you have a variable that has the current page number?
if (reaction._emoji.name === "◀️") {
i0 = i0 - 10;
i1 = i1 - 10;
page = page - 1;
.setTitle(`Sayfa: ${page}/${Math.ceil(bot.guilds.cache.size / 10)} (${bot.guilds.cache.size} sunucu)`)
yeah
Do not do anything if the current page is ${Math.ceil (bot.guilds.cache.size / 10)} (2). how do i do such an operation
if(i0 < 0){
}
/***
* @typedef {String[]} pages
*/
if (reaction._emoji.name === "◀️") {
if(page === pages.length) return;
i0 += 10
i1 += 10;
page++;
.setTitle(`Sayfa: ${page}/${Math.ceil(bot.guilds.cache.size / 10)} (${bot.guilds.cache.size} sunucu)`)
}
if (reaction._emoji.name === "◀️") {
if(page === 0) return;
i0 -= 10
i1 -= 10;
page--;
.setTitle(`Sayfa: ${page}/${Math.ceil(bot.guilds.cache.size / 10)} (${bot.guilds.cache.size} sunucu)`)
Should look something like this.
don't spoonfeed them code
its fine, its not showing them that much
yeah i see, could've still explained it though
i still have not find the answer in the doc @earnest phoenix
i mean could have, but at the exact same time, we would be here for a while if i were to explain it
@eternal osprey i literally took a screenshot of the section
oh that
this is all you sent
what's confusing
if you would just read through the doc you would get what you need to do
i don't even work with python and i know what to do
how would you do a skipto command for a music bot? (so it would give an ID to each song (1,2,3,4 etc) and you can get the numbers by looking up on 1queue commamd, and what I need is an example that you could skip to any song currently playing in the queue by comand example 1skipto 2 the output would be "Skipped to the second song in the queue". the song that was playing and songs before the given number are deleted from the queue and the song with ID of 2 changes their ID to 1 and starts playing) ANY IDEAS?
forgot to mention
I am using djs
just have it remove x amount of items in a array/map/list/what every you stored the songs in.
well, I am using a map, but when I tried to get map by var and for example doing getMap[2] <- "2" would signify the pos of the song in the queue. which should return my song right? I have made a outputs which should infact work, but it says that it's not defined
Hi again, I could use some help, this has been a problem for a while and i have yet to find the solution or a work around, all help is appreciated. Thanks in advanced!
Here are some Images of my problem and other things related to it:
why are you making it a promise
I run the query in mysql too and it gets the data required by the way so I don't think its the query.
why are you making it a promise
@earnest phoenix It was the only way I got with some help for it to get the data from the table before, I may have assumed it would work the same way here. Could you explain why it shouldn't be a promise?
it's valid to wrap it around one, i was just wondering why you were making it one
then i read up on the mysql package and it only does callbacks
Ah
It's kind of weird, it doesnt seem to be getting the value like it should be for some strange reason and comes out with no data.
It's showing no data being retrieved, but there is no error, yet when i do the query inside mysql, sure enough it locates the data
tried logging your statement yet?
actually print out to console what the statement looks like
this?
the actual string of the statement
ergo this
the actual string of the statement
@earnest phoenix sorry, can you explain? My mind went blank lol
uppercase commands
@opal plank doesn't have to be
ik
i put a screenshot
its just more redable
fair
i put a screenshot
@earnest phoenix what about it again? I don't think I understood 😅
log that string to console
see if everything's correct
then run the string through mysql to see if it returns data properly
weird
the userid is different from mine?
but what is this userid?
huh? why is it getting the bots userid?
are you sure the msg is the message you get from the event
and not the bot's message
keep in mind that bots also get their own messages
hmm, now that i think about it it could potentially be that but I don't know why it would do that...
possibly
the problem seems to be that the bot is getting its own id though
so how would i prevent that from happening and it finding the userid of the person who used the command?
it seems to fire when a command is used
which actually makes sense now that i think about it
keep in mind that bots also get their own messages
simply return out of the listener if the message author is a bot
Is there a way to get an users intigrations? (Discord.js)
only through oauth2
okay thank you
hi, anyone have an example of chart.js
hey discord.py problem when i do a on_message_event event and i send the before and after content it spams the channel with embeds saying the bot is editing the message when its not here is a photo https://im-a-dev.xyz/D6kN7Sbd.png
https://im-a-dev.xyz/hyKHtzIY.png thats the code
Do you think you may be triggering any of these five scenarios where the event would be fired: https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message_edit
@sudden geyser The message has received an embed. what this mean
@fickle arch what are you struggling on with it?
@vernal rivet learning to make music function xd
is there a way to connect all the shards of my bot?
Where's the difference?
well i was putting it in something like this hello
and that triggered a loop i think
How to get the bots pfp? Js
your own?
Yes
client.user
or that
So something like client.user.avatarURL?
@thick gull no more spam now lol
what the different of module.exports with exports.run ?
now just gotta switch the console lot to an emitter
pog
gers
anyone here discord.py?
just ask your question
File "main.py", line 352, in <module>
main()
File "main.py", line 348, in main
DiscordBot().run(config.DISCORD_TOKEN)
File "main.py", line 18, in init
allData = data.loadJSON(data.DATABASE_FILENAME)
File "/home/container/data.py", line 91, in loadJSON
with open(getFileName(fileName), 'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'database.json'
does anyone know discord.py?
do you?
File "main.py", line 352, in <module>
main()
File "main.py", line 348, in main
DiscordBot().run(config.DISCORD_TOKEN)
File "main.py", line 18, in init
allData = data.loadJSON(data.DATABASE_FILENAME)
File "/home/container/data.py", line 92, in loadJSON
return json.load(f)
File "/usr/local/lib/python3.8/json/init.py", line 293, in load
return loads(fp.read(),
File "/usr/local/lib/python3.8/json/init.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/local/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
your json seems to be malformed
you might want to consider not using json as your database. that's really, really dumb.
yeah don't do that. there are much better ways.
I'm sure you can find an easy sqlite database wrapper or something.
File "main.py", line 352, in <module>
main()
File "main.py", line 348, in main
DiscordBot().run(config.DISCORD_TOKEN)
File "main.py", line 18, in init
allData = data.loadJSON(data.DATABASE_FILENAME)
File "/home/container/data.py", line 92, in loadJSON
return json.load(f)
File "/usr/local/lib/python3.8/json/init.py", line 293, in load
return loads(fp.read(),
File "/usr/local/lib/python3.8/json/init.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/local/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
what does that mean
it means you should not use json as a database.
please don't use it as a database
I don't even know python and I'm sure I know what that error is.
yep. knew it.
Have you considered perhaps learning python before making bots? you seem to have issues with the basics.
I say the same to beginner JS devs: Learn the language Before making bots. Bots are hard, they use complex concepts that are hard to grasp for beginners.
ik json but not a lot of py
i wonder if w3schools has a py course
if not codecademy probably does
The answer to "I don't know a lot" is the same as "I'm learning": go do some online courses or tutorials for basic python first, take a couple weeks, and once you feel comfortable, then do bots.
i think w3 focuses most on web langs tbh
Im now happy with the result of my cache
Happy when i see it
sad when i realize its only step one out of 3

@commands.group
@cooldown(1, 0.5, BucketType.user)
async def dep(self, ctx):
await ctx.send(':lock: Command locked')
@dep.command
@cooldown(1, 0.5, BucketType.user)
async def all(self, ctx, arg, member: discord.Member = None):```
this wont work?
fuction not attribute of command
can my bot have a global command like this !set-bot-prefix?
Yes
I dont trust my code

its working too well
cant do much without more info
¯_(ツ)_/¯
what does your code look like?
@Typical Finney#5282 idk if someone answered your question but the difference between module.exports, and export.run is actually more of a question of what the difference of module.exports and export. The main difference is that module.exports passes it's body as an object. Example
// Message.js
module.exports = "Hello World";
// Index.js
var msg = require("./Message.js");
console.log(msg); // prints out Hello World
Exports is very similar but it passes it's body into a property.
Example
// Message.js
exports.message = "Hello World";
// Index.js
var msg = require("./Message.js");
console.log(msg.message); // prints out Hello World
They are very similar.
exports is basically a shortcut for module.exports
its a reference to the same initial value
right now this just returns the first image in each entry first, but i want it to be randomized so that it returns a different image each time
You know you can just do !args[0] without needing to do args.length == 0
!args.length would be semantically more correct but yeah [0] is shorter lol
Yeah, I mean I am just saying it's kind of useless
images.entries returns an iterable so i want i to be random so i can return a random value from the entries
assign image.values() to an array, then use the Math.random() on array.length thingy
Discord bots are impossible to be hacked unless their server ip and password or token gets leaked right?
yes.
the bot token is pretty much the only attack vector
I mean, unless you mess up your permissions and give open access to an eval function to execute arbitrary code on the server.
so... bad code, token leak, or your VPS being accessed.
your server and infrastructure would be a different category of attack, because it doesnt really target your bot specifically, if your server ever gets hacked, 90% chance the hacker is not targeting your bot, they just want to install viruses and turn it into a zombie
What tim said
ohai Zoro!
I've got a
module.exports = {
}```thing, and I wanna use client.user, but it says client is undefined because it's not there, but I already defined it as a new discord client in another file
well, is what you're exporting a function?
then you should provide your client to that function when calling it
then again in this case, message.client would work just as well
:O
ku
ohai Zoro!
I've got .setThumbnail(message.client.user.avatarURL) but it's not working
If you're using Discord.js v12, .avatarURL is a method.
i am out of creativity to think in new commands for my bot
i wonder if anyone have any ideia
@quaint hornet what is your bot about
everything
Plenty of those around
is there one specific thing your bot excels at // one category your bot is very good at
well most part of the commands are about music
Excels at nothing, amateur at everything
@quartz kindle this didnt seem to work
Check logs
How to add my bot?
i has thinking about some command of AI
but What is too important that need to be executed by a AI
i never see someone using const [i, value] of array before
that's actually called destructuring.
interessing
TypeScript is if JavaScript forced you to be strict and gave you what other OOP languages give you.
A more proper definition would be to see it for yourself: https://www.typescriptlang.org
TypeScript is still compiled down to JavaScript in the end.
TypeScript extends JavaScript by adding types to the language. TypeScript speeds up your development experience by catching errors and providing fixes before you even run your code.
a javascript turned into a csharp?
into a higher oop
javascript but everithing is a object?
is there a way to see what is most closely related to a given string in an array?
hm
you give a word and a array
which one
What do you mean by "closely" related. Sounds like you want to iterate over an array doing something on each element until you find something that matches.
I mean like even if you misspell Pikachi it auto corrects to Pikachu because its the most closely related
What you're probably looking for is called the Levenshtein distance.
if it doesnt use a package and is more efficient than a package then I will accept that as the best answer
oh I found it on stack overflow
dont mind if I do...
If you end up implementing it, I recommend you set it to a number based on the length of their input (in case what you're matching against is short) and a low number, like 2-3.
i have a question
how do i make a welcoming channel through discordpy
pls hel
help*

message.channel.send(message.author.avatarURL({ dynamic: true, format: 'png', size: 1024 })); how do i make it so it sends the bots pfp, not the users?
ok then idk
how do i make a welcoming channel through discordpy
im doing it inside a
module.exports = {
execute: async function(message, args) {
}
}
and client isnt defined
^
everyday i ask my self WHY, WHY!!!
console says DiscordAPIError: Cannot send an empty message
Hi! , I have a question, how can I block the private messages that reach my bot?
check if message channel's type is dm then return it
console says
DiscordAPIError: Cannot send an empty message
your message probabily is just a space
like this
then hoe 2 ficks?
what are you trying to do
ar i undestando
probabily there so lag
or you do something wrong getting the url
get the bots pfp, the code is
message.channel.send(client.user.avatarURL({ dynamic: true, format: 'png', size: 1024 }));
I'd prefer 2048 instead of 1024
how do i use client.startTyping() discord js
1024*1024 is almost fullHD
DiscordAPIError: Cannot send an empty message ^^^^ SyntaxError: Unexpected identifier
how do i make it so my bot id "typing" in the chat
so it shows the status underneath the bar
@worthy glacier <TextBasedChannel>.startTyping() is what you're looking for: https://discord.js.org/#/docs/main/stable/class/TextBasedChannel?scrollTo=startTyping
so i need to resolve the promise by sending a message?
It resolves when the bot stops typing, which I think is based on the count parameter.
I'm a bit confused on what it means, but I think it means the number of times the typing thing should be considered "active". I'd assume it resolves on its own, but you could test it to see.
ok thx
it seems to work during the command but continues aftwerwards continuously until i use another command
i might have to use .stopTyping at the end of commands
Oh yeah
You will need to use that if you want it to stop as soon as the command is over.
djs's typing is a mess
I wish typing could be disabled as a user setting
don't need to be up at 3 am then accidently hit my keyboard
"everyone now knows you are here"
how do i crop an image in an embed if i have an image link?
you need to download the image and process it with some editor, like canvas, sharp, jimp, etc
oh
oh nvm i got it to work well with just doing this
Make sure you check for errors and whatnot that may be thrown from the .run() method // make sure the typing will actually stop
A try block could help
i just do this lol await message.client.api.channels(message.channel.id).typing.post();
that reminds me, why do they make .api return nothing if you try and display it
I can't test it but it would return nothingness and no form of property access would show anything when I tried it with an eval command in the past
its a proxy
ah, I've never tried out proxies in js
its pretty smart what they did, but at the same time so unnecessary and overly complex lmao
basically its a route builder, where methods are converted to api paths, ie .channels() is converted to "/channels" and .channels(id) is converted to "/channels/id"
and so on until you call one of the actual methods (get,post,etc), then it intercepts those and makes the request with the stored path
try console.log(client.api.a(1).b(2).c(3)) lul (if it doesnt show anything, add .toString())
oh, that actually looks very useful
ive got an image in the assets, what file directory like ../ would i need to get that image?
most likely ../assets/image.png
oh thank you

ok
anyone know how to
limit the command
to one channel
like a verify command
no like
you can only use the command]
in one channel
rip
ima go ham mode
to try myself
attach a listener to that channel
and then if !message.content.startsWith(command) message.delete()
@earnest phoenix
If message.channel isnt the channel you want return
eh nah thats not gonna work as well as i want it to so ill do another way
rendered = rendered.trimRight(); is this outdated becayse the connsole says TypeError: Cannot read property 'trimRight' of undefined
or is rendered undefined?
rendered is
how did this bot AniGame (https://top.gg/bot/571027211407196161) get a purple online status??
Its typescript that good or is like php?
@restive notch it is a custom css i guess
typescript is a javascript compiler, has nothing to do with php
no, its not shit
@summer torrent but you can only change the css of the text box
Ok thanks
check dev tools
lol he called php s*it
there is something like .status purple
i use php 
@summer torrent ok
i still use some php as well lol
ehh php is ok but its helpful
"Ugly problems often require ugly solutions. Solving an ugly problem in a pure manner is bloody hard"
Im just here for the meme
if you want memes, both js and php are memed hard
still love that quote from the creator
but i guess php is memed a bit more
JS was probably memed a lot more in the past.
how can I get exec's output? This returns something starts with <* Socket>
https://i.imgur.com/1nnALT6.png
I can't imagine using it without em6
how can I get exec's output? This returns something starts with
<* Socket>
https://i.imgur.com/1nnALT6.png
@summer torrentawait exec()? shouldn't it beawait execSync()?
What is exec declared as.
going to #topgg-api
const { exec } = require("child_process")
wouldn't you need to promisify that if you're going to use await?
oh wait
const MongoClient = require('mongodb').MongoClient;
const uri = `mongodb+srv://${dbuser}:${dbpass}@cluster0.dszlo.mongodb.net/<dbname>?retryWrites=true&w=majority`;
const dbclient = new MongoClient(uri, dbOptions);
dbclient.connect(err => {
const collection = dbclient.db("test").collection("devices");
dbclient.createCollection( "contacts",
{ validator: { $or:
[
{ phone: { $type: "string" } },
{ email: { $regex: /@mongodb\.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
]
}
} )
dbclient.close();
});```
@pale vessel ty
why am i getting an error
dbclient.createCollection is not a function
how do I even use mongodb their docs is so confusing
afaik collections are created automatically if they dont exist
dbclient by itself is only the client, you cant do anything to it directly
you have to work on your database, "test"
oh
WHO DARETH SAY TS IS SHIT?
so if createCollection exists and is valid in mongodb (idk since i dont use mongo), it will likely be on the db, not in dbclient

erwin you okay 
therefore db = dbclient.db("test"); db.createCollection()
i see
oh you want to make it first
most likely it can, but one would assume the database variable will be reused many times throughout the code
nvm then 
hmm
im curious how most bot devs approach this--storing the database client globally or generating a new one for each command
from a client pool
id much rather prefer the latter tbf
for a high-concurrency long-running process, the more stuff you can keep open/connected the better
Day two and not a single line of code exists
magic
let object = await axios(url).catch(function (error) {message.channel.send(error.message)});
is there any way to make this shorter?
let object = await axios(url).catch((e)=> {message.channel.send(e.message)});
let object = await axios(url).catch((e)=> {message.channel.send(e.message)});
@opal plank What happened to everything?
let object = await axios(url).catch((e)=> {message.channel.send(e.message)});
@opal plank How do I use throw??
by reading the docs
@opal plank Where do I put throw "Not Found"
How do I put all the objects inside an array?
How do I put all the objects inside an array?
@carmine summit the same way you put anything in an array
let myArr = []
myArr[0] = someObj
What do you mean?
iirc arrays in JS can be any type of obj
nvm
Where do I put throw "Not Found" in let object = await axios(url).catch((e)=> {message.channel.send(e.message)}); ???
@commands.group
@cooldown(1, 0.5, BucketType.user)
async def dep(self, ctx):
await ctx.send(':lock: Command locked')```
```py
@dep.command
@cooldown(1, 0.5, BucketType.user)
async def all(self, ctx, arg, member: discord.Member = None):```
this wont work?
fuction not attribute of command
You put it where you want it to throw an error saying "Not Found". We can't really tell you where to place something, but .catch may have something to do with it? I'm confused on what you really want.
@drifting wedge what is the real error message pls
discord.ext.commands.errors.ExtensionFailed: Extension 'currency' raised an error: AttributeError: 'function' object has no attribute 'command'
@sudden geyser
Could you try calling .group() to see if anything changes? Also, what line is the error specifically coming from (is it @dep.command?).
@drifting wedge CaLl The DeCoRAToR
okay
i came back
after making other code
to fiond out
how to check if the user is doing the command
in the right channel
Ok
@drifting wedge CaLl The DeCoRAToR
@slender thistle fixed it
how do you make a mute role that overides every channel so a user cant type?
i used to know
ill check my code
message.channel.overwritePermissions([
{
id: message.guild.roles.everyone, deny: ["SEND_MESSAGES",]
}
``` thats a channel permission override you can simply change it to be a role
Can someone help me?
@client.event
async def on_member_join(ctx, member):
await member.send(f'Hope you like the server! {member.mention} make sure to check out the rules!')
embed = discord.Embed(title = "Welcome", description = f"{member.mention} Just Joined \nWelcome to our server :partying_face: \nStay Here and Buy Some Discord Bots! \nYou are the {len(list(member.guild.members))} member!")
embed.timestamp = datetime.datetime.utcnow()
embed.set_footer(text = f"{member.guild}", icon_url = f"{member.guild.icon_url}")
embed.set_author(name = f"{member.name}", icon_url = f"{member.avatar_url}")
embed.set_thumbnail(url=f"{member.avatar_url}")
with open("filename.json", "r") as f:
guildInfo = json.load(f)
channel = guildInfo[ctx.message.guild.id]
await channel.ctx.send(embed = embed)
this is my code
let muteROle = guild.roles.create({ data: { name: 'Mod'});
muterole.overwritePermissions([
{
id: message.guild.roles.everyone, deny: ["SEND_MESSAGES",]
}
```? idk
but when i run it
it says: TypeError: on_member_join() missing 1 required positional argument: 'member'
@client.event
async def on_member_join(ctx, member):
await member.send(f'Hope you like the server! {member.mention} make sure to check out the rules!')
embed = discord.Embed(title = "Welcome", description = f"{member.mention} Just Joined \nWelcome to our server :partying_face: \nStay Here and Buy Some Discord Bots! \nYou are the {len(list(member.guild.members))} member!")
embed.timestamp = datetime.datetime.utcnow()
embed.set_footer(text = f"{member.guild}", icon_url = f"{member.guild.icon_url}")
embed.set_author(name = f"{member.name}", icon_url = f"{member.avatar_url}")
embed.set_thumbnail(url=f"{member.avatar_url}")
with open("filename.json", "r") as f:
guildInfo = json.load(f)
channel = guildInfo[ctx.message.guild.id]
await channel.ctx.send(embed = embed)
error: TypeError: on_member_join() missing 1 required positional argument: 'member'
pls help me
Why DM me personally again
you're not providing all the required arguments?
thing1
await thing2
thing3
does thing3 only happen after await thing2 has been done?
@sonic lodge i tried doing this:
@client.event
async def on_member_join(member):
await member.send(f'Hope you like the server! {member.mention} make sure to check out the rules!')
embed = discord.Embed(title = "Welcome", description = f"{member.mention} Just Joined \nWelcome to our server :partying_face: \nStay Here and Buy Some Discord Bots! \nYou are the {len(list(member.guild.members))} member!")
embed.timestamp = datetime.datetime.utcnow()
embed.set_footer(text = f"{member.guild}", icon_url = f"{member.guild.icon_url}")
embed.set_author(name = f"{member.name}", icon_url = f"{member.avatar_url}")
embed.set_thumbnail(url=f"{member.avatar_url}")
with open("filename.json", "r") as f:
guildInfo = json.load(f)
channel = guildInfo[member.guild.id]
await channel.send(embed = embed)
but i get an error
channel = guildInfo[member.guild.id]
KeyError: 747929495427874836```
oh, this is what happens when a js dev with little python experience tries to help
oh lol
you are really overestimating my python knowledge
i just thought the problem was a general programming one
@silver lintel do u know how to help?
@client.event
async def on_guild_join(guild):
#loads json file to dictionary
with open("filename.json", "r") as f:
guildInfo = json.load(f)
guildInfo[guild.id] = guild.text_channels[0] #sets key to guilds id and value to top textchannel
#writes dictionary to json file
with open("filename.json", "w") as f:
json.dump(guildInfo, f)
#allows server members to set channel for welcome messages to send to
@client.command()
async def welcomeChannel(ctx):
with open("filename.json", "r") as f:
guildInfo = json.load(f)
guildInfo[ctx.message.guild.id] = ctx.message.channel.id #sets channel to send message to as the channel the command was sent to
with open("filename.json", "w") as f:
json.dump(guildInfo, f)
await ctx.send(f"I have set the welcome channel!")
@client.event
async def on_member_join(member):
await member.send(f'Hope you like the server! {member.mention} make sure to check out the rules!')
embed = discord.Embed(title = "Welcome", description = f"{member.mention} Just Joined \nWelcome to our server :partying_face: \nStay Here and Buy Some Discord Bots! \nYou are the {len(list(member.guild.members))} member!")
embed.timestamp = datetime.datetime.utcnow()
embed.set_footer(text = f"{member.guild}", icon_url = f"{member.guild.icon_url}")
embed.set_author(name = f"{member.name}", icon_url = f"{member.avatar_url}")
embed.set_thumbnail(url=f"{member.avatar_url}")
with open("filename.json", "r") as f:
guildInfo = json.load(f)
channel = guildInfo[member.guild.id]
await channel.send(embed = embed)
```my entire code
Are you going to keep messaging me and this server at the same time
no
apparently KeyError appears when you try to access a dictionary with a key that doesn't exist
sorry, i cant help, my python knowledge is even less than pooled
see if there exists a key in guildInfo before accessing it
P.S. just because you think it exists doesn't mean it actually exists
Workaround is to use guildInfo.get and check if it returned None
so what should i do?
I just said what you can do
thing1
await thing2
thing3
does thing3 only happen after thing2 is done?
As far as I'm familiar with asynchronousness (I barely am), yes
I'm not really sure what you mean by
Workaround is to use guildInfo.get and check if it returned
None
Search dict.get python on Google
ok
so how should i use that?
@slender thistle when i look at my file, where it stores the dict
it shows this
{"747929495427874836": 748295756053741770}
maybe is it because the keyname is a string?
Yes
Stringify the ID when trying to access the key
ok
@earnest phoenix what should I see here? :)
Let see
You need to make a bot that detect when dsl bot give out the vote role
When the dsl give the vote role to someone, that mean that person voted your server
So yeah, thats all.
hopefully iOS 14 gives me better file access so I can run this bih
Also the phone I’m using is stuck in beta and I can’t go back to 13
i can tell you right now
you likely wont get anywhere using IOS
bots running on iOS? good luck
Why would you want to do that in the first place.
I still don't understand the different of module.exports with exports.run
@fickle arch so
exports mean export stuff
You can get stuff by require the file
For example
example1.js
exports.hi = 'hello';
exports.bool = false;
exports.json = {
"e":"i"
}
And on example2
example2.js
const example1 = require("example1.js");
example1.hi // hello
example1.bool // false
example1.json // that json data
module.exports mean export something as default
example
module.exports = "e"
require("example"); // e
I tried my best to explain it
Np
Is there a way I can make a bot send a message in a channel if a member upvotes a server on the top.gg discord server list
@boreal flume hhh
#development message
Idk if server webhook exist or not
But if it exist, use the webhook method
But webhook method is not recommded
That is easy, you can just use the bot.on('roleUpdate') event listener, correct?
Yes
However, you need the owner to slecify the role id for the voting
So besure to do that
also
memberRoleUpdate
anyone could give me good API for punch command 🤔
@fickle arch
Theres alot
Let me see it.
ty @quartz kindle that worked perfectly
There is not memberRoleUpdate listener
KSoftAPI,
nekos.life (not recommded),
nekos.club (not recommded),
asuna.ga (maybe recommded),
weebsh (invite only).
@boreal flume member update
Is there a role parameter for that?
well
memberUpdate return
oldMember:GuildMember and newMember:GuildMember
And guildMember class have .roles
So, I have to do some logic lol
Yes
is guildMember.roles.cache.has(...) a function?
Idk
maybe === will work ig
unless the discord collrctiom have compare functiom
does old guild member come first in parameters?
Yes
That was very easy logic
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h4>Jazz</h4>
<h4 style="text-align: right; margin-bottom: 20px;">Portfolio</h4>
<h4>Contact me</h4>
<hr>
</body>
</html>``` somebody please help me get the pOrtfolio and contact me on right side
its been years since i coded so dont judge mee
i can get it on right side but cant get it on same line...
if(srole.position >= message.member.roles.cache.position) return message.channel.send(noPermissions);```
Hello, Does anyone know if I did something wrong, cause it doesn't seem to return;
Why check 2 times
Also, you don't need to return message.channel.send
if(srole.position >= message.guild.me.roles.cache.position){ message.channel.send(noPermissions); return}
Ehh, more work somewhat
I always add return afterward
eh
More of a preference imo
I call the function, THEN return
return message.channel.send work fine
- its easier
Unless your function return spefic value then you can use that
should I use ytdl or lavalink for music function ?
@fickle arch lavalink is better
I don't do music, but everything I have read about it uses ytdl
a lot use ytdl kinda.
Why though
Bruh I did
Ima try use lavalink and let my brain processing a bit.
It didnt send error message?
if I do like !addrole <user> <role>, if role is higher than bot or the author, it doesnt return. It justs say it adds but it doesnt
I want it to return
but it doesnt
you mean of return ?
you mean like this for addrole stuff ?
the only add-role commands I have made creates roles
you mean like this for addrole stuff ?
@fickle arch Yes, but if the role is higher than the bot or the author performing the command, it should return
But it doesnt return
@fickle arch Yes, but if the role is higher than the bot or the author performing the command, it should return
@feral aspen Try starwoman solution, I'm still dumb dumb about coding 😆
how do you edit a message after like 3 seconds in js?
You need to get the highest one
@earnest phoenix THANK YOU sooo much]
Idk what I'm doing rn-
message.channel.send("hi").edit{timeout: 3000} something i forgot
No
@silver lintel you have to create your own timrout
setTimeout(function, timeout in millisecond);
Is that even calling syntax
message.channel.send('hi')
.then((msg)=> {
setTimeout(function(){
msg.edit('hello');
}, 1000)
});
It's not even a parameter of the method. Just an object thrown right there next to the method
so like this?
I haves another question about the voting thing
Does it take the role off after the 12 hour period?
Yes
So, I can add in a feature that sends a message saying their vote wait has expired
Yeah
Though, that seems like kind of a dickish thing to do lol
"Oh, we see you have finished waiting for the vote. GO VOTE NOW!!!!!!"
TypeError: message.guild.createRole is not a function
how do i make a mute role with overide perms so a user cant type?
mute function 🤷♂️
how
Yes I mean that
You misunderstanding
overall channel mute chat right ?
Mute only work for vc
let mootRole = await message.guild.createRole({
name: "Muted",
color: "#ff0000",
permissions: []
});
message.guild.channels.forEach(async (channel, id) => {
await channel.overwritePermissions(mootRole, {
SEND_MESSAGES: false,
ADD_REACTIONS: false,
CONNECT: false
});
});
i did this
but im pretty sure its wrong
wait how you send text like that I forget lol.
```js
blah blah blah
```
ohh
I was meaning like this before
TypeError: message.guild.channels.forEach is not a function i came back from 2 year coding break, so everything i type is v11, whats this function in v12?
@silver lintel uh
my way probably sucks
https://github.com/discordjs/discord.js/releases/tag/12.0.0
https://discordjs.guide/additional-info/changes-in-v12.html
channel.updateOverwrite(channel.guild.roles.mootRole, { SEND_MESSAGES: false });?
sigh
In v11 .channels return collection of channels
But now in v12
.channels return ChannelManager
update your bot code to v12
channelManager.cache retuen collection of channels
yes, im rewriting a bot
@austere fern https://discordapi.com/permissions.html
A small calculator that generates Discord OAuth invite links
Ok
or just invite bot, and change the ID with your bot ID
@fickle arch bad practice
I do that before so 🤷♂️
Use api calculator and select the bot permission your bot need
Not admin directly
I see.
thank you starwoman it works
So basically. I want a code and need someone to explain me that how to make a command that sends random memes
@sick fable your better learn coding language of your choice first
memes API
And no we wont spoon feed
your choice.
@sick fable your better learn coding language of your choice first
@earnest phoenix I am learning it
If your want discord.py then fo with it
Heres how we do it
So first we need an reliable api
You know what api is?
Same
Oh fuck
My brain stop working after writing lines of code.
Lol
https://en.m.wikipedia.org/wiki/API#:~:text=An application programming interface (API,the%20conventions%20to%20follow%2C%20etc.
An application programming interface (API) is a computing interface which defines interactions between multiple software intermediaries. It defines the kinds of calls or requests that can be made, how to make them, the data formats that should be used, the conventions to foll...
My brain stop working after writing lines of code.
@fickle arch same bruh
You send request to api, then api sned back image, buffer, or url to the image
Nvm
Oh*
@slender thistle
What am I needed for
Idk
Explain them how to get memes
Yes
Using python
pats aiohttp
This good boy is asynchronous and doesn't block your code
Axios is python libaries wdym
Since when
wait wut
What did you sniff today
srsly
its only for browser and node?
requests for sync
aiohttp for async
requests is blocking
While request is processing, the entire process stops and waits for it to finish
While that's happening, your client can't acknowledge heartbeats from Discord and your bot goes offline after a while
depends
Async with async good
Async with sync good if it's not blocking too much
So if i understand correctly
Sync stop process and wait for stuff to be done
While async dont?
In a way
in simple terms ig
Ty ig
what is code for wtch guild id
im trying to make command with bot can react to message // command : f!command {messageid} {emoji}
@blazing ravine Dont expect to be spoonfeeded code
@slender thistle do the spoonfeed commanf
gj
let mootRole = await message.guild.roles.create({
data: {
name: "Muted",
color: "#FF0000",
},
});
``` how to change permissions of this role?
permissions property
not work 😦
with an array of objects like this
{
id:"2342342",
allow:
deny:
}
i guess
its been a while since I didnt use djs
anyways readthedocs
@silver lintel
dammit
30 secs to search
what did you search?
well thats for the data: {} part
ok
well just the discord.js doc
let mootRole = await message.guild.roles.create({
data: {
name: "Muted",
color: "#FF0000",
permissions: "SEND_MESSAGES" false?
},
});
how im still confused
becAUSE THEY Dont really give an example
lemme spoon feed u
thanks :}
oh wow
or watch indian tech guy on youtube about programming language 🤔
exactly
message.channel.overwritePermissions(mootRole.id, { SEND_MESSAGES: false});
they help me solved how to revive my dead phone from 2 years ago 
how do i do it to all the channels in a server?
put it in rice
how you expect to dry a dried phone 🤔
how you update node.js to current version ?
javascript is weird too much
functions are instances of the Function class
classes are special functions
how to check if a user's highest role is higher or equal to another user's?
@silver lintel #GuildMember.roles.highest.position
<member>.roles.highest.positon
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'position' of undefined
let authorHighestRole = message.member.highest.position;
let mentionHighestRole = kickMember.highest.position;
if (mentionHighestRole >= authorHighestRole) {
return message.channel.send(
"You can`t kick members with equal or higher position"
);
}
@austere salmon i would recommend https://repl.it for temporary bot hosting
Repl.it is a simple yet powerful online IDE, Editor, Compiler, Interpreter, and REPL. Code, compile, run, and host in 50+ programming languages: Clojure, Haskell, Kotlin, QBasic, Forth, LOLCODE, BrainF, Emoticon, Bloop, Unlambda, JavaScript, CoffeeScript, Scheme, APL, Lua, Pyt...
move to a VPS like https://vultr.com when you think you can afford it
@earnest phoenix never recommend free hosting
temporary
Dont
yea but PINS
@austere salmon look at pins
I want it for free
@austere salmon repl.it is a good enough free service for doing bot stuff but you should move to a VPS ASAP
@misty sigil any free vps
check the pins istg hayper
@earnest phoenix Thank you
@coral trellis come here stinky
ok
@wintry niche
@slender thistle this guy is talking via his bot
E?
🤔
Lemme try to invite it again
let kickMember = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0]);
console.log(kickMember);
avatar: 'e5a433d2ca73e2631441123689d2609b',
it comes up with ^, i want the avatar, but how do i get it with these numbetrs and letters?
@silver lintel its hash
oof
kickMember.displayAvatarURL() or kickMember.user.displayAvatarURL()?
ok
Hello how i can store json from webapi?
@elfin tulip let not use json database
is this the proper way of handling perms for purge command?
if (!message.member.hasPermission('MANAGE_MESSAGES')) return message.channel.send('');
if (!message.guild.me.hasPermission('MANAGE_MESSAGES')) return message.channel.send('');
yes
maybe send a message saying you dont have perms
if you are not going to send anything
just do return;
no need for the message.channel bit
hum
the thing is with new bots people probs gonna think it my bot's bug and not there fault
yea..
btw ur gonna get errors when the command has been triggered
how
yea, dont do that, just do return
i have text in it dw
is the text saying u dont have perms or something
so something like this
if (!message.member.hasPermission('MANAGE_MESSAGES')) return message.channel.send('**Error:** You can not do that. Missing permission `MANAGE MESSAGES`');
if (!message.guild.me.hasPermission('MANAGE_MESSAGES')) return message.channel.send('**Error:** I can not do that. Missing permission `MANAGE MESSAGES`');
const amount = parseInt(args[0]);
if (isNaN(amount)) {
return message.reply('**Error:** Not a valid amount.');
} else if (amount < 2 || amount > 100) {
return message.reply('**Error:** Input a number between 2 and 100.');
}
message.channel.bulkDelete(amount, true).catch(err => {
console.error('Purge:\n' + err);
message.channel.send('**Error:** Unable to pruge messages in this channel.');
});```

well its scary it didnt
Ahh good
oh right
Bulk delete rounds
Just do integer.parse
I t hi nk
1 message is it self
Yea, do bulkDelet(amount + 1.....
that's what parseInt do lol
so ive got let kickMember = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0]);, and i did console.log(kickMember), and the console is
a big big json like collection idk, but i wanna do something like kickMember.send(), but kickMember isnt a member. so like how do i make it a user
Can someone give me a music code for my bot?
@elfin tulip let not use json database
@earnest phoenix ??
Idk how to work that music for my bot
@cyan mulch i suggest deleting the message
you literally opened your database to the public
humm message.guild.member(message.mentions.users.first())
i can get the id of kickMember tho
why
message.guild.member(message.mentions.users.first())
and not
message.mentions.users.first()
You can do message.mentions.members.first()
wait bruh
why do i have message.guild.member(message.mentions.users.first())

welp

also would like to ask
when the mentioned user gets kicked
he is only kicked from that server and not other servers right (if bot and user have in common)
or do i have to specify?
the current server
cool
hum so lets suppose
There are three roles
Bot
admin
mod
all of em have KICK_MEMBERS perms
as discord works mod cannot kick admin as he has a higher role
but what if he uses the bot and kicks admin 
thats why you should have a special thing
let authorHighestRole = message.member.roles.highest.position;
let mentionHighestRole = kickMember.member.roles.highest.position;
if (mentionHighestRole >= authorHighestRole) {
return message.channel.send("You can't kick members with equal or higher position");
}
tasty pasta
doesn't member.kickable handle that for you already?
oh yea
the mod uses the bot
you should only do that if you want to check the mod's permission too
i didnt knew about member.kickable let me see
doesn't look like it checks
if (!message.member.hasPermission('KICK_MEMBERS')) return message.channel.send('**Error:** You can not do that. Missing permission `KICK MEMBERS`');
if (!message.guild.me.hasPermission('KICK_MEMBERS')) return message.channel.send('**Error:** I can not do that. Missing permission `KICK MEMBERS`');
const member = message.mentions.users.first();
if (!message.mentions.users.size) return message.reply('**Error:** You need to tag a user in order to kick them.');
if (member.kickable) {
try {
await member.kick();
} catch (err) {
console.error(err);
}
}```
something like this?
from my limited and small understanding, member.kickable is if the bot can kick it?
my kick command has this
if (!kickMember.kickable) {
return message.channel.send("I don't have permissions to kick this user");
}
i may be wrongh
cool feature













