#discord-bots
1 messages Β· Page 979 of 1
it not on_member()
it on_guild()
they havent even said what problem they're having yet
on_member_join and on_guild_join are separate events
I know u didn't wanna sound like it but it felt as if u were gonna kill him for using replit if u met him irl π
):
is python really a good language for making a big discord bot?
He didn't mean it tho, dw
He is just a kind and innocent helper
i wanna send welcome message when someone joins my server
Sure
I made a 2k line script for it, so yea
i have a bot already in rust and i was thinking of adding few commands with python but i am scared of the time it will take to restart
Just use cogs for it to run faster in my past experiences π
rust is also good
nahhhhhhhhh
line isnt concerning rather its the server count
are you sure about that?
i mean i code bots in python
@client.event
async def on_member_join(member, message):
await message.channel.send("")
# or...
embed = discord.Embed(
title='',
description='',
url='',
color = discord.Color.random()
)
await message.channel.send(embed=embed)
Databases will really help
what about shards tho
is it more efficient to use try/catch rather than if/else when you have to go through a dictionary of say 2000 entries?
wont it take time because of shards
Shards? π³
I have never used shards
imagine a restart that takes approx 2hrs
discord doesnt easily provide this information, so you'd have to manually track the invite uses in the server and see which one increases when they join (or for temp invites check the audit log)
would be pain
Bro, not even big bots like Dyno take that much
(round(bot.latency * 1000))
it depends on how you manage the gateway and which language you use tbh
If your VPS specs are good, then sharded bots won't take much to start up
Ikr, or Dank Memer
big bots prob have custom made gateways
mee6 is made in python so that news
if x in big_dictionary:
if y in big_dictionary[x]:
### VERSUS ###
try:
if y in big_dictionary[x]:
except:
pass
My bots can turn on in 4 seconds
but cython maybe
@sick kettle calm down don't worry
Even sharded bots don't take much to start
You can look at bots in https://discord.gg/dpy, specifically R. Danny.
It is fully made in Python but with the correct specs, takes seconds to start
it would be weird yknow that the whole bot is made in rust but just a small part is made in python
am i a good person ):
@client.event
async def on_member_join(member, message):
embed = discord.Embed(description='Welcome to our guild!', color=random.choice(client.color_list))
embed.set_thumbnail(url=member.avatar_url)
embed.set_author(name=member.name, icon_url=member.avatar_url)
embed.set_footer(text=member.guild, icon_url=member.guild.icon_url)
embed.timestamp = datetime.datetime.utcnow()
await message.channel.send(embed=embed)
Bro, no one gives a fuck
Ofc
are you sure?
i guess but the users would give a fuck if it will become slow
is this okay
meh
As long as it works, it doesn't really matter
Calm down, it won't be slow as long as u write good code
do you think i should do some changes to the api wrapper like discord.py or pycord to fit my bot
what kind?
Probably not a question for here, but I do not know how to add a compiler to VS Code
my kind π
like changing the gateway according to the current shard size
Dude you CANNOT change the gateway
removing unused imports from the library etc
PoV: No import is unused
whats the Cannot about in it tho
bro @maiden fable is right u cant change it
If you try to, you are breaking ToS'
I think
its done in rust so why not in python
very true
How tf u gonna access the gateway code π
yeah
Google Dev Tools
You can only change how you connect to the gateway
ah same thing same thing
hmm π€
Sure, the url to the gateway is wss://gateway.discord.gg/?v=9&encoding=json
No it is not LMAO
And how u gonna edit how u connect to the same, bro
......?
Hmm
reporting to discord... imagin
that depends upon how i need it to be at that time
rn i havent even started coding in python just because i am getting paranoid with this "slow" word
the language isnt slow
Dude, Python isn't even that slow what the
Python isn't slow
It is sometimes faster than other langs like C#
It just gets slower for stuff like GUIs and websites
It's how you code it, I recommend using cogs for optimal speed
Yes. It depends a lot on how u code
Bad Code -> Slow Speed
Good and Esoteric Code -> Fast Speed (in most cases)
imagin
Yep
its just slow because its a general language and because its interpreted and somethings in python are as fast as native c
it isnt slow and ik cause i have been working with python for about 2yrs but adding the discord bot concept to the language is what that makes me paranoid
Bro π
It isn't slow
ik bro π
Carl bot is coded in Python
reset i think you have a case of paranoia
HOW DO I USE PYTHON APP TO FREAKING START MY BOT!!!!!!
My bot's latency is 70ms what you talk about?
Calm down calm down
bro
NOOO
Uh, latency depends on your internet connection and not on the code
BECAUSE I ONLY KNOW HOW SE REPLIT!!!!
i shouldnt be overthinking and give it a try and if it really doesnt work out for me then maybe i switch to java or rust
bro whatπ
THIS IS IMPOSIIBLE
Why not just write it in Rust?
maybe do
Hm?
SHUT UP
cause i hate rust
the latency attr in the bot class only gives the latency of an ack hb and not the latency to the api
I mean, rest of the bot is written in Rust
its syntax makes me wanna cry myself to sleep
It still depends on the Internet. The ack hb would be late if the internet is slow
THAT'S OKAYYY JUST USE THIS https://discordpy.readthedocs.io/en/stable/quickstart.html FOR REFERENCE.. AND TRY TO RUN IT OKAY?? U HAVEN'T EVEN SHOWED THE CODE AND YOURE' ASKING FOR HELP.. SO USE IT FOR REFERENCE
Ngl C#'s syntax is sane
Be nice, we are trying to help you π
lmao
if it were so slow to matter it would probably get disconnected
Can everyone calm down?
no
bot has two main categories
music and economy, music is rust but economy currently in nodejs
Yes
how
xD jk lol
Why tf
Just go with a single lang dude
broo wftff bruoo
can someone help me
i could use nodejs yes but that was made by another dev and i am not good with nodejs as much i am with python
You will get mad, tryna maintain the bot
This dude trying to pull 3 different languages in 1 bot π€£
cause speeeeeed
yes pls ask (not to me tho :> )
speed wouldnt matter in a bot
How can i use anyother app or something to start my bot ):
why do you think the big bots switches languages at a certain point of time
VS code
none of them have?
Bruh, carl bot uses Python
π
IDFK HOW USE IT
it does if its a music bot but not much for economy
@sick kettle Music Bots are against ToS anyways
- Do not scream at me.
- It is simple to use. π
no it doesnt.
yes but all other are in either JDA or eris
I am using Pycord library 2.0.0b4, I am making a ping command which can only be used by certain roles. But this is not working, everyone can access it.
Can anyone help me with this please? I even tried has_role()
@bot.slash_command(guild_ids=[GUILD_ID], default_permission=False)
@permissions.has_any_role("admin")
async def ping(ctx):
"""Say hello to the author"""
await ctx.respond(f"Hello {ctx.author}!")```
i tryed it showed this....
see.. u always need a host to run bots okay... either use vsc.. or your cmd.. :") whatever you're comfortable with (although both are almost same lmao)
shush its not tos realted music bot
No?
it did for the other dev and rewrote the whole code from nodejs to rust apparently
i think im just gonna leave because of this chaos maybe ill return when the new thread comes(ill probably return later on the day)
except that smh
yh
yeah the most popular bot is made with python (private wrapper)
Yea
import gay
And the reason they used a private wrapper is cz they just wanted custom syntax for their bot
- in the folder make a venv( optional)
- run your file like
py python main.pywhere main.py is the name of the main file :'/
Its not like dpy does anything wrongly π
idk how u do that
π
ig i should give pycord a try and if it doesnt workout then maybe change to nodejs and if that too doesnt workout then cry myself to rust
yes they do!
do u have you rcode in your local computer?
Not pycord pls, people prefer disnake
π π π π π π
idk
disnake never used
oof pycords source is horrible and not type safe
pycord used and contributed ig
π why udk?
@unkempt canyon uses disnake
idk ):
i think they migrated back but not my point
π then who is suppose to know?
but i need to relearn a lot of functions then π
pls help ):
ok so where are your code files right now?
ok so how many files are there?
2
how
ok
What is Custom Python
Custom Wrapper
Oh, so they made their own?
yea
Damn, must have been tough xD
not really hard
Its easy peasy
I could make my own? :OOO
we should make oneπ
How many lines would it take?
Bruh
depends on codebase
Hmm
Don't ever think about the number of lines it will take
but it will take allot of time because endpoints models etc
Ima check out yt π
dont.
Mk that is fine
yts tutorials are horrible just check out ddocs
I can bet
in total way more
π , which docs?
@fresh kestrel
discord developer docs
Okay
@slate swan
I am very familiar with that website
π ok so.. do u have python installed?
i do
good
k
Windows 11 cringe ngl
sometimes
):
Windows 10 supreme
now i'm feeling offended lmao
now what
ok back to u
good (:
are you familiar with ratelimits hb intervals ws gateway events and how to parse them and entities??
in that folder.. open cmd
No π³
you have allot to read on
`Traceback (most recent call last):
File "C:\Users\ollie\PycharmProjects\Maxy Logs\main.py", line 25, in <module>
confession_channels = json.load(f)
File "C:\Users\ollie\AppData\Local\Programs\Python\Python310\lib\json_init_.py", line 293, in load
return loads(fp.read(),
File "C:\Users\ollie\AppData\Local\Programs\Python\Python310\lib\json_init_.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\ollie\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\ollie\AppData\Local\Programs\Python\Python310\lib\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)
Process finished with exit code 1`
Does anyone know how to fix this error? I've been searching it up and trying solutions but i cant find one
start on docs of the gateway
omfg dont send a big thing blocking chat
Which one xD
Right...
looks like invalid json
anyways (:
Yea i know that
show me the json then lmao
I just havent found a way to fix it
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
@slate swan
?
now what
ok now
How do i get the amount of boost for server?
instlal required libs @eager bough
u hack discord?
?
how
how!??!?!?!
class discord.Guild```
Represents a Discord guild.
This is referred to as a βserverβ in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guildβs hash.
str(x) Returns the guildβs name.
Mk, and it is in Js and not Py Hmm
i mean which lib you're using for bot?
@slate swan HELP! NOW WHATT
the docs are in javascript yes.
π i asked for json file.. not the py code
Look on the left.
The json file is empty lol
How could I make it into Python tho? π
WAITING...
should have told me first lmao.. ok so..
you only need to worry about parsing the json data
Ah
``` if you're using discord.py
install your libs accordingly
This looks like alot of code π
So what do i do?
ok back to u
uh oh @slate swan
Ima go learn and try my best :OOOO
let it finish
it done
best of luck!
I will try, ig
now.```py
python main.py
try your best then!
Ye
showing lots of codes (:
show me the code :")
Eito?
uhm.. not sure but like.. try to put this ```json
{}
and try again ig
):
anyone has a script that works for bots checking user status for a invite like discord.gg/python, /python and works for multiple servers, not just one server
π
like its able to be configured
do u have internet connection...? idk.. never had that kind of error.. but it doesn't look like an error with discord.py or with your code
did it work?
Checking
idk?
Ill tell you if it did
π bro, u don't know if you've internet connection on your pc??
now i got instenet
yes pls
internet
π u gotta be kidding me fr π
):
I just have to wait it to sync since its a new slash command and it takes forever
now what i type in cmd @slate swan
python main.py
e
aah i see.. which lib you're using btw?
discord-py-slash-command
discord.Guild.premium_subscription_count
ok i never used it nvm.. idk how to help there
):
It works it just takes ages to sync the commands
taht question was for it was for ol1
it shoujld be 1 hour
same error? :'/
Thats what i hate, whenever i update a command I have to wait an hour or so to make sure it works
@slate swan
@slate swan
π can understand
yeah sorry i was afk :'/
@slate swan!!!!
gimme a min broo
π¦
Is your OS on the newest version ?
Ussualy outdated certificates are installed this way
ok @eager bough my answer is still same.. it doesn't look like this is an error with your code or discord.py.. this is something with your pc ig
i'll try to look for the solutoin on internet and will let u know if i find any
:'/
:'/
(:
can help me ))::::
!d discord.Guild
class discord.Guild```
Represents a Discord guild.
This is referred to as a βserverβ in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guildβs hash.
str(x) Returns the guildβs name.
ye :'/
trying to get the channels that are private lmao
so u help me son (:
):
:">
):

I NEED HELP!!!! @slate swan
@slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan
@slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan
:'/ yes bro?
Idk what to do ngl, actually confusing
@slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan
You must like pings π
@slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan
π
An exception has occurred while executing command confess: Traceback (most recent call last): File "C:\Users\ollie\PycharmProjects\Maxy Logs\venv\lib\site-packages\discord_slash\client.py", line 1353, in invoke_command await func.invoke(ctx, **args) File "C:\Users\ollie\PycharmProjects\Maxy Logs\venv\lib\site-packages\discord_slash\model.py", line 210, in invoke return await self.func(*args, **kwargs) File "C:\Users\ollie\PycharmProjects\Maxy Logs\main.py", line 67, in confess channel = bot.get_channel(confession.channels[str(ctx.guild.id)]) File "C:\Users\ollie\PycharmProjects\Maxy Logs\venv\lib\site-packages\discord\client.py", line 793, in get_channel return self._connection.get_channel(id) File "C:\Users\ollie\PycharmProjects\Maxy Logs\venv\lib\site-packages\discord\state.py", line 1118, in get_channel pm = self._get_private_channel(id) File "C:\Users\ollie\PycharmProjects\Maxy Logs\venv\lib\site-packages\discord\state.py", line 329, in _get_private_channel value = self._private_channels[channel_id] TypeError: unhashable type: 'list'
When i try and run the command
@slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan
it's just that.. you get only 1 ping even if someone pings u 100 times in a message lmfao
bro stop
@slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan
:)
makes it more funny
):
Yea
@slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan @slate swan
<@&831776746206265384>
!mute 857785190625181698 1h investigating
:incoming_envelope: :ok_hand: applied mute to @eager bough until <t:1650056036:f> (59 minutes and 59 seconds).
π€ not sure but ilke try.. ```py
channel = bot.get_channel(int(confession.channels[str(ctx.guild.id)]))
ik lmao , i ain't dumb
π³
π³
Oh yea, integer as its a ID, that may be the issue
lol
yeah... for now i'm thinking that only...
if it doesn't work.. then.. let's try agian lol
Let me test
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
need help
okkk wait.. ig u need to install it from github branch not from pypi
ok so first, uninstall your current discord.py by ```py
pip uninstall discord.py
channel = bot.get_channel(int(confession.channels[str(ctx.guild.id)])) AttributeError: 'str' object has no attribute 'channels'
now ```cmd
pip install discord.py @ git+https://github.com/Rapptz/discord.py
π show me code pls
i make a button with the bot
when i send msg bot replay to my msg with 2 button
i need afet i click to them delet the messege of the buttons
how can i do it ,
Is it possible to add a feature to my discord py bot to restrict users to only be able to send images to a certain channel? Or at least to auto-delete every message that is not an image/video?
a filter variable maybe π€
π¦
In a codblock please
@slate swan
Yeah, if something needs immediate attention (like that situation) a ping is fine. If you want to report something without a ping, DM'ing @novel apex is the way to go
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Someone ping me?
What's this
what has happened to this chat
Ignore him
Good question π
π pls use some hastebin or something.. it is so difficult to look for it though messages
alright, thanks (i knew that already i was just chilling lmao, but again, thanks :> )
Please DM @novel apex and if needed, you can block a user
hey brad
whats your opinion on the new thread thats coming for this chat?
Yeah sure
I think it's a great idea, can't wait to see the discussions that happen with the change in focus
What thread? :OOO
same here im quite excited for the future discussions and what i will learn being in the chat.
can anyone help me how i remove this
Ah
ill for sure be there
Okimii you gave me the right link to the developer docs no?
i did because?
This makes no sense
what makes no sense
The beginning
do you have 2.0
Like what is this?
the payload structure of the endpoints
do you have pycord or 1.7.3?
What do I do with it? The docs are too confusing π
nothing you read it and learn the payloads for when you need to parse the payloads
delete them
?
Yea this makes no sense
have you ever worked or wrapped an api?
i suggest you wrap another api that doesnt use ws like discord
Like what?
any api thats REST
any RESTful api would be good
thats just showing whats a restful api lol
Then what do you recommend I use
discord π
i would recommend you wrap an api that doesnt haev a gateway or ws
Hmm
Would it be easier to use REST
^
andy bro hes starting
the RESTful API isn't hard
yeah
It's the gateway
what api would you recommend that I wrap
any maybe a dog api which doesnt gave much endpoints and doesnt use auth or a token and most have 2 entities like i.e big dog and small dog
mulesoft?
never heard of it, wrap any api you would like that can be easier for you!
π
That is good
folder_name_head = "head/"
folder_name_head_3d = "head3d/"
#folder = os.path.join(folder_name, nick)
def head(url_2, file_name):
file = folder_name_head+file_name+".png"
urllib.request.urlretrieve(url_2, file)
@bot.command()
async def head(ctx, nick):
else:
url = f"https://minotar.net/helm/{nick}/100.png"
file_name = nick
head(url, file_name)
await ctx.send(file=discord.File(f"head/{nick}.png"))```
head(url, file_name)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
you probably forgot to await something
can I send modal using command ctx ? or is it only interaction
Only interactions.
scoopy hydπ
Heyy okimii, I'm doing good wbu?
im doing better
I'm glad to hear that 
π
Hey can someone help me?
can someone help me rq?
class Counter(discord.ui.View):
def __init__(self, *, timeout=180):
super().__init__(timeout=timeout)
@discord.ui.button(label='Close π©', style=discord.ButtonStyle.primary)
async def counter(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.send_message('test')
the error is
AttributeError: 'Button' object has no attribute 'send_message'
nvm i figured it out
how do i get the user that clicked the button?
interaction.user
yes
new syntax is ```py
async def button(self, interaction, button):
...
you overwrited your old head function
I'm trying to make a feature where a user can setup a channel that command outputs are sent to
I want to use a json file to store the data of the setup channels in the guild id it was setup to
what are you having trouble with in this?
channel = bot.get_channel(int(confession.channels[str(ctx.guild.id)])) AttributeError: 'str' object has no attribute 'channels'
what is confession?
Advise: donβt
Music bots violate YouTube terms of service
I Fix that
I have the same name
Command and function
you did confession.channels
nothing will happen if i do it, right??
Youβll get a cease and desist order
holy shit im blind
we won't help with it
Probably get terminated
Hey guys so if I have message intents but my bot doesn't have slash commands. It would still work after April right?
It's still using discord.py
yes, of course
but you have to apply for message intents once your bot gets verified
My message intents got approved
My bot was verified since like January of previous year
nice I guess
I've been so stuck with work, i don't have the time nor the patience to update my bot to new slash commands.
Slash commands is a huge pain
I tried them out. Would take like an hour to register a command? Like bruh
When doing bot updates it takes around an hour for slash commands to sync so It takes forever to do bug tests
Ik
I'll update once i have time. I cant be arsed with it. Ugh.
and it won't be available on other guilds
which makes it possible to have a test server
really cool
guilds = [] ?
Yk what's cool doe? Not bringing unnecessary changes to something that works perfectly fine
well, you can set a guild for a command and add it to your tree
actually, I did forget it since I've only done this once
but our guy won't update for a time so I can check later
I don't know if users even like slash commands but that's just me
they did it to spare their API's use
Eh. I'm happy i got message intents lol.
They made me write a privacy policy
That I'm not storing any data

π π π
I'll show lmfao wait
Bounty Store Bot - Privacy Policy The Bounty Store Bot https://discord.com/invite/FJHsW2aAFk does not either Track, Save or Record any messages. There is no need for opt-out policy, because nothing is being stored or saved anywhere when you use the bot. Thank you. kraknn7#7263
Better to write a Google doc than rewrite the whole bot
not much
Exactly. It isn't much, but after i sent this, my message intents got approved
heres my error
Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\youse\Downloads\FlyAscent\DiscordBots\FlyAscent\Embed bot\main.py", line 221, in images
damsg = await channel.send(embed=embed)
AttributeError: 'str' object has no attribute 'send'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\youse\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\youse\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'send'```
channel is a string
type hint channel to a discord text channel like so -> channel: discord.TextChannel
nah i wanna so like u do .images <channel
as said.
ok one sec
and no need for the parenthesis in the color kwarg
this?
I wanna use pillow to make a caption command but it doesnt do anything
looks like you should have gotten a MissingRequiredArgument error in your terminal
since you only typed "test" which dpy would parse as the argument for file but leaves nothing for your text parameter
and how can i make it so it basically detects the image?
you should check ctx.message.attachments to see if the list isnt empty
but first, did any error show up in your console
Nope
then the command message was either not seen by your bot or a command error handler ate it
do any other commands in your cog work?
I dont have any other commands in there but i can try adding one real quick
yea, other commands work in there
hm, do you use any on_command_error handlers?
not in that cog
is the outside handler attached to your bot (i.e. a global event handler) or just a cog/command-specific handler
one for the cooldown and one if a command doesnt exist
can you paste the code
The caption code or the handler?
handler
basically if you have a @bot.event for on_command_error, you have to manually print out any errors you see
#If command not found
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.errors.CommandNotFound):
embed = discord.Embed(title=" An error has occurred!", description="**Expection: Not Found: 404**\n The command does not exist.", colour=0x992d22)
embed.set_footer(text=f"Use {get_prefix}help.", icon_url=f"{bot.user.avatar_url}")
await ctx.send(embed=embed)
#If cooldown
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
embed = discord.Embed(title="", description=f"{round(error.retry_after, 2)} seconds left", colour=0x992d22)
await ctx.send(embed=embed)```
oh you literally do have two on_command_errors
- with
@bot.eventit can only store one function at a time, so only the last function is registered - you dont print/re-raise the error afterwards so you cant see when command errors happen
what you can do is combine those two handlers into one and tack on a raise error at the end so it shows up in the terminal
basically like this?
I donβt think you can pass in ctx in an event.
on_command_error does take (ctx, error) as its parameters
close, but you only want raise error to run if the error was neither of those exceptions
like this?
almost right, use elif in the middle
otherwise the raise error runs even if it was an CommandNotFound error
afterwards you can run your command again and see any errors you stumble into
and then come back to this, because you'll need to download the attachment before you can open it with pillow
Message.attachments is only a list, you need to index the first Attachment object in that list and then download it to a file using its save() method
!d discord.Attachment.save
await save(fp, *, seek_begin=True, use_cached=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Saves this attachment into a file-like object.
also for both that and the img.save() line at the end, python has a io.BytesIO class you can use to read/write to in-memory files rather than saving them to your actual hard drive
oh actually, Attachment.read() would be more convenient when storing the image in a BytesIO object for pillow
import io
...
# get the attachment from the user's message
# (this list could be empty)
attachment = ctx.message.attachments[0]
# download the image and store it in-memory
image_bytes = await attachment.read()
input_file = io.BytesIO(input_file)
# pass it to pillow and do your image processing
img = Image.open(input_file)```
Suggest a good tutorial to start making discord bots π
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
isn't discord.py discontinued
no
it's not being developed anymore
its development has been resumed
hmm
Discord.py was discontinued on 8th August 2021 (you can see why, on this gist: https://gist.github.com/Rapptz/4a2f62751b9600a31a0d3c78100287f1). But gladly, it was back on 6th May 2022 (for more information see this gist: https://gist.github.com/Rapptz/c4324f17a80c94776832430007ad40e6).
The main reason the development was stopped was that Discord announced that all of the verified bots had to migrate to slash commands. This needed a huge rewrite and rework to the library which is not worth of time and effort.
The main reason the development was continued was that Discord again announced that it would decommission API versions 6 and 7 on May 1st, 2022. This will break all of the bots that use v1.7.3 as it is using API version 7. In order to save the ecosystem, it made sense for Danny (The creator of Discord.py) to come back.
Ignoring exception in on_guild_remove
Traceback (most recent call last):
File "C:\Users\****\PycharmProjects\ALL1\venv\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\***\PycharmProjects\ALL1\main.py", line 96, in on_guild_remove
prefixes(str(guild.id))
TypeError: 'dict' object is not callable
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\***\PycharmProjects\ALL1\venv\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\***\PycharmProjects\ALL1\venv\lib\site-packages\discord\ext\commands\bot.py", line 979, in on_message
await self.process_commands(message)
File "C:\Users\***\PycharmProjects\ALL1\venv\lib\site-packages\discord\ext\commands\bot.py", line 975, in process_commands
ctx = await self.get_context(message)
File "C:\Users\***\PycharmProjects\ALL1\venv\lib\site-packages\discord\ext\commands\bot.py", line 886, in get_context
prefix = await self.get_prefix(message)
File "C:\Users\***\PycharmProjects\ALL1\venv\lib\site-packages\discord\ext\commands\bot.py", line 831, in get_prefix
ret = await discord.utils.maybe_coroutine(prefix, self, message)
File "C:\Users\***\PycharmProjects\ALL1\venv\lib\site-packages\discord\utils.py", line 341, in maybe_coroutine
value = f(*args, **kwargs)
File "C:\Users\***\PycharmProjects\ALL1\main.py", line 61, in get_prefix
return prefixes[str(message.guild.id)]
KeyError: '885790789370789938'
Can anyone help me solve this error?
The guild ID isn't in the dictionary
You are currently calling prefixes which is a dict object. It is not a callable. The correct way to index a string is by doing: dict["key"] or dict.get("key") to prevent KeyErrors.
Donβt use json for storing prefixes and IO operations here are blocking
Is there anywhere I can find a list of discord rate limit times? Like x per second, y per minute, etc.?
They aren't documented because they are dynamic and may change at any time.
By chance has anyone made one anyways?
they can still parse the header of ratelimits
Yep, you could parse the X-RateLimit-Limit and X-RateLimit-Reset-After from a request header (You probably need to modify the source code though, but a print statement would be enough).
yeah nukers probably do that with there own wrappers
its kinda dumb not to document ratelimits per endpoint if your still gonna send the header
its like not giving the answers before the exam but then giving it on the exam its just pointless like if there was a different outcome of giving the answers first
How would you know π€¨
how else would they
idk
exactly
Mostly just not documented because they are dynamic
If it were undocumented to prevent endpoint abuse, then they wouldn't even show it in the response header
why not say the base limit?
in its base case i.e it would be 1/5
Because the base limit can change without further notice from discord
can it?
There is no "base" ratelimit, because there are many different endpoints
ment for each endpoint
How would there be a base ratelimit if the ratelimits are dynanmic
"Because rate limits depend on a variety of factors and are subject to change, rate limits should not be hard coded into your app. Instead, your app should parse response headers to prevent hitting the limit, and to respond accordingly in case you do." (https://discord.com/developers/docs/topics/rate-limits)
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
well i thought ratelimits were dynamic per request
They are dynanmic in the sense that they can change
Imagine a static IP address vs a dynanmic IP address
yes and i thought it was only per request and not time frame
One can change, while the other cannot, it's static
this is what i ment bro
calm down jeez i know what dynamic means
Well, yes per request they will be dynanmic, this is due to how buckets work
Thanks for the information. I got this from a dev too to confirm it:
Individual rate limits are generally not documented on our API docs, and that is for good reason: they can change at any time. We make no guarantees that rate limits will remain the same, and they may end up being variable per application at some point in the future.
Your wrapper will be hashing for the buckets, and they will have their own different ratelimits
yeah
I get this error whenever I try and run my program
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\KingPower\OneDrive\Desktop\Python Projects\discordpybot\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:/Users/KingPower/Desktop/discordpybot/main.py", line 16, in on_ready
user.send(":white_check_mark: Elim Bot has been started up!")
AttributeError: 'NoneType' object has no attribute 'send'
That's because the bot didn't find any user with that ID
I copied my ID tho
It needs to be awaited.
await client.fetch_user
try getting the user in your on_ready instead
ok
you should not.
Right, forgot one shouldn't do things in on_ready, sorry π
I am trying to make a bot that sends a message to console at a specific time but I can't seem to get it to work. Nothing happened when it hit the specified time
make a task
i forgot the dir
show code
it seems like self isnt being accessed so you dont need the argument and did you ran your bot
yes
does anyone know how i can make a bot run a command when a webhook thing is sent
well im not quite sure, im not quite familiar with tasks
Have you started the task? It won't run unless you start it. If you haven't, it's simple: task_function.start(), so in your case it would be printer.start().
yep. thanks!
For some reason my printer seems to not be working. This is my code
How can i add a code to send what my bot does to a webhook
oh idk how to do that in python
i know how to do it in java tho
lemme check my java code
π
We do Python here
ik bro
but I, myself, is curious and want to look at my java code
Cause they will never be equal, you formatted %H:%M but didn't include it in the comparison string.
Ok
I removed that part now but it still is broken
This website may help: https://python.plainenglish.io/send-an-embed-with-a-discord-bot-in-python-61d34c711046
If you have only the print() statement on the loop, does it print?
If you mean without the if statement yes
got it
do you know how to have a bot keep retrying?
retrying what?
from discord.utils import get
from discord.ext import commands
bot = commands.Bot(command_prefix="h!", intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f'Logged into {bot.user}')
@bot.command(aliases=['presence'])
@commands.has_permissions(administrator=True)
async def status(ctx, status_type: str, *, msg):
if ctx.author == bot.user:
return
await ctx.message.delete()
if status_type.lower() == 'p' or status_type.lower() == 'playing':
await bot.change_presence(activity=discord.Game(name=msg))
embed = discord.Embed(title='Status changed!', colour=discord.Colour.orange())
embed.add_field(name=f'Status is now "Playing {msg}"!', value='Enjoy the beautiful new status!', inline=False)
await ctx.send(embed=embed)
elif status_type.lower() == 'l' or status_type.lower() == 'listening':
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=msg))
embed = discord.Embed(title='Status changed!', colour=discord.Colour.orange())
embed.add_field(name=f'Status is now "Listening to {msg}"!', value='Enjoy the beautiful new status!',
inline=False)
await ctx.send(embed=embed)
elif status_type.lower() == 'w' or status_type.lower() == 'watching':
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=msg))
embed = discord.Embed(title='Status changed!', colour=discord.Colour.orange())
embed.add_field(name=f'Status is now "Watching {msg}"!', value='Enjoy the beautiful new status!', inline=False)
await ctx.send(embed=embed)
@bot.command()
@commands.has_permissions(administrator=True)
async def statusrole(ctx, role: int, *, checkstring: str):
removeCount = 0
if get(ctx.guild.roles, id=role):
roleObj = get(ctx.guild.roles, id=role)
else:
await ctx.send(f":x: I couldn't find a role with id `{role}`")
return
await ctx.send(":mag: Please wait. This might take a bit")
status_members = []
for member in ctx.guild.members:
for s in member.activities:
if isinstance(s, discord.CustomActivity) and checkstring in str(s):
status_members.append(member)
elif roleObj in member.roles:
await member.remove_roles(roleObj)
removeCount += 1
if len(status_members) == 0:
await ctx.send(f":x: I couldn't find anybody with \"{checkstring}\" in their status")
if removeCount > 0:
await ctx.send(f":white_check_mark: I removed role with id `{roleObj.id}` from {removeCount} members")
return
for member in status_members:
await member.add_roles(roleObj)
await ctx.send(f":white_check_mark: Thanks for Added role with id `{roleObj.id}` to {str(len(status_members))} member(s)")
if removeCount > 0:
await ctx.send(f":shield: I removed role with id `{roleObj.id}` from {removeCount} members")
bot.run("")```
the bot searches for statuses and adds/removes a role
Then what part did you remove?
but the its at the point where they have to do the command manually
for the bot to add it/remove, i want the bot to retry and search on its own
I got rid of the hour time portion
make a loop?
im not sure
yes
loop so itll keep searching after a certain amount of time
but idk where to add the loop at
Actually, there might be an on_reaction event
reaction?
Okay, looking at https://strftime.org/, %M means "Minute as a zero-padded decimal number.". I'm guessing that you mean month, then its %m.
I thought you were searching for a reaction?
OH
@commands.has_permissions(administrator=True)
async def statusrole(ctx, role: int, *, checkstring: str):
removeCount = 0
if get(ctx.guild.roles, id=role):
roleObj = get(ctx.guild.roles, id=role)
else:
await ctx.send(f":x: I couldn't find a role with id `{role}`")
return
await ctx.send(":mag: Please wait. This might take a bit")
status_members = []
for member in ctx.guild.members:
for s in member.activities:
if isinstance(s, discord.CustomActivity) and checkstring in str(s):
status_members.append(member)
elif roleObj in member.roles:
await member.remove_roles(roleObj)
removeCount += 1
if len(status_members) == 0:
await ctx.send(f":x: I couldn't find anybody with \"{checkstring}\" in their status")
if removeCount > 0:
await ctx.send(f":white_check_mark: I removed role with id `{roleObj.id}` from {removeCount} members")
return
for member in status_members:
await member.add_roles(roleObj)
await ctx.send(f":white_check_mark: Thanks for Added role with id `{roleObj.id}` to {str(len(status_members))} member(s)")
if removeCount > 0:
await ctx.send(f":shield: I removed role with id `{roleObj.id}` from {removeCount} members")```
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change:
β’ nickname
β’ roles
β’ pending...
i want it to search'=
discord.on_user_update(before, after)```
Called when a [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") updates their profile.
This is called when one or more of the following things change:
β’ avatar
β’ username
β’ discriminator...
yeah that was the issue lol. thank you
!d discord.on_presence_update
discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their presence.
This is called when one or more of the following things change:
β’ status
β’ activity
This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.presences "discord.Intents.presences") and [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled...
The actual right one
Do you use discord.py 2.0?
peep code
@commands.has_permissions(administrator=True)
async def statusrole(ctx, role: int, *, checkstring: str):
removeCount = 0
if get(ctx.guild.roles, id=role):
roleObj = get(ctx.guild.roles, id=role)
else:
await ctx.send(f":x: I couldn't find a role with id `{role}`")
return
await ctx.send(":mag: Please wait. This might take a bit")
status_members = []
for member in ctx.guild.members:
for s in member.activities:
if isinstance(s, discord.CustomActivity) and checkstring in str(s):
status_members.append(member)
elif roleObj in member.roles:
await member.remove_roles(roleObj)
removeCount += 1
if len(status_members) == 0:
await ctx.send(f":x: I couldn't find anybody with \"{checkstring}\" in their status")
if removeCount > 0:
await ctx.send(f":white_check_mark: I removed role with id `{roleObj.id}` from {removeCount} members")
return
for member in status_members:
await member.add_roles(roleObj)
await ctx.send(f":white_check_mark: Thanks for Added role with id `{roleObj.id}` to {str(len(status_members))} member(s)")
if removeCount > 0:
await ctx.send(f":shield: I removed role with id `{roleObj.id}` from {removeCount} members")```
where would it go
It's a event
yuh yuh
Do you use discord.py 2.0
yea
Okay
It's a event so it wouldn't go in your command
ok
Ok
Cause what
Intents?
i have one in js that checks statuses on its own normally
Yeah
but in my py 1, the user gotta do the command in order for the bot to check statuses
This isn't js
ik
This is what on_presence_update does
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
async def on_ready():
await b.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="Custom Status"))
print("Bot Ready")
async def threading():
total_seconds_wait=5
fg=0
while total_seconds_wait:
guil = b.get_guild()
memberList = guil.members
for user in memberList :
fla=0
for s in user.activities:
fla=1
if isinstance(s, discord.CustomActivity) :
if str(s).find('gg/') !=-1 :
r = user.guild.get_role()
if r in user.roles :
continue
else : ```
for example this one right here checks statuses and gives/removes role
Robin help
why is the code shaped like a line with negative slope
negative linear association π
anyway
the first thing, don't change presence on_ready
Yes why are you giving us examples
because that code keeps searching for statuses
my current one doesnt
im trying to add something like that 1^ in
I already told you what event to use
idk where to put it
async def on_ready():
print(f'Logged into {bot.user}')```
put it there?
do i add the before,after
or just the on presence update
Can anyone help? I don't get what's wrong
await ctx.send(embed = embed, view = TTT_GameView(ctx, self.bot, (ctx.author, ctx.author), ctx.author))
class TTT_GameView(discord.ui.View):
def __init__(self, ctx, bot, players: List[discord.Member], current: discord.Member):
self.ctx = ctx
self.bot = bot
self.players = players
self.current = current
That causes this
Ignoring exception in command ttt:
Traceback (most recent call last):
File "C:\Users\ryano\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 191, in wrapped
ret = await coro(*args, **kwargs)
File "r:\VSCode-Projects\Discord-Bots\BiscuitBot\cogs\TicTacToe.py", line 21, in ttt
await ctx.send(embed=embed, view = TTT_GameView(ctx, self.bot, (ctx.author, ctx.author), ctx.author))
File "C:\Users\ryano\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\context.py", line 692, in send
return await super().send(
File "C:\Users\ryano\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\abc.py", line 1487, in send
with handle_message_parameters(
File "C:\Users\ryano\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\http.py", line 183, in handle_message_parameters
payload['components'] = view.to_components()
File "C:\Users\ryano\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 216, in to_components
children = sorted(self._children, key=key)
AttributeError: 'TTT_GameView' object has no attribute '_children'
Does anyone know why? Any help is appreciated :)
add super().__init__() into the class's init method
Ohh right, I forgot about that. Thanks!
No
Make on_presence_update in it's on event
ok ok
Why do you keep showing me i know what it does
my fault slim
how would i get this to find the channel name of the new made ticket and send "ticket opened"
@bot.command()
async def ticket(ctx):
guild = ctx.guild
channel = discord.utils.get(ctx.guild.channels, name=f'{ctx.author}')
role = discord.utils.get(guild.roles, name="Ticket Banned")
if role in ctx.author.roles:
await ctx.send("you cannot make tickets!")
return
await guild.create_text_channel(f'{ctx.author}')
await ctx.send("ticket made!")
await channel.send('ticket opened!')
Why are you using ctx.guild in your channel variable when you defined guild as ctx.guild
Where are you storing the data for the tickets? π
hi guys im getting an issue with discord not communicating with my bot, i have it coded so that i should recieve messages in the discord in my terminal as a test but i dont get that
any ideas where i might have gone wrong
Code please?
how do i post in a nice fancy box like above
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
@client.event
async def on_ready():
print('we are logged in')
client.run('mytoken')
@client.event
async def on_message(message):
print(message.content)
print(dir(message))```
i have imported discord
Hmm
Your on message should be above your client.run() as client.run() is blocking
You're running above the on_message
Yeah
Client.run must be below everything
Your client.run should be closing your script
omg am so dumb thanks guys im v new
yuss it worked, thank you so much
sorry for the stupid questionπ
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
I make dumb mistakes too it is fine π
i might be dumb but... i want to check if the string high is larger or equals 3 while low is range 1-3 and H is 4-6
Im a bloody beginner.
#dice_final = 3
high = (3, 4, 5)
low = (1, 2, 3)
if high == dice_final:
#DO STUFF
if high < dice_final:
#DO STUFF
elif high > dice_final:
#DO STUFF
Basically i need to declare that high is an integer from 1 till 3.. but.. how? Sorry for that stupid question.
!paste @slate swan
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
This isn't discord bots related
its for a discord bot.. so i thought it is.
Also use =>
high low game. π Sorry.
The code isn't though
You are making a basic game, so try #game-development ig.
=> is equal or larger than
i have another more complex question, i want to have an input('what would you like to search? ') command that can be input through discord with an !ebay command so for example !ebay television. im not even sure what to google to find the answer of what i should put
Alright, thanks.
You would need to redo some of your code.
Currently your code would only run events.
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
oh yeah the code i have already done was just a test to get the bot logged in and working
ooh
Oh you mean an argument
You need to do
Saw input so thought you were trying to wait for a user's input
yes so if they type !ebay that activates the bot and searches ebay for television and then sends the url to discord
client = commands.Bot(command_prefix = "!")
Use commands.Bot
Bad naming convention
That is what I usually do π
Change
to what?
Bot
Okay
oh man this is confusing afπ
since commands.Bot subclasses discord.Client it inherits all of it's methods and attributes
You can do client or bot
They both do the same thing
discord.utils.get
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'get' is not defined
Code:
check_role = get(ctx.message.server.roles, name='Rich Student')
ok so i have done bot
Yes but one is bad naming convention
Good choice
so now ! is a command prompt for my bot?
It's the prefix, yes
You can change it to whatever you want, I just used it as a example.
@client.event
async def on_command('!ebay'):
But bot is generally recommended because it's descriptive of what it is
check_role = discord.utils.get(ctx.message.server.roles, name='Rich Student')
AttributeError: 'Message' object has no attribute 'server'
does that look ok
No
im shooting in the dark ngl
Server is guild
followed some video for a completely diff bot
You need to do a command
Also jist use ctx.guild.roles
Yes
You're probably looking at outdated code
@client.command()
async def ebay(ctx):
await ctx.send("This is Ebay.")
@grave summit
That is a basic command
Spoonfeed
It's my code from a year back
π
I just realized that π€¦ββοΈ
Yeah they have changed
Been focusing on discordgo and I wanted to try something in py
amazing thank you
Anytime π
Wouldn't work since hazbob said he uses bot
what does the (ctx) in brackets mean
Context
ah
That is the parameter
Context
The parameter(s) is *args and **kwargs
The context is inside the parameter
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'member' is not defined
They updated member too?
You should just start over
You'd have to remake everything in your code
I will I just need this running before I do
Whats member now?
Just start fresh
Member
@slate swan exactly what is your code
just creates a channel in a category if they have certain role
once i have !ebay setup, how do i add whatever comes after that as an input
Add a argument in the parameter
You want something to print in the console as well?
ok ill google how to do that now, thank you
nah idc about console, i just want a message sent with a url
(ctx, item):
...
oh thank you saved me the google haha
Now item is an argument
Also you have an on_message event in your code Hazbob
Member is still not defined, would it be discord.Member?
Which will need to be filled or it will raised an error
I would recommend adding a line to that so the command will register
I actually need your code
how do i fill an argument
I don't know what it looks like
ah sorry i dont really know what im on aboutπ
Now the user has to do !ebay ps5
check dms
