#discord-bots
1 messages ¡ Page 707 of 1
It should be inside the init function
makes sense
They are fields
don't tell me someone codefeeded you for that avatar command
!d discord.Embed.add_field
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining.
đś i understand i need examples but i need a basic concept of implementation
Is there some listener that listens for replies to a certain message?
if you're looking for an event which replies to a message if it's something, on_message is probably that
Couldn't find anything in the docs
also , you should not edit your discord client with apps like better discord / bandaged discord
It's against discord TOS
wait i misread it
Just check if The message has message.reference
!d discord.Message.reference
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
It's none if it's not a replied message or channel integration
You may use it in normal on_message events
something i learned today: bot events are just complicated things easened for you
not applicable to all events tho
Yeah , if you would be doing it thru the raw data you get from the discord Gateway connection , it would be very hard
That's what a wrapper is meant for
so it wrapped my present for christmas?
how can I do client.latency in a cog cause there is no client
What do you have bot defined as in your cog?
ctx.bot.latency
You could do that 
alr thanks
So I should create an on_message event, and then check message.reference for every message?
another way to do that is defining the .bot for your cog class inside the `init function
Yeah you can just check if the message has a message.reference and it's not a channel integration ( the follow channels stuff ) message
If the condition satisfies , move on to next step
Else you can return
guys how to do like bot waiting for user's answer an than use it?
You may use wait_for
Inside a command right?
!d discord.ext.commands.Bot.wait_for , use "message" as the event position arg
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.9)"). 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.9)") 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.9)") 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**...
Whatâs wrong
Also what is that
Itâs missing kwargs
Itâs missing a lot of stuff
Is there a way to add a listener to a command group?
res = await client.wait_for("message", timeout=15, check=whatever)
# do stuff
check @upbeat otter
what i should write instead of ctx if im writing this inside on_voice_state_update
and it doesn't accept ctx
what does the word âkwargsâ suppose to mean
when im passing ctx into on_voice_state_update it writes me an error
How can I then change the user limit differently?
Could anyone help me here?
a kwarg is a keyword argument and since its plural it would be kwargs
!d disnake.Member.timeout
await timeout(*, duration=..., until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Times out the member from the guild; until then, the member will not be able to interact with the guild.
Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.
You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.
New in version 2.3.
theirs 3 kwargs in the coro
help me please i want to get input from user but i dont know how because its not possible to pass ctx inside on_voice_state_update
dang
can i use something different instead of ctx.author and ctx.channel?
i tried
And?
and nothing
And nothing.
u dont need ctx u have before and after?
yes i have before and after
Put ctx in and see what it does
on_voice_state_update does not accept ctx
that what it writes me when i put ctx inside
the event doesnt take ctx
how would you check against ctx.author when that means like command author
And that as well
and thats an event lol
ctx = Context
Do you want to see if the member before is the same as "New" (after)
@bot.command()
async def command(ctx: commands.Context):
await ctx.send("message")
makes sense
dont know if its type hinted well tho
I think that's the way, usually the Context is imported to avoid commands.
yeah since ctx is a positional argument
user writes a number, than bot sets an user limit in voice channel that typed user
before and after are member objects
@bot.command()
async def command(smt: commands.Context) -> None:
await smt.send("message")â
in this case ctx is smt since its a positional arg it doesnt matter its arg naming but yes its bad practice
As in English if member before == member after: #do smth do you want to do smh like this
isnt weird how dpy converts something to a obj with a typehint
maybe i did something wrong i dont know, i got this code from the internet
I didn't even think about that
but my idea was to get input from user and then use it to set a voice limit
kayle was talking about it and to me its very unpythonic since type hints is just a hint
imo that is quite useful
yeah weird how it converts it to an obj
pretty cool at the same time
!e
def foo(name: str) -> None:
print(f"hello {name}")
foo(1)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
hello 1
i type hinted it to a str but gave a int
probably a bad arg error
Dang that is very useful, I mean I have used it as like that but never thought about it
(nonetype: discord.Member)
this would make it a member obj which is kinda unpythonic but very cool
Everything is making sense now
pretty cool right
thank you !
If you want it to send something
Yep
And you canât use ctx
Now I can use that feature even more effectively
member.guild.system_channel.send() use this
yep
Okimii being smort 
*.*kwargs is a dictionary of arguments passed, for example
def test(**kwargs):
# **kwargs is a dictionary
print(kwargs)
test(arg1 = "Hello")
# Result will be { "arg1": "Hello" }
Maybe I could make a custom object for discord.member or discord.user
what i need to write instead of this? @velvet tinsel
not really something i learned from kayle very cool
it highlited the syntax bruh
this is mostly used for unknown arguments that the user can pass
Thx for telling me about that!
and
*arg
would make it a tuple
anytime
*arg also takes unlimited arguments
member = guild.get_user(<user-id>) @proven osprey
Improve your Googling skills 
like
def test(*args):
print(args)
test("arg1", "arg2", "arg3")
# Result will be (arg1, arg2, arg3)
i gtg rn cya guys
Cool
yep
!e
def test(*args):
print(args)
test("arg1", "arg2", "arg3")
# Result will be (arg1, arg2, arg3)
@velvet tinsel :white_check_mark: Your eval job has completed with return code 0.
('arg1', 'arg2', 'arg3')
Yep đ
results would be a tuple lol
I encountered that lol
a tuple
lol
since it eats all the text
am i stupid but i don't understand the place where i should write this @velvet tinsel
Use listen()
@slate swan
I also posted it
Be sure to mark my answer as correct
đł
- your using client and importing commands?wut
2.put your on ready event on top
3.its message.reply
Mark my answer as correct as well
yep and takes keys as well
wouldn't work
Yeah and message.reply
!e ```py
def test(**args):
print(args)
test(arg1 = "arg1", arg2 = "arg2", arg3 = "arg3")
@proven ore :white_check_mark: Your eval job has completed with return code 0.
{'arg1': 'arg1', 'arg2': 'arg2', 'arg3': 'arg3'}
đ
and this is kwargs
a dict
Ah returns a dict
??
lol
Heâs trying to get my attention
ye
4.use the bot framework for commands ffs
this is true...)
I sent you the solution
what
The id
He canât pass ctx
He asked that ages ago
And client.listen()
@slate swan read this :))
Lolll
no nitro moment
:kek:
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
If youâre super beginner why you doing discord py
user types a number and than bot sets an user limit in voice channel but i can't get input from user because i can't pass ctx inside on_voice_state_update
your the same level as him 
Bro
You didnât even know the bot can reply to itself
đ´ď¸
Be prepared to encounter lots of errors
If you donât know simple python
on commands it cant but on events yes learn the difference 
i know where you live
Hold up
Where are you
I want some company
dpy uses asynchronous programming and oop
!ot
Off-topic channel: #ot2-never-nesterâs-nightmare
Please read our off-topic etiquette before participating in conversations.

As someone who just learned to code in python a few weeks ago, I've been looking for projects that i could do. I've narrowed down my choices to making a webpage and or discord bot. What route would be the best?
if you want to i would recommend to learn pythons syntax yes,but if you want to learn dpy go for it,it will be hard but do whatever your heart desires 
Did you finish all the fundamentals
Like lists, dictionaries, functions, async, OOP, and classes?
maybe webpage since you cant make a career out of discord bots
I made a career out of discord bots
better like:
types
functions
loops
classes
the way its written in
Okimii
Do you know of a good place where i can begin coding a webpage? Sorry im asking alot of questions, i'm pretty new to this stuff
each language has their on syntax but can do the same thing like spanish and english
HTML, CSS is probably what you want
Python is mainly for backend
So is JavaScript
Was gonna say that
correct

alright
Cool
14
Bro I thought you were in high school
good luck tho
Maybe England has different ways of teaching
about to be 15 in a month
đ¤
prob
Happy birthday
wait for January 24
Iâm gonna send you a gift đł


Where do you live
ikr
im your neighbor?
Iâm gonna buy you that big pink fluffy unicorn toy
Use after.author?
U do not need ctx if you have after and before parameters
You mean the sussy guy that walked down the street for a coke?
yes thats me
Off-topic channel: #ot2-never-nesterâs-nightmare
Please read our off-topic etiquette before participating in conversations.
@bot.command()
async def say(ctx, *,message):
await ctx.send(message)
await ctx.message.delete()
why it doesn't delete the message?
message.delete()
whats the kwarg in your params for
ctx*
And also whatâs the- oh you said it
your wrong lol
message should be ctx.message.id btw
wdym
message.delete is for an event
Huh?
message=None this
I corrected myself message is a var that contains the message ID
you need context to delete the msg
Why is that even there
an kwarg
the var contains the message ID
nvm i just removed it
No
ohhh
ctx.message.delete
wtf is that
Whatâs that even doing there
A stack overflow answer from 1969
Yeah maybe message=None is causing the error

await ctx.message.send()
the coro deletes the command
Cute little snek
@bot.command()
async def say(ctx, *,msg):
await ctx.send(msg)
await ctx.message.delete()
nothing changed
delete the msg before you send it
that makes it a unknown amount of arguments
*, this makes every following arg a kwarg
know your stuff mr
How very interesting
*I know my stuff
how didnt you know about that
yeah surely
@bot.command()
async def say(ctx, *,msg):
await ctx.message.delete()
await ctx.send(msg)
now it doesn't send message and the message doesn't get deleted
Can I sleep
Cos you didnât wait
You sent it then immediately deleted it
Of course nothings gonna happen lol
Use asyncio.sleep()
!d asyncio.sleep
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [Whatâs New in 3.10âs Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.
Example of coroutine displaying the current date every second for 5 seconds:
Ah tylerr
How did you use the command
?
Hello
try this
@bot.command
async def say(ctx,*,rep=None):
await ctx.message.delete()
await ctx.send(rep)
no need for the default value
Did you just do
[p]say or did you actually put a message behind it
Why did you delete it first
he wanted to
He wanted to say it first lol
it deletes the command
Thereâs a reason why itâs called âsayâ
no difference
Exactly
no difference too
Betting he did what I said. It probably rose a commands.MissingArguments or something
Sorry đ
it deletes the command not its msg smh
probably
Answer my question
A
wdym deletes the command
How did you use the command.
B
The invocation message
Whatâs ur command
gave arguements
Question*
Show us
basic stuff
?say a
ctx.message.delete()
And?
And that didnât work.
Youâre 10 steps behind
nothing happens after that
Which
Because you sent it and deleted it
dude why are you trying to help me
Uhhh then whatâs wrong now
I donât need your help.
At the same time donât you see
Itâs not working apparently
you guys need to scroll up ngl
@bot.command()
async def say(ctx,*,rep=None):
await ctx.message.delete() #doesn't do anything
await ctx.send(rep) #works but not when it's 2nd like now
Then the problem from him?
This works properly
O
? Whatâs that
Why did you delete the message first
Explaining wts wrong ig
Funny how I still dk whoâs asking lol
Itâs Korn
Oh
Who did you think was asking
Trying doing ctx: commands.Context
naw
@bot.command()
async def say(ctx,*,rep=None):
await ctx.send(rep)
await ctx.message.delete()
no need
Type hinting doesnât effect run time in this case
@sage otter XDDDD
WHAT
What if
SERIOUSLY
Ik no need but what if
its a positional arg ffs
Yes Ik but what if
@bot.command()
async def say(ctx,*,rep=None):
await ctx.message.delete()
await ctx.send(rep)
Just try
Iâm leaving. I already put in my 2 cents.
maybeâŚ.rep.delete()? Stupid idea lol
đś
đ´ď¸
Do ctx:commands.Context and try
your joking right?
your joking right?
No
Yeah maybe bot.delete()
đ¤
you guys should learn basic oop
bot.delete() would work
imma head out
Lol what
How the hell is this related to oop Lol
No
he wants to delete the message that invoked the command
attrs are related to oop and dpy uses oop
Try bot.delete_message(ctx.message)
But ctx.message.delete() isnât working?
Yes but there are no classes used here?
delete() is a coro not a class
yes their is?
@daring valley
And use bot.say()
yes but what are the attrs of the coro?
Corona đŚ
Too outdated lmao
thats been deprecated for years
Or use purge()
Ainât using the attrs rn, we are using functions
But thatâs too risky
Yeah try this
Ye
Those functions are actually methods of their respective classes, so yes you are using OOP
Sometimes the bot is slower
is there a function that returns the last command/event ran?
see basic oop
It can delete the message

afaik no lol
Ik but we are using the functions of the classes not the classes
But there is a way
Can you say that again outloud to yourself
whats the way đ
Bruh
You are quite literally using the class by using the methods of the class
For each command, append the name of the command to a list
im stupid but its basic oop
You do str.split not split(str)
Thatâs not true
Unless split is defined otherwise
:))
That would be functional programming
It is kinda doe
mhm ok thx đ
Ok guys letâs go back to the topic lmao
For example, @bot.command(): async def foo: ⌠list.append(foo)
osam7a| Ik but we are using the functions of the classes not the classes
đ¤Ş
Yes pls am looking dumb rn
đ¤
ANYWAYS
What discord.py is this
đ§âđŚŻ
âIdk, discord pyâ
https://www.programiz.com/python-programming/object-oriented-programming
here guys for you
In this tutorial, youâll learn about Object-Oriented Programming (OOP) in Python and its fundamental concept with the help of examples.
đ§âđŚŻđ§âđŚŻđ§âđŚŻ
đ
âItâs discord pyâ
âThen why did you ask which discord py it isâ
ââŚwellâ
I meant what version lol
Not programiz
you mean fork?
Then ask what version
No what version
you sure
Uhh yeah?
alright 
OkayâŚ
OkayâŚ
đ§
just dont delete the msg tbh
https://pastebin.com/pzaJBUfS wat do u guys think abt this
Still working on it doe
^^^^^
FYI thatâs Okimiiâs way of saying âyouâre stupidâ
dont knownmuch about tk lol
I just realized imported requests from no reason
Bad format and off topic
O k
But that channel is dead as hell đŠ
Anyone has a cool template for web dashboard of a discord bot? (I wanna use it with flask)
^^^^^^^^^Âż
Yeah
Your pfp with a tag that says ayo look itâs my bot
Looks like something to me ;)
Wdym
Take a screenshot of your pfp
And then put a text that says âayo itâs my botâ
And use it as banner
me not sorry
No fr dyk any templates breh
hi anynone has a cool avatar and nickname for a but cuz i think of channging pfp of my bot and nickaname
what is it about?
i dont know i just need cool pfp and nickname for my but i losing ideas
whats your bot about
cant quite say since maybe the name and pfp do not relate to the bot
but fisrtly i dont thing of this to be releate to the bot
good luck, last time I tried to change the name and the pfp it was a nightmare
your joking right?
no
its the easiest thing
it wont work through dev portal
just run the bot after you update its name and boom done
secondly u need to think of good cool name
it doesnt work like that
change it to 6969
no 
yeah but
it's your opinion ig lol
yeah ig
my bot gots this nickname and pfp but i dont have any ideas to change nickname and pfp
Mr.support
mabe
im a beginner and im doing discord py whats wrong with it? đ
show the code and error if their is
there is none
code?
i meant whats wrong with being a beginner
ah my fault
i only have 148 lines for my bot rn but idk what commands to add i have basic ones and kick ban unban mute etc
well nothing to be exact everyone starts as a beginner
You havenât learnt basic python yet
i just do have one question how do i hid my token? so client.run(TOKEN)
is hidden
see
ah
a good command for someone thats starting is maybe using another api like the reddit api and use the api wrapper asyncpraw to make a search command that only gives images and the command should have a cooldown since your making requests
I tried making a music one where it plays and i made it so it can leave/join using !join but i couldnt figure out how to do it
i think since youtube is taking down usic bots its not possible
@slate swan if you want a challenge dont use tutorials and only use examples and docs and no copy pasting code 
ive only been using tutorials but no copy pasting so far đ
i like to type it it gives me a real experience
well i recommend to use docs and no tutorials that are probably outdated
kekw
heh
how to make command that counts messagas has user send
when samone types +user it shows stats of usaers messages
if i can do this in python
pls
Store in a database each user's messages count, and increment +1 each time a user sends a message.
but i dont know how to make that how to start even make it
but i dont know how to make the coomand and event it is needed
this
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your botâs own messages and private messages are sent through this event. This can lead cases of ârecursionâ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
@dapper cobalt do u know
!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.
something like that ```messageCount = {}
@client.event
async def on_message(ctx):
author = str(ctx.author)
if author in messageCount:
messageCount[author] += 1
else:
messageCount[author] = 1
await client.process_commands(ctx)```
its an event i know
Don't do if author in messageCount. It's
try:
messageCount[author]
except KeyError:
messageCount[author] = 1
return
ok
!d collections.Counter
class collections.Counter([iterable-or-mapping])```
A [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter "collections.Counter") is a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict") subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter "collections.Counter") class is similar to bags or multisets in other languages.
Elements are counted from an *iterable* or initialized from another *mapping* (or counter):
```py
>>> c = Counter() # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping
>>> c = Counter(cats=4, dogs=8) # a new counter from keyword args
I present
!d dict
class dict(**kwargs)``````py
class dict(mapping, **kwargs)``````py
class dict(iterable, **kwargs)```
Return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments.
Dictionaries can be created by several means:
⢠Use a comma-separated list of `key: value` pairs within braces: `{'jack': 4098, 'sjoerd': 4127}` or `{4098: 'jack', 4127: 'sjoerd'}`
⢠Use a dict comprehension: `{}`, `{x: x ** 2 for x in range(10)}`
⢠Use the type constructor: `dict()`, `dict([('foo', 100), ('bar', 200)])`, `dict(foo=100, bar=200)`
but why but its okay if need to use something alse
Bottom one
so rn i need to make command +user thats shows users sent messages in the discord server
Anyone know how to fix this it is prolly smth i am missing but idk
Are you trying to create new instance of ConnectFour or just run the innit function
but i dont know how to make that command
Because if you want to tun innit, you need an instance first, and when you create instance innit gets called
You need to count messages in on message event and store the count somewhere, then make a command that shows the count
Hb the command
but the command i dont know how to make
Just read data from the db and display it
Where do you store data
Itâ s faster to use if/else than to have an exception generated and then catch it
How did you determine that it's generally faster?
Keep in mind that if if is used, then the code is checking every time versus only raising an exception if it doesn't exist
But in this use case it would probably raise an exception quite often if you would do it with try/catch
Especially when he doesnât have any users stored
Idk, for this use case it just seems nicer to use if/else
Tho I get what u mean
Im tryin to pass through those variables so i put everything in the innit function
Im assuming that im not supposed to do that
If you want to create an instance just delete innit part
Wdym
But i cannot pass through the variables through that class
It doesnt let me and gibs me an error
i need to make some sort of file for that coomand or something (i usin hosting and in this hosting i making command and files for commands thats needs files)
Wdym
And i was told to pass them through the innit function
Send code
And the error
Use db
what is db
No, you gotta set a db up and connect to it
Google mongo, Itâ s simplest and u can have a free cluster in cloud
import nextcord, datetime, os
from datetime import datetime
from nextcord.ext import commands
def setup(bot):
print("Connect Four has loaded.")
class ConnectFour():
def __init__(self, bot, msg, game_num, player1name, player1id, player2name, player2id):
class ready_up_button(nextcord.ui.View):
def __init__(self):
super().__init__()
self.value = None
@nextcord.ui.button(label='Ready', style=nextcord.ButtonStyle.primary)
async def connect_four_button(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
self.value = 1
self.stop()
``` and so on
You can use mongo atlas
ConnectFour.__init__(bot, msg, game_num, user_name1, user_id1, user_name2, user_id2)```
but how i dont even know oabout mongo atlas
Do, connect_four = ConnectFour(args)
But args are in innit function
Wdym
You cant run innit if you dont have an instance
wait but how the data base must looks like for that command
What is happening here..??
Why did you put the whole class in the init?
Yes, ok, that is a constructor, now create a new instance of this class
They did what?
OHHHHH
I an idot
Did u put whole class inside constructor?
I pit everything in that
That is not how Itâ s done
Innit is basically a function that gets called when u create new instance
So u kinda need an instance to run it
And if you try to define class methods in there it wont work
You gotta flip those around
self.bot = bot
Basically, self is an instance of this class
Read this
but i dont wanna type out self.bot
U gotta
m vicuh q4jnkae.fmdzxck oiq eul;ar.jkdfcm,va0pa9w;iloukj.,dermgscv v9pui;khj.WSRDFXC;HJK.WSDFCGYHPBKSD NZXC
Bot isnt
oki then
Send ss of whole class
Hey @mellow gulch!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
⢠If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
⢠If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
class ConnectFour():
def __init__(self, bot, msg, game_num, player1name, player1id, player2name, player2id):
self.bot = bot
self.msg = msg
self.game_num = game_num
self.player1name = player1name
self.player1id = player1id
self.player2name = player2name
self.player2id = player2id
view = ready_up_button()
if self.game_num == 1:
channel1 = self.bot.multi11channel```
I shortened it
Why is the bottom code just floating inside the class?
You don't have access to self like that.
Right?
@mellow gulch I recommend watching this -> https://www.youtube.com/watch?v=ZDa-Z5JzLYM&list=PL-osiE80TeTsqhIuOqKhwlXsIBIdSeYtc
Yes, when you create new instance
!e
class abc:
def __init__(self, x):
if x == 3:
print(x)
abc(3)
``` like this @mellow gulch
@jade jolt :white_check_mark: Your eval job has completed with return code 0.
3
Ok thx
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
3
Well they are kinda different.
This is called before init
i like __call__
and that does..?
means you can call a class
show a quick example in #bot-commands ?
You enable instance to be called like a function
They are used so classes can behave like functions.
o
If you do instance(), it will execute whats inside __call__
__call__ can return values
doesnt seem like it has a practical use to me^
https://www.geeksforgeeks.org/__call__-in-python/amp/ here is an explanation on __call__
tyvm
!e ```py
class abc:
def init(self, x):
self.x = 3
def __call__(self):
print(self.x)
obj = abc(3)
obj()
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
3
is there a way to get your bot to play music ive tried so many times but cant find out?
There is a way but i don't want to tell you.
oh okay
No lol in all seriousness it violates the ToS
that does have a use now. ty
oh FR?
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeâs robots.txt file; (b) with YouTubeâs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
Yeah... well groovy and rythm died
Hb if u dont use ytdl
Well downloading/streaming still violates ToS.
I mean if you have the music locally
^ if its non copyright iirc
That probably isnt against tos
It isnât
how do i hide my token i tried doing it using .env but didnt work
Music bots arenât against discord tos. Itâs the means of how the music bots get their music.
Still violates it since download/streaming rule is against YouTube ToS it has nothing to do with copyright.
true
U install python-dotenv and use load_dotenv then get token with os.getenv
if you download from non copyright sounds themselves its fine
Fortunately YouTube has nothing today with local audio files 
Share?
wym "use" load_dotenv
like import load_dotenv
from dotenv import load_dotenv
From dotenv import load dotenv
speed
now do i wanna put that in .env or should i put it in my main bot folder with all the other import
And u do load_dotenv(path)
Oooo legend, ty
U put that in ur python file
yea i realized LOL
Python imports usually go into python files
In .env u only put TOKEN=gigegc77(5(74hjtdjydtt try h se
Or whatever u want
Seems legit
Ikr
I do recommend putting it in a string though.
U mean token=âtokenâ
?
@commands.command(alias="restrict") Why alias doesn't works ?
Wrong. It's an iterable object of string objects 
It's the object discord.ext.commands.Command.aliases that is called aliases it's a list of aliases the command can be invoked under. The type of the kwarg being a union of list and a tuple containing strings.
aliases accepts list or tuple only
Smh statically typed code be like
discord/ext/commands/core.py line 329
if not isinstance(self.aliases, (list, tuple)):```
oof
Statically typed code đ
It's fine because I like doing the same for every single function I make 
It would be quite easy to implement Iterable[str] here instead of only supporting list and tuple
hm...
kraots, greetings
Old code, which Danny didn't bother bettering much 
There is loads of old code.

nice anime
Yes
you got nitro
It's not anime... It's a game
:kek:
Old code, kek same reason why get_channel is O(n) instead of O(1)
O(n) means time is dependent on how many elements are in the sequence, O(1) means constant time no matter how many elements
get_channel can be O(1) since channel doesn't require to be accessed through a Guild
There should be no reason why get_channel should O(n)
Understood from the 2nd example more than from the 1st ngl
There's Bot.get_channel tho
Yes, that isn't O(1)
Oh
That's O(n), like I said
Then I still didn't understand it 
Don't understand what exactly? The O notation part?
This made me think that it can be O(1) because of Bot.get_channel since you said it doesn't require the guild object
It CAN be O(1), just that danny decided not to make it O(1)
I c 
Channels are accessed through the official API via channels/channel_id not guilds/guild_id/channels/channel_id
That's why you can just smack a global cache of channels
why not? It will improve the performance of the lib
And if you were to set a key in the dict via the channel's ID
You can use dict's getitem
Which is O(1)
The reason I seem to got was that it was old code
get_channel was the first get_ method from what danny said
I c 
You'd need to ask danny ÂŻ_(ă)_/ÂŻ

cache system is kinda bad but no one bothers to change it.
Don't even get me started on the message cache lmao
That shit is O(n) as well when it can be O(1)

One of the things to influence myself to make my own wrapper
My message cache is O(1) getitem
Will increase ram by some amount.
Depends on the max amount
It's acts like a deque but it's also a dict
So it will never go over a certain amount of ram usage
Do keep in mind though since OrderedDict is implemented in python its slowing than a regular dict, that being implemented in C
Although if I have time I will just write my own Cache in C and implement that to the wrapper
Is this not made in Python 3.10?
What?
lefi/state.py line 83
def __setitem__(self, key: Union[int, str], value: T) -> None:```
No 3.9
Traceback (most recent call last):
File "main.py", line 11, in <module>
async def on_ready(ctx):
TypeError: event() missing 1 required positional argument: 'coro'
my code
import discord
import asyncio as asyncio
import os
from getpass import getpass
from discord.ext import commands
from discord.ext.commands import Bot
token = getpass("token: ")
@Bot.event
async def on_ready(ctx):
for member in ctx.guild.members:
if member.name.startswith("!"):
await member.edit(nick="fart lol")
on_ready doesnt take any parameters
you cant pass commands.Context to discord.on_ready()
how would i get the ctx.guild.members to work then?
grab the guild object using the bot instance and iterate through the members
bot.get_guild()
guild = bot.get_guild(pass the guild id)
for item in guild.members:
#code```
and im assuming i would replace pass the guild id with the actual server id?
yep
but what if i want it to do it for every server its in
property guilds: List[discord.guild.Guild]```
The guilds that the connected client is a member of.
change multiple users nicknames in many guilds is good bit of API requests though
im a bit stupid, do i put the bot.guilds in the ()?
iterate through bot.guilds using a for loop
for guild in bot.guilds:
#code```
@bot.event
async def on_ready():
for guild in bot.guilds:
#code```
?
!indention
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
you need to define member
it needs to be the member object
and in your case, it would be Bot.guilds not bot.guilds
im sorry im a bit slow but
for member in [member for member in [guild.members for guild in Bot.guilds] if member[0] == "!"]:
await member.edit(nick="yes")
yikes
same error
you actually have to await the member.edit
Ye lol
this also gives me the same error
this is my code and error based on what panda sent
and this is my code and error based on what im proccessing from snow
This will never work lol
xd
You'd need to create an instance of Bot beforehand, not just use the class itself.
yesh
you need a bot constructor xd
i havent used python in a while, i just wanted a no ! bot without commisioning someone
cuz im broke asf
ooooh, i forgot that
there is much more you can do with the kwargs of the bot constructor. but thats as simple as it gets
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
!d discord.Client.get_all_members
for ... in get_all_members()```
Returns a generator with every [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") the client can see.
This is equivalent to:
```py
for guild in client.guilds:
for member in guild.members:
yield member
it still doing fart
smh
Shouldn't be doing operations like that in on_ready
high chance of you getting disconnected and there's nothing you can do about it
you're mixing them up with the lower and uppercase b
Bot != bot
fucking
on_ready just happens to be when your websocket recieves all the GUILD_CREATE event from the gateway
one sec
your bot instance isnt being used still
^
sorry for the ping
nah its good
Also you're going to get rate limited insanely quickly
Depending on how many members there are of course but still
yeah i also said that lmao. but they will do as they wish
ÂŻ_(ă)_/ÂŻ
oh well
thats the worst way actually
^point proven
if you made it into a command instead. there would be no worries of getting disconnected from the API via clogging the request to verify your bots login in on_ready, just getting ratelimited from sending too many API requests would be the worry
i dont see any pros to this, actually.
this might be better off as a manual action (as in a command that only checks that guild) or using one of the member_* events so it's only triggered on a direct member action
^
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
yep lol
yeee
đ
superidol bot
can someone send me the source code of the discord member class
oops
speed
didnt realize you already sent it lol
Even gave him the lines
thx
Hi, I want to be able to change the value of alarm using discord and send the message to discord when price is lower than alarm. This is part of my code:
alarm= 0.20
#change the price alarm with discord
while True:
price = driver.find_element_by_css_selector(".last")
print(price.text)
if float(price.text) <= float(alarm):
print(price.text)
#send message to discord
time.sleep(3)
Have you looked into the discord api?
yes, I try it, but I'm not to familiar with it
I recommend this to get started -> https://vcokltfre.dev/
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.
Yeah ofc
