#discord-bots
1 messages ยท Page 55 of 1
not too customisable and heavy
gnome consumes 1-1.5gb memory on standby
for xfce its 500-900mb
the only annoying thing ive encountered is i cant add custom apps like discord into the favorites panel which is sad, i always need to check the dir and launch the executable
mhm ic, is their any tutorial on how to do the migration?
You can always do <link> so it wont get embeded lol, thanks
yeah i did the same in the edit cause there's no remove embeds option on phone
how would i edit a role name and color from a command
!d discord.Role.edit
await edit(*, name=..., permissions=..., colour=..., color=..., hoist=..., display_icon=..., mentionable=..., position=..., reason=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the role.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this.
All fields are optional.
Changed in version 1.4: Can now pass `int` to `colour` keyword-only parameter.
Changed in version 2.0: Edits are no longer in-place, the newly edited role is returned instead...
can't discord detect if someone is online through a python file for example and then ban it immediately and by that they get rid of self-bots
a lot of people use selfbots to do illegal stuff such as spamming
advertising
and so on
clinet.run(token, bot=False)
that doesnt exist anymore within the library.
im asking if discord is able to detect the places a disocrd user can log into an account through
what library
dpy
you can literally make another one
Im just sayin
Is it possible to create a bot that will notify me if too many users join my server in a certain amount of time?
for example, if more than 3 new members join in less than 1 minute, can i get a notification / temporarily block the users joining?
how cycle funtion work ?
i creating a russion - roullet game so i want first player1 play then second then again player1 till 6 bullets if a player die in beetween game complete
yes
that's why bots exist
make conditions and use time
yup use member join event ufff
its easy
event u can do so many other stuff
cool, thanks!
you can use next()
if you load the players into an iterable . You can call next() on it to cycle through the players. Alternatively, you could just cycle manually by having a list and popping and appending continuously through turns.
afaik not really
i have list = [palyer1 , player2]
is i use next()
it will only tigger 2 bullet
i need first player1 came then 2 then again 1 then 2 so on ..... till 6 times
oh
let me read your text again
still it will didnt work i thing
๐ค
I havent really used it before because I havent really had a use for it. However, its something I was told could be used in your situation. If I had to give an example that could apply to your situation without using it. It would be along the lines of:
player_list = [player1, player2]
for _ in range(6): # 6 total turns
selected_player = player_list.pop(0)
... # Do whatever here
player_list.append(selected_player)
For sure not a perfect example but
its all I got so 
works exactly in the way you want tho.
https://cdn.discordapp.com/attachments/821741267054493737/1012207189261299804/unknown.png
@sage otterthis working but if player = iter(["player1" , "player2"] it gives errors
ooo sory
let me read your text first
thats for sure a way to do it. Not very efficient tho.
hmm got it
Have you made sure that you installed discord.py to the same interpreter that your vscode uses for python?
E.g the one you install to might be 3.9 while the one your vscode uses is 3.10 for an example
???
it's not about vscode
What does this mean exactly
If you are running it from the vscode terminal it might matter
Also your linter seems to suggest it's missing as well
Which most commonly suggests an issue with Vscode using the wrong interpreter for python
i am not
Can you show how you install discord.py and how you run the file?
pip install discord?
and run it through PS
python file.py
is your file name is discord ?
no its not
Can you show the output of pip install discord? like all the messages returned to your terminal
๐ค
Also show the traceback from python file.py
my file name is the name in my rich presence on my profile does it matter because it has a symbol
Okay now show the traceback of python file.py
Keep in mind doing pip install discord will install a mirror but that isn't the cause of your issue so ignore that for now
@slate swan sadly i couldnt deploy xubuntu fully it was getting allot of errors and when it did the files were corrupted
Whats the point of xubuntu if you can just swap Gnome with XFCE
i was thinking about it but idk tbh
Im sure if you're having issues with Xubuntu installing XFCE will be way, way easier
i wasnt quite sure as my xfce session or xubuntu session were both crashing
Just install xfce using your package manager, logout of your ubuntu session and use your login manager to switch desktops
yeah i was thinking about it but im not sure due to my past issue with crashing of sessions and when they didnt crashed the corrupted files would come in play
Are you using bare metal or is this a VM?
Also could be an issue with graphic drivers
dualbooting currently, so "bare metal"
i did saw the issue of drivers, i also tried disconnecting my secondary monitor as it would cause some dual driver issues or something along the lines
I would suggest reading /var/log and looking for any XFCE entries to try to diagnose it then
ill reinstall xubuntu-desktop and ill see
And why even XFCE
Gnome should suffice, and it's easy as hell to rice
Not to mention there is also gnome shell extensions such as material shell
Which convert Gnome desktop into A tiling window manager
well idk, personally i dont have nothing against gnome and ubuntu the only thing that i dislike is the usage of memory and stutters for some reason maybe because its a fresh instalation i doubt it
If you want a lower memory footprint then gnome isn't a good choice, xfce is lite yea
But I would suggest, for the long run a tiling window manager itself
For an example, you would make a fresh install, then install, lets say BSPWM or I3 (or I3 gaps)
All you do from there is add anything extra, like notifications, bars etc
Then boom, you got yourself a super minimal desktop
to spare some back pain, i think ill probably just remove my ubuntu installation and probably use XFCE
@primal token why is hunter asking me if I know you?
Your gonna remove your distro installation and just use a desktop????
Or did you mean gnome and not ubuntu
what
dont even know who youre talking about honestly
@maiden fable him
i think ill probably just remove my "ubuntu installation" and probably use "XFCE"
well theyre both different distros right?
No

XFCE is a desktop enviorment
It's a package you download to use in your distro for desktops
Ubuntu is a distro itself
ah i see, guess im mixing stuff up
so gnome is a desktop environment itself i suppose?
yes
alright let me install XFCE then
its currently logging looping so ill try this
hello, how do I make my bot delete a certain message on a certain channel? python
can i turn off reply to orignal message in buttons ?
get the message and do await message.delete()
is that a followup?
then it's not possible
is there a way to delete a specific word like for example "hello" in a single channel and not the rest of the channels?
say i have two channels, and I don't want to have hello on one of the channels
I don't really get the idea, but if you want to just remove hello from the channel name, then you can check if 'hello' in channel.name: await channel.edit(name=channel.name.replace("hello", ""))
uhm, I don't think that is the topic of this channel
try asking somewhere else, where topic looks similar to what you're doing
i'll try to explain it as much as i can...
it's like blacklisting a message in a specific channel, wherein, you're allowed to message "hello" in one channel and when you type "hello" on a different channel, it gets deleted.
channel 1
- allowed to type hello and send it
channel 2
- not allowed to chat hello, it gets deleted
tbh, no idea
doesn't automod exist?
just ask
ok
How do you write code in Python?
Is how to write (if the result is greater than zero, do the command)
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
you cant help me ?
i changed the display manager for lightdm but still the same issue, ill probably troubleshoot it tomorrow, anyways thanks for the suggestions and help
Alright
I don't mean, can you find out this information from here?
My first thoughts on a ubuntu were pretty good, it didnt broke down 50 times like my windows installation kek
what? did you click that link and search for resources? For example if you choose beginner and book this book is first what pops up https://automatetheboringstuff.com/
And there is completely everything you need to learn python
ok thanks
client = commands.Bot(command_prefix = "!")
TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents'
whenever i try to run the bot that error shows up
it is suggesting that the commands.bot line has a problem
Add intents argument
wdym
!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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.
ahhh
client = commands.Bot(command_prefix = "!", intents=intents)
try it
it's a kwarg, so no
only the initialization of that variable has to be, since discord.Intents is a class
ah
client = commands.Bot(command_prefix = "!", intents=intents)
NameError: name 'intents' is not defined. Did you mean: 'Intents'?
error says it all
hmm
the first 3/4 lines matter too
lol
Does anyone know how to make a bot automatically delete it's message?
await ctx.message.delete()
!d discord.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other peopleโs messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
I'm talking about like the bot's own message
So basically for example, I use a command for the bot to send a message, then a couple seconds later the bot deletes the message it sent (not mine)
that will delete the message the bot sent
Oh okay thanks
This isn't working for me, it's deleting the command I send
What code
oh
Just do
await ctx.send('message', delete_after=2.0)
alr ill try it
remove the ctx.delete though
alr
It worked, thank you man I appreciate it :)
Np
I didn't know exactly what you wanted at the start my bad
No worries man
@client.command()
async def battle(ctx, *, member: discord.Member):
n1 = message_author
n2 = member
i1 = 100
i2 = 100
while i1 < 101:
ctx.send(f"{n1}'s health is: {i1}")
i1 = i1 - random.choice(range(-2, 35))
time.sleep(0.6)
ctx.send("--------------------------")
ctx.send(f"{n2}'s health is: {i2}")
i2 = i2 - random.choice(range(-2, 35))
time.sleep(0.6)
ctx.send("--------------------------")
if i1 <= 0 and i1 < i2:
ctx.send(f"{n1}'s health is: 0 DEAD")
break
elif i2 <= 0 and i2 < i1:
ctx.send(f"{n2}'s health is: 0 DEAD")
break
what do i use instead of message author
if i wanted to grab the user that uses the command
What's going on?```py
Traceback (most recent call last):
File "/home/runner/StarLight-Services/venv/lib/python3.8/site-packages/discord/ui/view.py", line 375, in _scheduled_task
await item.callback(interaction)
File "/home/runner/StarLight-Services/cogs/services.py", line 78, in ticket
view = ticket_creation(select.values[0], member)
File "/home/runner/StarLight-Services/cogs/services.py", line 26, in init
super().init(
File "/home/runner/StarLight-Services/venv/lib/python3.8/site-packages/discord/ui/modal.py", line 57, in init
self._weights = _ModalWeights(self._children)
File "/home/runner/StarLight-Services/venv/lib/python3.8/site-packages/discord/ui/modal.py", line 263, in init
self.add_item(item)
File "/home/runner/StarLight-Services/venv/lib/python3.8/site-packages/discord/ui/modal.py", line 280, in add_item
index = self.find_open_space(item)
File "/home/runner/StarLight-Services/venv/lib/python3.8/site-packages/discord/ui/modal.py", line 270, in find_open_space
raise ValueError("could not find open space for item")
ValueError: could not find open space for item
code
ctx.author?
class ticket_creation(discord.ui.Modal):
def __init__(self, ttype, member):
super().__init__(
(*[discord.ui.InputText(style = discord.InputTextStyle.long, label = i[0], placeholder = i[1], min_length = 2) for i in questions[ttype]]),
title = "Ticket Creation")
self.timeout = None
self.ttype = ttype
self.member = member
async def callback(self, interaction: discord.Interaction):
How many inputtext fields may a modal have?
As I know Modal only takes kwargs
and you are passing (*[discord.ui.InputText(style = discord.InputTextStyle.long, label = i[0], placeholder = i[1], min_length = 2) for i in questions[ttype]]
which doesnt even seem valid syntax
looks like you forgot close one )
oh no you didnt
sorry
The children isn't a kwarg, just args.
class discord.ui.Modal(*children, title, custom_id=None, timeout=None)
only takes kwargs
wait is that pycord or waht?
You bet
Not really, but do you know max children a modal can have?
and i never used pycord
unlimited?
gonna check on dev portal then
yeah it has limit @slate swan
it's 5
Yeah, thanks, that's the problem!
Which event comes on member timeout?
Can't find that
AttributeError: 'Bot' object has no attribute 'memcached'```
I dont know how to add memcached to Bot class
bot.memcached = ...
yes but what
anything you want
idk, seeing that first time
;-;
subclass bot?
dpy Bot has no memcached, if you wanna use it, just subclass the Bot and do self.memcached = MyCoolMemCached
still same error
i installed everything, even ubuntu memcached
my bot has no main file
how can I use memcached with dpy
since i always get error
What is memcached
simple mistake, its client.command()
is this a valid view ?
its just a view for button in message'
are you getting an error?
Why the hell is there such a big indent in for loop of the start method
yes in list player
my eyes
and follow pep8 pls
lol wait
Send the code i will run black on it for you
oh gimme a sec
you cant use self in classvars
Why is player a classvar !
Because that's genius
and why would you need to make it a list
The self outside of methods
no, sarth and okimii are genius
Nah this dude is
agreed
then how can i append author in list
This is so genius I feel like an idiot
.append()?
i mean add
๐
if you want to add more players then why is variable called player?
not players
ctx.message.author will return name
๐
๐
1 - ctx.author is same
๐
ye true
damn
2 - it returns Member / User object
ohh ok k got it
not name
wait....
got it i need that no problem
str(Member / User) = smth like mecool#3456
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
an user by an command
Follow?
Yes twitch
Use twitch API
send
you can follow me here: https://mybeautfultwichfollowlink
With aiohttp
Yes
Why the hell I said twitter at first
Lemme DM you
Guys how can I use โฎ๏ธ emoji in button emoji?
\โฎ๏ธ
But i got error
what error
I keep getting TypeError: expected token to be a str, received <class 'NoneType'> instead when trying to run my bot in vsc, I made sure I set the token env variable and everything but it still doesn't want to work even with putting the whole token in. Anyone has any ideas on what it might be?
your token is none
you either dont have it in env or have it with other name
on_message doesn't get ctx
do you think people would leak their tokens while asking for help here
so it should be client.send_message
a lot of them do
wtf is that
@silk fulcrum
What?
counting in programming starts with 0
thought its a thing lmao
class Help(discord.ui.View):
def __init__(self):
super().__init__(timeout=180)
self.page = 1
@discord.ui.button(label=None,style=discord.ButtonStyle.blurple,row=0,emoji=":left:")
async def left(self,interaction:discord.Interaction,button:discord.ui.Button):
self.page = self.page-1
if self.page < 1:
self.page = 1
await interaction.response.edit_message(content=f"page {self.page}", view=self)
@discord.ui.button(label=None,style=discord.ButtonStyle.blurple,row=0,emoji=":track_previous:")
async def md(self,interaction:discord.Interaction,button:discord.ui.Button):
await interaction.response.edit_message(content=None,view=self)
@discord.ui.button(label=None,style=discord.ButtonStyle.blurple,row=0,emoji=":right:")
async def right(self,interaction:discord.Interaction,button:discord.ui.Button):
self.page = self.page+1
if self.page > 8:
self.page = 8
await interaction.response.edit_message(content=f"page {self.page}", view=self)
how do i make it respond to certian messages without a command then
Hey @limber bison!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
await message.channel.send()?
@silk fulcrum
Laughs in Lua
How did you set the env var
in a .env file and then i loaded it into main
Could you show your files hierarchy
Aiohttp clientsession or Requests? Which is better for APIs? I personally have been using aiohttp clientsession but yesterday i shifted to vsc from replit and for some reason I cant have so many clientsessions ๐
Ayyyyyy master
If your file isn't named exactly .env you should parse filename as argument to load_dotenv(). Like this
dotenv.load_dotenv("token.env")```
๐
for bots aiohttp is obviously better since its async, and why would you need more than one session?
Idk master, i have so many commands that use different APIs, so I had so many clientsessions earlier when I was on replit but as you know last night I shifted to vsc and apparently it doesn't let me have those many clientsessions
I changed it but it still gave me the same typeerror
You should open one session and save it in the bot as a bot variable

Could you show contents of your token.env with token replaced or regenerated
So can I make one clientsession and request data from all the APIs?
I don't see why not
what is the problem?
Just asking ๐ฅฒ
You can
Ight i will try it then
insert token here
the parenthesis is just to show it here but in the code its just the token
Try removing the spaces around =
Yes yes
still the same
Also I see you renamed it to .env, have you removed an argument from load_dotenv?
its still this
is this pycharm or vsc?
vsc
Is this function executed before you getenv
yeah
Try printing entire os.environ after loading
Or, os.environ.get("TOKEN")
dotenv.load_dotenv(โ.envโ)
os.getenv(โTOKENโ)
when I printed the token it said None
You should use os.environ
That works as well
If you want KeyError raised yes
That won't raise a KeyError exception
!d os.environ
os.environ```
A [mapping](https://docs.python.org/3/glossary.html#term-mapping) object where keys and values are strings that represent the process environment. For example, `environ['HOME']` is the pathname of your home directory (on some platforms), and is equivalent to `getenv("HOME")` in C.
This mapping is captured the first time the [`os`](https://docs.python.org/3/library/os.html#module-os "os: Miscellaneous operating system interfaces.") module is imported, typically during Python startup as part of processing `site.py`. Changes to the environment made after this time are not reflected in [`os.environ`](https://docs.python.org/3/library/os.html#os.environ "os.environ"), except for changes made by modifying [`os.environ`](https://docs.python.org/3/library/os.html#os.environ "os.environ") directly.
This mapping may be used to modify the environment as well as query the environment. [`putenv()`](https://docs.python.org/3/library/os.html#os.putenv "os.putenv") will be called automatically when the mapping is modified.
!e py d = {"a": 10} d.get("a")
@vale wing :warning: Your 3.11 eval job has completed with return code 0.
[No output]
!d os.getenv
os.getenv(key, default=None)```
Return the value of the environment variable *key* if it exists, or *default* if it doesnโt. *key*, *default* and the result are str. Note that since [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") uses [`os.environ`](https://docs.python.org/3/library/os.html#os.environ "os.environ"), the mapping of [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") is similarly also captured on import, and the function may not reflect future environment changes.
On Unix, keys and values are decoded with [`sys.getfilesystemencoding()`](https://docs.python.org/3/library/sys.html#sys.getfilesystemencoding "sys.getfilesystemencoding") and `'surrogateescape'` error handler. Use [`os.getenvb()`](https://docs.python.org/3/library/os.html#os.getenvb "os.getenvb") if you would like to use a different encoding.
[Availability](https://docs.python.org/3/library/intro.html#availability): most flavors of Unix, Windows.
received None in terminal
you need to load the env file too
I did
What did you use to load the .env file
!e py d = {"a": 10} d.get("b")
@vale wing :warning: Your 3.11 eval job has completed with return code 0.
[No output]
get(key[, default])```
Return the value for *key* if *key* is in the dictionary, else *default*. If *default* is not given, it defaults to `None`, so that this method never raises a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "KeyError").
Ah heck
whats the filename of the env file?
Why was I sure it raises the error
.env
๐
Is it written in a line before the print
yes
Did you install it using py -m pip install python-dotenv
yeah i have it installed
U did load_dotenv(โ.envโ)?
is it in the same directory as the file you run?
it is in the same directory and I did install it correctly
I tried that and it still gave me the same thing
Try os.getenv(โTOKENโ)
!pypi python-dotenv
thats the same thing, won't make a change
@edgy maple try this
import dotenv
values = dotenv.dotenv_values(".env")
print(values)```
OrderedDict()
Is there not like a spotify api or something
the closing quotes are in next line for some strings.. is that because of your IDE?
That might just be word warping
yeah, then on_message event could be the issue
why would that be an error, these are only links
Or you have insufficient intents
It wouldnt, Itโ s just better approach to get a list of songs
Also you don't have to save https://open.spotify.com/track/ in each of the strings, you can put it in the sent string and save the track IDs with the song IDs in the list instead
@client.command()
async def abba(ctx):
abbasongs = ["https://open.spotify.com/track/2245x0g1ft0HC7sf79zbYN?si=a70500225cec458f ", "https://open.spotify.com/track/2TxCwUlqaOH3TIyJqGgR91?si=2deaa976e19e409f", "https://open.spotify.com/track/5pMmWfuL0FTGshYt7HVJ8P?si=3b499efd06f24e61", "https://open.spotify.com/track/1rMfDvE2C8ne8UZj847rKM?si=05ca598895564711", "https://open.spotify.com/track/0J2p4KYdr6Mg4ET6JPlbe1?si=bb96cae9955d4e3f", "https://open.spotify.com/track/762B4bOcXF7I2Y8UlKTyTy?si=f7c8b5ac3e0942a7", "https://open.spotify.com/track/29FNeqjOV2kPWGS55qhtGB?si=f3dc8d19271d4f5a", "https://open.spotify.com/track/2w6JXokk0F8i241Y8C0Mn6?si=1e9a3104a7474f6d", "https://open.spotify.com/track/1PtJclc46wTk367PlsU6Uj?si=58cce7e83cb84897", "https://open.spotify.com/track/08GOw3NsrJ0LsCCeyqzt3b?si=312019ebf1fb4033", "https://open.spotify.com/track/6zgtBUEkAfilJ2YEOvNexR?si=39cd2237592844dc", "https://open.spotify.com/track/1zZLRpTzRTqPQ7G7uxYI9Y?si=64e6197df7134cc2", "https://open.spotify.com/track/6TvxPS4fj4LUdjw2es4g21?si=793cdb07cd874d79", "https://open.spotify.com/track/2TxCwUlqaOH3TIyJqGgR91?si=01d194a029a748d5"]
song = random.choice(abbasongs)
await ctx.send(f"Here's some great :a: :b: :b: :a: song for ya \n {song}")
well check if you have an on_message event without process_commands , and turn message _content intent on if they are not already on
its actually right below it
what
Is windows 10 slow or is it just me?
That is an off-topic question
i don't understand what you mean by "turn message _content intent on if they are not already on"
[Button(label="ok", style= "3", emoji= "๐", custom_id= "button1"), Button(label="lol", style= "4", emoji= "๐", custom_id="button1"), Button)] ]) whats wrong is this ^
SyntaxError: closing parenthesis ')' does not match opening parenthesis '['
!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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.
You need to have intents.message_content = True going by this example
@brazen raft
do i just add that to my code
Why so strict?
You have a weird item like Button) in your list (the last item)
Yes
depends on your pc tbf
That depends on your code
You should name discord.ext.commands.Bot instances bot or something, so it's not misleading, because discord.Client is a thing
Just saying
then i have few @clientcommand and one on message event
Is it enabled in the developer portal
of course
What's the body of your on_message event
why are u hiding Ramsey
At the end of it you need to put await client.process_commands(message)
listen() is also a thing
What do you mean
@bot.listen()
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
similar to Cog.listener()
Yeah
still coming
@silk fulcrum [Button(label="ok", style= "3", emoji= "๐", custom_id= "button1"), Button(label="lol", style= "4", emoji= "๐", custom_id="button2")] ]) interaction = await client.wait_for("button_click", check = lambda i: i.custom_id == "button1") await interaction.send(content = "Button clicked", ephmeral=True) whats wrong in this ^
SyntaxError: closing parenthesis ')' does not match opening parenthesis '['
sheeh loks terrible
[
Button(
label="ok", style= "3", emoji= "๐", custom_id= "button1"
),
Button(
label="lol", style= "4", emoji= "๐", custom_id="button2"
)
]
])```
now see the problem?
sometimes you gotta do this to figure out what is problem with brackets
sus imposter bgm plays in the background
do you see the problem now?
whats the problem u only tell me
why are there these ]) brackets at the end?
@worn onyx
sed lyf always getting ignored
man the error itself is telling you the issue, parenthesis means brackets fyi
what is this? new to vsc ;-;
@silk fulcrum ๐
why only me?
i simplified your code
problem is obvious now
it's a warning that you have this error somewhere in your code
um
i am trying to run my code by clicking on the run button
thats when i am getting that thing
stll getting error
DUDE I LEGIT TOLD YOU WHAT TO DO
does it say the line? or smth else
code and error
if you changed something
if not - go find the problem
thats it
you've already been told what is it
is there anything in yourcode highlihted with red?
try running in console
ight
bruh my touchpad is dead
F
wait nvm startup problem, it was actually stuck ๐คก
how to detect if a message contains a specific word within a sentence whether it's lower or upper case
why do you even use code runner, just use your terminal
you can convert all of the text to lower of upper
!e print("SomE TexT".lower())
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
some text
and check if the lower string is in that string
lol
"word" in "sentence" ?
!e py print("word" in "sentence")
@silk fulcrum :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
hi
has anyone here ever used Cython for their Bot?
use client.listen()
what
!e print("M" in "Master")
it will work
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
python?
no, Cython
client.listen instead of on_message?
cpython?
dk wat dat is
no
I mean Cython and CPython are different things, "Cython"
if you don't know how to use in statement, consider learning more python
@client.listen()
async def(...)
...
@fresh iron
then no idea
!pip cython
๐ฆ
what would be the goal of that
speed up the Bot
90% of the code, which will be coming from discord.py's source code will not be cython compatible, so forget about speed
especially for things related to the voice client
how do i make it so that when i use a command, it will get my id and dump it in a json file?
rewrite needed ๐ฉ๐
?
are u using a json file as a sorta of database?
mhm
its temprory
use mypy... it would increase your speed by 4x-10x only by typehinting
okey
help
you can actually use any linter with strict typing and compile it with mypyc
https://mypyc.readthedocs.io/en/latest/
yeah but can i use on_message with that
yes
yes
he's 7 kilo btw 
๐น
wtf thats heavy
Okmi
thats CHUNKY
@silk fulcrum can i dm you master? ๐ฅบ
its cute so who cares?
I can't get the error on unwarn
are my DMs blocked or what?
that's cool, thx
anyone please help
why u r obsessed with okimii
!paste
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.
Why are you here go back to college
anyone please help I'll send the code rn
it doesn't unwarn and shows "string indices must be integers"
yes
um guys so i recently shifted to vsc from replit and am getting error with aiohttp.ClientSession apis, so it says it doesnt have any setup_hook and so i did this, dont even know whether this is right or wrong tbh
did what?
class Estelle(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
super().__init__(
command_prefix="?",
description="My Cool Bot!!!",
intents=intents,
strip_after_prefix=True,
case_insensitive=True
)
async def setup_hook(self):
self.session = aiohttp.ClientSession()
for cog in cogs:
await self.load_extension(cog)
please someone
๐ฅฒ
I pasted the code why does unwarn not work
Your cogs must have setup function
as in
check this example https://gist.github.com/Master326486/6cf48c1ca0509b98e673451e356ba625#setup-hook @cerulean shale
ight sensei
at the very bottom
you mean this?
async def setup(bot):
await bot.add_cog(Chatbot(bot))
but its already there for all the cogs ๐คก
oh ok
F
async def main():
bot = Estelle()
await bot.start()
@bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.online, activity=discord.Game('?help if you are lost '))
print("Bot is running.")
``` it is saying that bot is not defined....
bot is not defined, 100% percent
Because bot is defined in local scope
it's only defined inside your main function
you can make on_ready right inside of the bot btw
like that ```py
class MyBot(commands.Bot):
def init(self):
super().init(...)
async def on_ready(self):
...``` @cerulean shale
and btw dont change presence in on_ready
its bad
oh-
you can do that directly in bot constructor
but i have other commands too
@bot.command()
async def load(ctx, extension):
await bot.load_extension(f"cogs.{extension}")
await ctx.send('Loaded Cog!')
@bot.command()
async def unload(ctx, extension):
await bot.unload_extension(f"cogs.{extension}")
await ctx.send('Unloaded Cog!')
@bot.command()
async def reload(ctx, extension):
await bot.reload_extension(f"cogs.{extension}")
await ctx.send('Reloaded Cog!')
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"{ctx.message.author.mention} :x: You don't meet all the requirements to use this command.")
elif isinstance(error, commands.CommandOnCooldown):
#{:.nf}, n places the decimals
msg = '**Still on cooldown**, pls try again in **{:.0f}s**'.format(error.retry_after)
await ctx.send(msg)
elif isinstance(error, commands.MissingRequiredArgument) or isinstance(error, commands.BadArgument):
helper = str(ctx.invoked_subcommand) if ctx.invoked_subcommand else str(ctx.command)
await ctx.send(f'{ctx.author.name} The correct way of using that commands is: ')
await ctx.send_help(helper)
elif isinstance(error, commands.CommandNotFound):
await ctx.send("No command under that name is found.")
else:
print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
you should move them into cogs
these ones seem to be good to put in Owner cog
cool sensei
on_command_error can be put inside the Bot subclassing or in the cog too
as @commands.Cog.listener()
ight master
what's the problem? @slate swan
uwnarn doesn't work
error?
string indices must be integers
it just shows this
and here is the code
do you have an error handler?
discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is logged to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.
The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.10)").
Note
`on_error` will only be dispatched to [`Client.event()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.event "discord.Client.event").
It will not be received by [`Client.wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for"), or, if used, [Bots](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#ext-commands-api-bot) listeners such as [`listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen") or [`listener()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.listener "discord.ext.commands.Cog.listener").
Changed in version 2.0: The traceback is now logged rather than printed.
or on_command_error
nah
hm
no errors only that
I think this except triggers and you only do print(p)
it sends that in chat
there was a problem with resetting users warns
it doesn't reset warns
print(exception) only prints the description of exception
so how do I fix the thing
I tried that once it didn't work
there is something like traceback.print_exc(), but you can just do raise e
instead of print(e)
what?
how do I fixxxxxxxxxxxxx
bruh
didn't handle errors
do this
works for me
do I remove except Exception as e: print(e) await ctx.send(f"There was a problem with resetting {user_short}'s warns in {guild_name}") return and change it to that?
should show full traceback
why the heck did you do traceback.print_exc()
you told me bruh
it most likely exists but you'd need to import traceback for that
how to run code in terminal btw? ๐ฅฒ
I literally told you to do raise e
and what will that do?
yes
ight
so raise(e) ??
or python main.py
WHAT SHOULD I DO THEN
raise e
read what I'm saying
bruh how do I do that then
You saying raise e and saying not to do that at the same time bruh
..
he said raise(e) won't work, raise e will
raise e = what I said
sarth is always right
now it shows an error
and what is the error
[2022-08-25 14:49:25] [INFO ] discord.client: logging in using static token
[2022-08-25 14:49:29] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 9bfa18d8839c9edc1c7ea328ce0e0550).
Dragon Bot is ready to fly in Discord Life
{'users': [{'name': 'Pengu', 'reasons': ['a', 'test']}]}
[2022-08-25 14:49:45] [ERROR ] discord.ext.commands.bot: Ignoring exception in command unwarn
Traceback (most recent call last):
File "C:\Users\hp\PycharmProjects\Dragon_Bot\venv\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\hp\PycharmProjects\Dragon_Bot\main.py", line 373, in unwarn
raise e
File "C:\Users\hp\PycharmProjects\Dragon_Bot\main.py", line 364, in unwarn
if obj["name"] == user_short:
TypeError: string indices must be integers
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\hp\PycharmProjects\Dragon_Bot\venv\lib\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\hp\PycharmProjects\Dragon_Bot\venv\lib\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\hp\PycharmProjects\Dragon_Bot\venv\lib\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: string indices must be integers```
obj is a string
??
how do I fix the thing
@silk fulcrum how to close a session? is that the issue or is it something else?
then you look at what your my_list is
my friend did the warning system where is obj["name"]
oh I found
yeah I should've noted in my example to close the session in close of bot
so what do I change it to so that it worked?
that happens when your bot crashes with some internal error, for your case you did asyncio.run()
in main.py right
you can do py async def close(self): await session.close() await super().close()
inside the Bot subclass
ight got it
yep
@slate swan do you know what enumerate means?
yeah right ๐
waht
runtime error
then what does it mean?
its like list mention many things at once??
you have an already running event loop
await bot.http._HTTPClient__session.close() will close the connection
what?
what the heck is that
why self.session.close() is not enough?
I have no problems with it
even for aiohttp.ClientSession?
oh ok then
!d discord.Client.session is a thing?
No documentation found for the requested symbol.
um.... ๐ญ
dpy uses aiohttp for requests aswell
@silk fulcrum please just tell me how to fix it, it gives headache
he's subclassing
and what's the session variable there?
!e ```py
class A:
__b = "name mangling"
a = A()
print(a._A__b)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
name mangling
I don't even have clear understand of how to fix it, because I don't understand what do you want by using enumerate for a dict
my friend created the warning system
look lemme explain
import discord
import asyncio
import aiohttp
from discord.ext import commands
cogs = (
'cogs.chatbot',
'cogs.events',
'cogs.fun',
'cogs.minigames',
'cogs.misc',
'cogs.mod',
'cogs.nsfw',
'cogs.reactions',
'cogs.search',
'cogs.owner'
)
class Estelle(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
super().__init__(
command_prefix="?",
description="My Cool Bot!!!",
intents=intents,
strip_after_prefix=True,
case_insensitive=True
)
async def setup_hook(self):
self.session = aiohttp.ClientSession()
for cog in cogs:
await self.load_extension(cog)
async def close(self):
await session.close()
await super().close()
async def on_ready(self):
await bot.change_presence(status=discord.Status.online, activity=discord.Game('?help if you are lost '))
print("Bot is running.")
async def start(self):
await super().start("token")
async def main():
bot = Estelle()
await bot.start()
asyncio.run(main())
``` this is the code on main.py btw
await self.session.close()
I made a mistake
2?warn @slate swan and reason in here, it adds the warning to reports.json file and then warnings display the warnings but 2?unwarn should remove all warnings of the current user from reports.json
@silk fulcrum
nah its my mistake to copy it blindly, will be careful from now on ;-;
that is pretty understandable but that doesn't explain why the hell would you want to enumerate the dict to me
that error isn't coming from his session, it comes from discord.py's internal session
IT WAS MY FRIEND HE CREATED THE WARNING SYSTEM
I said this like 3 times
then how can i help you if you dont even know what your code does
I DONT KNOW WHAT UNWARN IS EVERYTHING ELSE I DO KNOW
hopefully your friend is not someone with a "how to create a warn system in discord.py" tutorial guy
ask him-
problem solved-
he's offline
you gonna leave earth in few hours?
๐
look I just need this code to remove users warnings from reports.json when you do 2?unwarn user
just wait for him to come online bruh
YES IM NOT FREE ALL DAY
noone is spoonfeeding you here
then do it tomorrow
or learn python
TOMMOROW SCHOOL STARTS ;/ PLUS BOT SHOULD BE OUT TODAY
how to read what the code does
you don't know the thing yourself
you should be able to read other code
btw um how to fix this, what does this even mean, something with the last asyncio.run(main()) right
not only writing your own
bruh whats the issue, tell again
enumerate is used to get index and value at the same time from LIST, i have no idea why would your friend do that for dict
dont just shout on others cause they are also trying to help you UNDERSTAND not DOING YOUR WORK FOR YOU
then how am I supposed to know bruh?
๐
THEY DON'T UNDERSTAND EITHER AND ARE ASKING ME WHY I CANT UNDERSTAND
why even make it if you dont know how?
ask your friend or rewrite your code
I'll rewrite ;/
stop shouting please
Send your code ffs ๐
am not
are
btw ;-;
.
@cerulean shale show the code that gives an error and the full traceback
that is probably the full traceback
but i dont see code
you may ask me why do I need the code again if you sent it like 5 mins ago
import discord
import http
import aiohttp
from discord.utils import get
from discord.ext import commands
from aiohttp import ClientSession
from main import Estelle
class Chatbot(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message):
cmdChannel = self.bot.get_channel(1008668481484500992)
inp = message.content
if message.author == self.bot.user:
return
elif message.channel.id != cmdChannel.id:
return
else:
await message.channel.typing()
async with aiohttp.ClientSession() as cs:
async with cs.get(f'https://api.popcat.xyz/chatbot?msg={inp}&owner=Ricky&botname=Estelle') as r:
res = await r.json()
await message.reply(f"{res['response']}")
async def setup(bot: Estelle):
await bot.add_cog(Chatbot(bot))
``` this is the code in chatbot.py
because some smart people change something to some shit because "this gave an error and i tried like that"
i didnt send it tbh ๐ this is the first time
for chatbot file yes
lmao
just use bot.run()
you''d need to launch your bot in other file
when you're inside an async function you can't use asyncio.run(..) (this doesn't even make sense) just await your coroutine
otherwise it will launch itself again when you import it
there is not problem with starting via asyncio.run()
the problem is with typehinting
typehinting has nothing to do with it :p
you can typehint a list as a discord.Client and the interpreter won't give a shit
not directly typehinting
he imports his bot instance from the bot file
and that runs the bot file again
so it tries to launch bot again
why tho lmao
that could lead to repeating commands if that was bot.run
because of my example in my gist(
that's what I do there
import the instance to typehint
i should just remove that
I just use launch.py to launch the bot, that's why my habit with importing the bot got me
import typing
if typing.TYPE_CHECKING:
from main import YourClass
class YourCog(commands.Cog): ...
def setup(bot: "YourClass"):
bot.add_cog(YourCog())
oh type_checking is actually usable here
setup should be asynchronous i forgor
;-;
gonna edit my example
msg is not defined
?
i dont see where is it defined
dont get ya
msg is not defined in that scope
ohh got it
@silk fulcrum ok so whats the issue again ๐ฅฒ
Event loop is closed
that in your cog instead of py from main import YourBotClass you need to do ```py
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from main import YourBotClass```
I am outside rn
ooooooh
Whatโs does this do
Oh ok
import typing
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from main import Estelle
``` is this right? cause i did it for every cog and saved it and yet it saying that estelle is not defined
actually no idea why
do from __future__ import annotations
does anyone have unwarn system?
TYPE_CHECKING is False so that condition will not be true
i think i got it, brb
bruh
tried to yoink code from friend but since it aint working, asking others for their code?
trying making it on your own and ask for help if you get any errors
TYPE_CHECKING doesn't do anything special, it just indicates to the reader that this class is being imported for type hinting purpose.
its basically if False: import ..., so you need to do the future import to make the annotation strs.
yoink? we were creating bot together bruh
and I'm asking for a code cuz there are lots of other errors for example on modmail that I have to fix so that didn't waste time
isn't it if True: import...? TYPE_CHECKING is false at runtime
๐คฆ
that's why I always worked on my bots alone
ayo master it works now btw, should do few changes and i will be completely shifted to vsc
no? the runtime argument is for type checkers as they don't run your code
discord.py 1.7.3 and discord.py 2.0 arent same just check the differences and try to make it worl
TYPE_CHECKING is always False
work*
ik
the docs says
A special constant that is assumed to be True by 3rd party static type checkers. It is False at runtime.
if TYPE_CHECKING:
...
doesn't this mean if TYPE_CHECKING is True: import...? (I'm just trying to understand)
"by 3rd party static type checkers", that means the python interpreter will not execute any code under that if, but if you use a 3rd part type checker like mypy, they will parse it and do their type checking thing
oh ok, now I understand, it's just for type hinting purpose, a normal import would create a circular import error right?
if you have a circular import then yes
hi guys
async def responsetime(ctx):
variable_list = [
'0000,4',
'3',
'0,1',
'00000000000000000000000000000000000000000000000,1',
]
embed = nextcord.Embed(
colour=0xc81f9f,
title="Rating",
description=f"it took {random.choice(variable_list)} seconds to respond to you"
)
await ctx.send(embed=embed)``` how can i add a rarity for 0,1?
yes
!d random.choices
random.choices(population, weights=None, *, cum_weights=None, k=1)```
Return a *k* sized list of elements chosen from the *population* with replacement. If the *population* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
If a *weights* sequence is specified, selections are made according to the relative weights. Alternatively, if a *cum\_weights* sequence is given, the selections are made according to the cumulative weights (perhaps computed using [`itertools.accumulate()`](https://docs.python.org/3/library/itertools.html#itertools.accumulate "itertools.accumulate")). For example, the relative weights `[10, 5, 30, 5]` are equivalent to the cumulative weights `[10, 15, 45, 50]`. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.
like that its more uncommon that 0,1 comes
can the on_member_remove be used for bans and kicks or it's some other event?
has weights
it can
cum? 
sounds good
cumulative
cumulative weights
ok
like they add up to prev weights
thanks
yo, pillow and pil are completely same or do they have any differences? ik that pillow is pil fork btw
PIL is no longer maintained iirc
well are they completely same? or are there any differences?
Do u mean Pillow?
why the bot's response for some commands is doubled
!pypi PIL
repeated twice
Oh, nvm
I always get confused ffs
Pil is such a hard library to install I stg
send code bruh
pil was the original lib, which has been left untouched since 2009 lmao
2009?!?
tf
Do u not know? They have to compile it themselves to install it :DDD
Ong
sorry, 2006
๐ญ
wasn't it just pip install pillow idk
Use HIM
easy_pil users: ๐ฟ
harvs imaging module 
It was sarcasm but cool
!pypi pillow
it's because i have an on_message event i think
not sure how to fix that without deleting the event
Register commands
Change the decorator
Or make it listen
From event to listen()
how about check message_content intents
tbh if someone uses commands.Bot without mention prefix or message_content Intents discord.py should log a warning
disnake does that iirc
Mention prefix??
!d discord.ext.commands.when_mentioned
discord.ext.commands.when_mentioned(bot, msg, /)```
A callable that implements a command prefix equivalent to being mentioned.
These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.
> Changed in version 2.0: `bot` and `msg` parameters are now positional-only.
>
>
Why would you throw a warning without a mention prefix
Why in python it try and except and not throw and catch
because whats the point of making commands that won't work ๐คก
from PIL import Image, ImageFont, ImageDraw, ImageOps this won't work? ;-;
because its not javascript
this is giving an error, PIL module is not found i installed pillow btw ๐
you need to install pillow my dear sir
. . .
This is why pillow is so ass because it doesnโt work half the time
uh is that an IDE or runtime warning?
if you're using VSCODE restart it
Use pycharm
this is cmd, i used terminal to installed it and it did but it wasnt working so i used cmd too
Venv ๐
i am literally shifting to vsc from replit, been working on that shi- for 2 days now and you want me to shift to pycharm? ๐คก
You used replit as your ide??? ๐ญ
i used to ๐คก
Pycharm is so easy to learn
i restarted it and yet it is showing the same error
Why are you clown emoji me
Damn you sexy ๐ฏ๐ฏ
cause i used replit, i feel like a clown
Mistake: you installed pillow
You should
My vscode doesnโt work
ok so in place of PIL i should write Pillow?
It just asks me to install python
No
then? ๐ญ
f
Tf??? Grass???? Python developer??? With grass???? Omg???? This crazy????
@frank lake
@slate swan ?
Bro where tf u at Iโve been sat here for an hour
What are u tralking about ?
you will probably get banned if you this kinda convo in here ๐คทโโ๏ธ
I don't know him
weird ppl got blocked

